Merge pull request #6904 from erikma/dev/erikmav/byteStringMemory
C#: Allow readonly view of byteString's data with ByteString.Memory property
diff --git a/.bazelignore b/.bazelignore
new file mode 100644
index 0000000..201f851
--- /dev/null
+++ b/.bazelignore
@@ -0,0 +1,3 @@
+# These are fetched as external repositories.
+third_party/benchmark
+third_party/googletest
diff --git a/.github/mergeable.yml b/.github/mergeable.yml
index c417001..a827eb7 100644
--- a/.github/mergeable.yml
+++ b/.github/mergeable.yml
@@ -9,10 +9,10 @@
- and:
- must_include:
regex: 'release notes: yes'
- message: 'Please include release note: yes'
+ message: 'Please include release notes: yes'
- must_include:
- regex: '^(c#|c\+\+|cleanup|conformance tests|integration|java|javascript|go|objective-c|php|python|ruby)'
- message: 'Please include at least a language label (e.g., c++, java, python). Or apply one of the following labels: cleanup, conformance tests, integration.'
+ regex: '^(c#|c\+\+|cleanup|conformance tests|integration|java|javascript|go|objective-c|php|python|ruby|bazel)'
+ message: 'Please include at least a language label (e.g., c++, java, python). Or apply one of the following labels: bazel, cleanup, conformance tests, integration.'
- must_include:
regex: 'release notes: no'
- message: 'Please include release note: no'
+ message: 'Please include release notes: no'
diff --git a/.gitignore b/.gitignore
index 4e909ae..0cbcf50 100644
--- a/.gitignore
+++ b/.gitignore
@@ -57,6 +57,7 @@
python/.eggs/
python/.tox
python/build/
+python/docs/_build/
src/js_embed
src/protoc
@@ -141,6 +142,8 @@
php/tests/protobuf/
php/tests/core
php/tests/vgcore*
+php/tests/multirequest.result
+php/tests/nohup.out
php/ext/google/protobuf/.libs/
php/ext/google/protobuf/Makefile.fragments
php/ext/google/protobuf/Makefile.global
diff --git a/.readthedocs.yml b/.readthedocs.yml
new file mode 100644
index 0000000..88f4c10
--- /dev/null
+++ b/.readthedocs.yml
@@ -0,0 +1,22 @@
+# .readthedocs.yml
+# Read the Docs configuration file
+# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
+
+# Required
+version: 2
+
+sphinx:
+ configuration: python/docs/conf.py
+ fail_on_warning: false
+
+# Setup build requirements for docs.
+# Use conda so that we can install the latest libprotobuf package without
+# having to build from scratch just for docs builds.
+conda:
+ environment: python/docs/environment.yml
+
+python:
+ version: 3.7
+ install:
+ - method: setuptools
+ path: python
diff --git a/BUILD b/BUILD
index f887912..8ab4cb4 100644
--- a/BUILD
+++ b/BUILD
@@ -1,25 +1,52 @@
# Bazel (https://bazel.build/) BUILD file for Protobuf.
-load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test", "objc_library")
-load("@rules_java//java:defs.bzl", "java_library")
+load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
+load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test", "objc_library", native_cc_proto_library = "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_lang_toolchain", "proto_library")
+load("@rules_proto//proto/private:native.bzl", "native_proto_common")
load("@rules_python//python:defs.bzl", "py_library")
+load(":cc_proto_blacklist_test.bzl", "cc_proto_blacklist_test")
licenses(["notice"])
exports_files(["LICENSE"])
################################################################################
-# Java 9 configuration
+# build configuration
################################################################################
+string_flag(
+ name = "incompatible_use_com_google_googletest",
+ # TODO(yannic): Flip to `true` for `3.13.0`.
+ build_setting_default = "false",
+ values = ["true", "false"]
+)
+
config_setting(
- name = "jdk9",
- values = {
- "java_toolchain": "@bazel_tools//tools/jdk:toolchain_jdk9",
+ name = "use_com_google_googletest",
+ flag_values = {
+ "//:incompatible_use_com_google_googletest": "true"
},
)
+GTEST = select({
+ "//:use_com_google_googletest": [
+ "@com_google_googletest//:gtest",
+ ],
+ "//conditions:default": [
+ "//external:gtest",
+ ],
+})
+
+GTEST_MAIN = select({
+ "//:use_com_google_googletest": [
+ "@com_google_googletest//:gtest_main",
+ ],
+ "//conditions:default": [
+ "//external:gtest_main",
+ ],
+})
+
################################################################################
# ZLIB configuration
################################################################################
@@ -68,6 +95,10 @@
create_compiler_config_setting(
name = "msvc",
value = "msvc-cl",
+ visibility = [
+ # Public, but Protobuf only visibility.
+ "//:__subpackages__",
+ ],
)
config_setting(
@@ -75,6 +106,10 @@
values = {
"crosstool_top": "//external:android/crosstool",
},
+ visibility = [
+ # Public, but Protobuf only visibility.
+ "//:__subpackages__",
+ ],
)
config_setting(
@@ -82,6 +117,10 @@
values = {
"crosstool_top": "@androidndk//:toolchain-libcpp",
},
+ visibility = [
+ # Public, but Protobuf only visibility.
+ "//:__subpackages__",
+ ],
)
config_setting(
@@ -89,6 +128,10 @@
values = {
"crosstool_top": "@androidndk//:toolchain-gnu-libstdcpp",
},
+ visibility = [
+ # Public, but Protobuf only visibility.
+ "//:__subpackages__",
+ ],
)
# Android and MSVC builds do not need to link in a separate pthread library.
@@ -108,6 +151,7 @@
load(
":protobuf.bzl",
+ "adapt_proto_library",
"cc_proto_library",
"internal_copied_filegroup",
"internal_gen_well_known_protos_java",
@@ -284,13 +328,15 @@
visibility = ["//visibility:public"],
)
-cc_proto_library(
+adapt_proto_library(
+ name = "cc_wkt_protos_genproto",
+ deps = [proto + "_proto" for proto in WELL_KNOWN_PROTO_MAP.keys()],
+ visibility = ["//visibility:public"],
+)
+
+cc_library(
name = "cc_wkt_protos",
- srcs = WELL_KNOWN_PROTOS,
- include = "src",
- default_runtime = ":protobuf",
- internal_bootstrap_hack = 1,
- protoc = ":protoc",
+ deprecation = "Only for backward compatibility. Do not use.",
visibility = ["//visibility:public"],
)
@@ -314,6 +360,17 @@
deps = [dep + "_proto" for dep in proto[1][1]],
) for proto in WELL_KNOWN_PROTO_MAP.items()]
+[native_cc_proto_library(
+ name = proto + "_cc_proto",
+ deps = [proto + "_proto"],
+ visibility = ["//visibility:private"],
+) for proto in WELL_KNOWN_PROTO_MAP.keys()]
+
+cc_proto_blacklist_test(
+ name = "cc_proto_blacklist_test",
+ deps = [proto + "_cc_proto" for proto in WELL_KNOWN_PROTO_MAP.keys()]
+)
+
################################################################################
# Protocol Buffers Compiler
################################################################################
@@ -467,6 +524,7 @@
"google/protobuf/unittest_proto3_arena.proto",
"google/protobuf/unittest_proto3_arena_lite.proto",
"google/protobuf/unittest_proto3_lite.proto",
+ "google/protobuf/unittest_proto3_optional.proto",
"google/protobuf/unittest_well_known_types.proto",
"google/protobuf/util/internal/testdata/anys.proto",
"google/protobuf/util/internal/testdata/books.proto",
@@ -516,8 +574,7 @@
deps = [
":protobuf",
":protoc_lib",
- "//external:gtest",
- ],
+ ] + GTEST,
)
cc_test(
@@ -529,8 +586,7 @@
],
deps = [
":protobuf_lite",
- "//external:gtest_main",
- ],
+ ] + GTEST_MAIN,
)
cc_test(
@@ -633,151 +689,49 @@
":cc_test_protos",
":protobuf",
":protoc_lib",
- "//external:gtest_main",
- ] + PROTOBUF_DEPS,
+ ] + PROTOBUF_DEPS + GTEST_MAIN,
)
################################################################################
# Java support
################################################################################
+
internal_gen_well_known_protos_java(
- srcs = WELL_KNOWN_PROTOS,
+ name = "gen_well_known_protos_java",
+ deps = [proto + "_proto" for proto in WELL_KNOWN_PROTO_MAP.keys()],
+ visibility = [
+ "//java:__subpackages__",
+ ],
)
-java_library(
+alias(
name = "protobuf_java",
- srcs = glob([
- "java/core/src/main/java/com/google/protobuf/*.java",
- ]) + [
- ":gen_well_known_protos_java",
- ],
- javacopts = select({
- "//:jdk9": ["--add-modules=jdk.unsupported"],
- "//conditions:default": [
- "-source 7",
- "-target 7",
- ],
- }),
+ actual = "//java/core",
visibility = ["//visibility:public"],
)
-java_library(
+alias(
name = "protobuf_javalite",
- srcs = [
- # Keep in sync with java/lite/pom.xml
- "java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java",
- "java/core/src/main/java/com/google/protobuf/AbstractParser.java",
- "java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java",
- "java/core/src/main/java/com/google/protobuf/AllocatedBuffer.java",
- "java/core/src/main/java/com/google/protobuf/Android.java",
- "java/core/src/main/java/com/google/protobuf/ArrayDecoders.java",
- "java/core/src/main/java/com/google/protobuf/BinaryReader.java",
- "java/core/src/main/java/com/google/protobuf/BinaryWriter.java",
- "java/core/src/main/java/com/google/protobuf/BooleanArrayList.java",
- "java/core/src/main/java/com/google/protobuf/BufferAllocator.java",
- "java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java",
- "java/core/src/main/java/com/google/protobuf/ByteOutput.java",
- "java/core/src/main/java/com/google/protobuf/ByteString.java",
- "java/core/src/main/java/com/google/protobuf/CodedInputStream.java",
- "java/core/src/main/java/com/google/protobuf/CodedInputStreamReader.java",
- "java/core/src/main/java/com/google/protobuf/CodedOutputStream.java",
- "java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java",
- "java/core/src/main/java/com/google/protobuf/DoubleArrayList.java",
- "java/core/src/main/java/com/google/protobuf/ExperimentalApi.java",
- "java/core/src/main/java/com/google/protobuf/ExtensionLite.java",
- "java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java",
- "java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java",
- "java/core/src/main/java/com/google/protobuf/ExtensionSchema.java",
- "java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java",
- "java/core/src/main/java/com/google/protobuf/ExtensionSchemas.java",
- "java/core/src/main/java/com/google/protobuf/FieldInfo.java",
- "java/core/src/main/java/com/google/protobuf/FieldSet.java",
- "java/core/src/main/java/com/google/protobuf/FieldType.java",
- "java/core/src/main/java/com/google/protobuf/FloatArrayList.java",
- "java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java",
- "java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java",
- "java/core/src/main/java/com/google/protobuf/IntArrayList.java",
- "java/core/src/main/java/com/google/protobuf/Internal.java",
- "java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java",
- "java/core/src/main/java/com/google/protobuf/IterableByteBufferInputStream.java",
- "java/core/src/main/java/com/google/protobuf/JavaType.java",
- "java/core/src/main/java/com/google/protobuf/LazyField.java",
- "java/core/src/main/java/com/google/protobuf/LazyFieldLite.java",
- "java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java",
- "java/core/src/main/java/com/google/protobuf/LazyStringList.java",
- "java/core/src/main/java/com/google/protobuf/ListFieldSchema.java",
- "java/core/src/main/java/com/google/protobuf/LongArrayList.java",
- "java/core/src/main/java/com/google/protobuf/ManifestSchemaFactory.java",
- "java/core/src/main/java/com/google/protobuf/MapEntryLite.java",
- "java/core/src/main/java/com/google/protobuf/MapFieldLite.java",
- "java/core/src/main/java/com/google/protobuf/MapFieldSchema.java",
- "java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java",
- "java/core/src/main/java/com/google/protobuf/MapFieldSchemas.java",
- "java/core/src/main/java/com/google/protobuf/MessageInfo.java",
- "java/core/src/main/java/com/google/protobuf/MessageInfoFactory.java",
- "java/core/src/main/java/com/google/protobuf/MessageLite.java",
- "java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java",
- "java/core/src/main/java/com/google/protobuf/MessageLiteToString.java",
- "java/core/src/main/java/com/google/protobuf/MessageSchema.java",
- "java/core/src/main/java/com/google/protobuf/MessageSetSchema.java",
- "java/core/src/main/java/com/google/protobuf/MutabilityOracle.java",
- "java/core/src/main/java/com/google/protobuf/NewInstanceSchema.java",
- "java/core/src/main/java/com/google/protobuf/NewInstanceSchemaLite.java",
- "java/core/src/main/java/com/google/protobuf/NewInstanceSchemas.java",
- "java/core/src/main/java/com/google/protobuf/NioByteString.java",
- "java/core/src/main/java/com/google/protobuf/OneofInfo.java",
- "java/core/src/main/java/com/google/protobuf/Parser.java",
- "java/core/src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java",
- "java/core/src/main/java/com/google/protobuf/ProtoSyntax.java",
- "java/core/src/main/java/com/google/protobuf/Protobuf.java",
- "java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java",
- "java/core/src/main/java/com/google/protobuf/ProtobufLists.java",
- "java/core/src/main/java/com/google/protobuf/ProtocolStringList.java",
- "java/core/src/main/java/com/google/protobuf/RawMessageInfo.java",
- "java/core/src/main/java/com/google/protobuf/Reader.java",
- "java/core/src/main/java/com/google/protobuf/RopeByteString.java",
- "java/core/src/main/java/com/google/protobuf/Schema.java",
- "java/core/src/main/java/com/google/protobuf/SchemaFactory.java",
- "java/core/src/main/java/com/google/protobuf/SchemaUtil.java",
- "java/core/src/main/java/com/google/protobuf/SmallSortedMap.java",
- "java/core/src/main/java/com/google/protobuf/StructuralMessageInfo.java",
- "java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java",
- "java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java",
- "java/core/src/main/java/com/google/protobuf/UnknownFieldSchema.java",
- "java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java",
- "java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java",
- "java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java",
- "java/core/src/main/java/com/google/protobuf/UnsafeUtil.java",
- "java/core/src/main/java/com/google/protobuf/Utf8.java",
- "java/core/src/main/java/com/google/protobuf/WireFormat.java",
- "java/core/src/main/java/com/google/protobuf/Writer.java",
- ],
- javacopts = select({
- "//:jdk9": ["--add-modules=jdk.unsupported"],
- "//conditions:default": [
- "-source 7",
- "-target 7",
- ],
- }),
+ actual = "//java/lite",
visibility = ["//visibility:public"],
)
-java_library(
+alias(
name = "protobuf_java_util",
- srcs = glob([
- "java/util/src/main/java/com/google/protobuf/util/*.java",
- ]),
- javacopts = [
- "-source 7",
- "-target 7",
- ],
+ actual = "//java/util",
visibility = ["//visibility:public"],
- deps = [
- "protobuf_java",
- "//external:error_prone_annotations",
- "//external:gson",
- "//external:guava",
- ],
+)
+
+alias(
+ name = "java_toolchain",
+ actual = "//java/core:toolchain",
+ visibility = ["//visibility:public"],
+)
+
+alias(
+ name = "javalite_toolchain",
+ actual = "//java/lite:toolchain",
+ visibility = ["//visibility:public"],
)
################################################################################
@@ -846,6 +800,10 @@
values = {
"define": "use_fast_cpp_protos=true",
},
+ visibility = [
+ # Public, but Protobuf only visibility.
+ "//:__subpackages__",
+ ],
)
config_setting(
@@ -853,6 +811,10 @@
values = {
"define": "allow_oversize_protos=true",
},
+ visibility = [
+ # Public, but Protobuf only visibility.
+ "//:__subpackages__",
+ ],
)
# Copy the builtin proto files from src/google/protobuf to
@@ -986,21 +948,18 @@
],
)
+# Note: We use `native_proto_common` here because we depend on an implementation-detail of
+# `proto_lang_toolchain`, which may not be available on `proto_common`.
+reject_blacklisted_files = hasattr(native_proto_common, "proto_lang_toolchain_rejects_files_do_not_use_or_we_will_break_you_without_mercy")
+cc_toolchain_blacklisted_protos = [proto + "_proto" for proto in WELL_KNOWN_PROTO_MAP.keys()] if reject_blacklisted_files else [":well_known_protos"]
proto_lang_toolchain(
name = "cc_toolchain",
- blacklisted_protos = [proto + "_proto" for proto in WELL_KNOWN_PROTO_MAP.keys()],
+ blacklisted_protos = cc_toolchain_blacklisted_protos,
command_line = "--cpp_out=$(OUT)",
runtime = ":protobuf",
visibility = ["//visibility:public"],
)
-proto_lang_toolchain(
- name = "java_toolchain",
- command_line = "--java_out=$(OUT)",
- runtime = ":protobuf_java",
- visibility = ["//visibility:public"],
-)
-
alias(
name = "objectivec",
actual = ":protobuf_objc",
diff --git a/CHANGES.txt b/CHANGES.txt
index 5aaee72..3179306 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,3 +1,200 @@
+2020-05-12 version 3.12.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+
+ Protocol Compiler
+ * [experimental] Singular, non-message typed fields in proto3 now support
+ presence tracking. This is enabled by adding the "optional" field label and
+ passing the --experimental_allow_proto3_optional flag to protoc.
+ * For usage info, see docs/field_presence.md.
+ * During this experimental phase, code generators should update to support
+ proto3 presence, see docs/implementing_proto3_presence.md for instructions.
+ * Allow duplicate symbol names when multiple descriptor sets are passed on
+ the command-line, to match the behavior when multiple .proto files are passed.
+ * Deterministic `protoc --descriptor_set_out` (#7175)
+
+ C++
+ * [experimental] Added proto3 presence support.
+ * New descriptor APIs to support proto3 presence.
+ * Enable Arenas by default on all .proto files.
+ * Documented that users are not allowed to subclass Message or MessageLite.
+ * Mark generated classes as final; inheriting from protos is strongly discouraged.
+ * Add stack overflow protection for text format with unknown fields.
+ * Add accessors for map key and value FieldDescriptors.
+ * Add FieldMaskUtil::FromFieldNumbers().
+ * MessageDifferencer: use ParsePartial() on Any fields so the diff does not
+ fail when there are missing required fields.
+ * ReflectionOps::Merge(): lookup messages in the right factory, if it can.
+ * Added Descriptor::WellKnownTypes enum and Descriptor::well_known_type()
+ accessor as an easier way of determining if a message is a Well-Known Type.
+ * Optimized RepeatedField::Add() when it is used in a loop.
+ * Made proto move/swap more efficient.
+ * De-virtualize the GetArena() method in MessageLite.
+ * Improves performance of json_stream_parser.cc by factor 1000 (#7230)
+ * bug: #7076 undefine Windows OUT and OPTIONAL macros (#7087)
+ * Fixed a bug in FieldDescriptor::DebugString() that would erroneously print
+ an "optional" label for a field in a oneof.
+ * Fix bug in parsing bool extensions that assumed they are always 1 byte.
+ * Fix off-by-one error in FieldOptions::ByteSize() when extensions are present.
+ * Clarified the comments to show an example of the difference between
+ Descriptor::extension and DescriptorPool::FindAllExtensions.
+ * Add a compiler option 'code_size' to force optimize_for=code_size on all
+ protos where this is possible.
+
+ Java
+ * [experimental] Added proto3 presence support.
+ * Mark java enum _VALUE constants as @Deprecated if the enum field is deprecated
+ * reduce <clinit> size for enums with allow_alias set to true.
+ * Sort map fields alphabetically by the field's key when printing textproto.
+ * TextFormat.merge() handles Any as top level type.
+ * Throw a descriptive IllegalArgumentException when calling
+ getValueDescriptor() on enum special value UNRECOGNIZED instead of
+ ArrayIndexOutOfBoundsException.
+ * Fixed an issue with JsonFormat.printer() where setting printingEnumsAsInts()
+ would override the configuration passed into includingDefaultValueFields().
+ * Implement overrides of indexOf() and contains() on primitive lists returned
+ for repeated fields to avoid autoboxing the list contents.
+ * Add overload to FieldMaskUtil.fromStringList that accepts a descriptor.
+ * [bazel] Move Java runtime/toolchains into //java (#7190)
+
+ Python
+ * [experimental] Added proto3 presence support.
+ * [experimental] fast import protobuf module, only works with cpp generated code linked in.
+ * Truncate 'float' fields to 4 bytes of precision in setters for pure-Python
+ implementation (C++ extension was already doing this).
+ * Fixed a memory leak in C++ bindings.
+ * Added a deprecation warning when code tries to create Descriptor objects
+ directly.
+ * Fix unintended comparison between bytes and string in descriptor.py.
+ * Avoid printing excess digits for float fields in TextFormat.
+ * Remove Python 2.5 syntax compatibility from the proto compiler generated _pb2.py module code.
+ * Drop 3.3, 3.4 and use single version docker images for all python tests (#7396)
+
+ JavaScript
+ * Fix js message pivot selection (#6813)
+
+ PHP
+ * Persistent Descriptor Pool (#6899)
+ * Implement lazy loading of php class for proto messages (#6911)
+ * Correct @return in Any.unpack docblock (#7089)
+ * Ignore unknown enum value when ignore_unknown specified (#7455)
+
+ Ruby
+ * [experimental] Implemented proto3 presence for Ruby. (#7406)
+ * Stop building binary gems for ruby <2.5 (#7453)
+ * Fix for wrappers with a zero value (#7195)
+ * Fix for JSON serialization of 0/empty-valued wrapper types (#7198)
+ * Call "Class#new" over rb_class_new_instance in decoding (#7352)
+ * Build extensions for Ruby 2.7 (#7027)
+ * assigning 'nil' to submessage should clear the field. (#7397)
+
+ C#
+ * [experimental] Add support for proto3 presence fields in C# (#7382)
+ * Mark GetOption API as obsolete and expose the "GetOptions()" method on descriptors instead (#7491)
+ * Remove Has/Clear members for C# message fields in proto2 (#7429)
+ * Enforce recursion depth checking for unknown fields (#7132)
+ * Fix conformance test failures for Google.Protobuf (#6910)
+ * Cleanup various bits of Google.Protobuf (#6674)
+ * Fix latest ArgumentException for C# extensions (#6938)
+ * Remove unnecessary branch from ReadTag (#7289)
+
+ Objective-C
+ * [experimental] ObjC Proto3 optional support (#7421)
+ * Block subclassing of generated classes (#7124)
+ * Use references to Obj C classes instead of names in descriptors. (#7026)
+ * Revisit how the WKTs are bundled with ObjC. (#7173)
+
+ Other
+ * Add a proto_lang_toolchain for javalite (#6882)
+ * [bazel] Update gtest and deprecate //external:{gtest,gtest_main} (#7237)
+ * Add application note for explicit presence tracking. (#7390)
+ * Howto doc for implementing proto3 presence in a code generator. (#7407)
+
+
+2020-02-14 version 3.11.4 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+
+ C#
+ * Fix latest ArgumentException for C# extensions (#7188)
+ * Enforce recursion depth checking for unknown fields (#7210)
+
+ Ruby
+ * Fix wrappers with a zero value (#7195)
+ * Fix JSON serialization of 0/empty-valued wrapper types (#7198)
+
+2020-01-31 version 3.11.3 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+
+ C++
+ * Add OUT and OPTIONAL to windows portability files (#7087)
+
+ PHP
+ * Refactored ulong to zend_ulong for php7.4 compatibility (#7147)
+ * Call register_class before getClass from desc to fix segfault (#7077)
+
+
+2019-12-10 version 3.11.2 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+
+ PHP
+ * Make c extension portable for php 7.4 (#6968)
+
+
+2019-12-02 version 3.11.1 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+
+ PHP
+ * Extern declare protobuf_globals (#6946)
+
+
+2019-11-19 version 3.11.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
+
+ C++
+ * Make serialization method naming consistent
+ * Make proto runtime + generated code free of deprecation warnings
+ * Moved ShutdownProtobufLibrary() to message_lite.h. For backward compatibility a declaration is still available in stubs/common.h, but users should prefer message_lite.h
+ * Removed non-namespace macro EXPECT_OK()
+ * Removed mathlimits.h from stubs in favor of using std::numeric_limits from C++11
+ * Fixed bug in parser when ending on a group tag
+ * Add a helper function to UnknownFieldSet to deal with the changing return value of message::unknown_fields()
+ * Fix incorrect use of string_view iterators
+ * Support direct pickling of nested messages
+ * Skip extension tag validation for MessageSet if unknown dependencies are allowed
+ * Updated deprecation macros to annotate deprecated code (#6612)
+ * Remove conversion warning in MapEntryFuncs::ByteSizeLong (#6766)
+ * Revert "Make shared libraries be able to link to MSVC static runtime libraries, so that VC runtime is not required." (#6914)
+
+ Java
+ * Remove the usage of MethodHandle, so that Android users prior to API version 26 can use protobuf-java
+ * Publish ProGuard config for javalite
+ * Fix for StrictMode disk read violation in ExtensionRegistryLite
+ * Include part of the ByteString's content in its toString().
+ * Include unknown fields when merging proto3 messages in Java lite builders
+
+ Python
+ * Add float_precision option in json format printer
+ * Optionally print bytes fields as messages in unknown fields, if possible
+ * FieldPath: fix testing IsSet on root path ''
+ * Experimental code gen (fast import protobuf module) which only work with cpp generated code linked in
+
+ JavaScript
+ * Remove guard for Symbol iterator for jspb.Map
+
+ PHP
+ * Avoid too much overhead in layout_init (#6716)
+ * Lazily Create Singular Wrapper Message (#6833)
+ * Implement lazy loading of php class for proto messages (#6911)
+
+ Ruby
+ * Ruby lazy wrappers optimization (#6797)
+
+ C#
+ * (RepeatedField): Capacity property to resize the internal array (#6530)
+ * Experimental proto2 support is now officially available (#4642, #5183, #5350, #5936)
+ * Getting started doc: https://github.com/protocolbuffers/protobuf/blob/master/docs/csharp/proto2.md
+ * Add length checks to ExtensionCollection (#6759)
+ * Optimize parsing of some primitive and wrapper types (#6843)
+ * Use 3 parameter Encoding.GetString for default string values (#6828)
+ * Change _Extensions property to normal body rather than expression (#6856)
+
+ Objective C
+ * Fixed unaligned reads for 32bit arm with newer Xcode versions (#6678)
+
+
2019-09-03 version 3.10.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
C++
@@ -213,7 +410,7 @@
* Introduce Proto C API.
* FindFileContainingSymbol in descriptor pool is now able to find field and enum values.
* reflection.MakeClass() and reflection.ParseMessage() are deprecated.
- * Added DescriptorPool.FindMethodByName() method in pure python (c extension alreay has it)
+ * Added DescriptorPool.FindMethodByName() method in pure python (c extension already has it)
* Flipped proto3 to preserve unknown fields by default.
* Added support for memoryview in python3 proto message parsing.
* Added MergeFrom for repeated scalar fields in c extension (pure python already has it)
@@ -376,7 +573,7 @@
PHP
* Fixed memory leak in C-extension implementation.
* Added discardUnknokwnFields API.
- * Removed duplicatd typedef in C-extension headers.
+ * Removed duplicated typedef in C-extension headers.
* Avoided calling private php methods (timelib_update_ts).
* Fixed Any.php to use fully-qualified name for DescriptorPool.
diff --git a/Makefile.am b/Makefile.am
index 8fd66c7..39c777c 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -68,6 +68,9 @@
csharp/protos/map_unittest_proto3.proto \
csharp/protos/old_extensions1.proto \
csharp/protos/old_extensions2.proto \
+ csharp/protos/unittest_issue6936_a.proto \
+ csharp/protos/unittest_issue6936_b.proto \
+ csharp/protos/unittest_issue6936_c.proto \
csharp/protos/unittest_custom_options_proto3.proto \
csharp/protos/unittest_import_public_proto3.proto \
csharp/protos/unittest_import_public.proto \
@@ -75,6 +78,7 @@
csharp/protos/unittest_import.proto \
csharp/protos/unittest_issues.proto \
csharp/protos/unittest_proto3.proto \
+ csharp/protos/unittest_selfreferential_options.proto \
csharp/protos/unittest.proto \
csharp/src/AddressBook/AddPerson.cs \
csharp/src/AddressBook/Addressbook.cs \
@@ -82,14 +86,15 @@
csharp/src/AddressBook/ListPeople.cs \
csharp/src/AddressBook/Program.cs \
csharp/src/AddressBook/SampleUsage.cs \
+ csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs \
csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs \
csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs \
csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj \
+ csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs \
+ csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs \
+ csharp/src/Google.Protobuf.Benchmarks/ParseRawPrimitivesBenchmark.cs \
csharp/src/Google.Protobuf.Benchmarks/Program.cs \
- csharp/src/Google.Protobuf.Benchmarks/SerializationBenchmark.cs \
- csharp/src/Google.Protobuf.Benchmarks/SerializationConfig.cs \
csharp/src/Google.Protobuf.Benchmarks/wrapper_benchmark_messages.proto \
- csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmark.cs \
csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmarkMessages.cs \
csharp/src/Google.Protobuf.Conformance/Conformance.cs \
csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj \
@@ -118,6 +123,10 @@
csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs \
csharp/src/Google.Protobuf.Test/JsonParserTest.cs \
csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs \
+ csharp/src/Google.Protobuf.Test/LegacyGeneratedCodeTest.cs \
+ csharp/src/Google.Protobuf.Test/MessageParsingHelpers.cs \
+ csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs \
+ csharp/src/Google.Protobuf.Test/ReadOnlySequenceFactory.cs \
csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs \
csharp/src/Google.Protobuf.Test/Reflection/DescriptorDeclarationTest.cs \
csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs \
@@ -128,6 +137,9 @@
csharp/src/Google.Protobuf.Test/SampleNaNs.cs \
csharp/src/Google.Protobuf.Test/TestCornerCases.cs \
csharp/src/Google.Protobuf.Test.TestProtos/Google.Protobuf.Test.TestProtos.csproj \
+ csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs \
+ csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936B.cs \
+ csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs \
csharp/src/Google.Protobuf.Test.TestProtos/ForeignMessagePartial.cs \
csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs \
csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions1.cs \
@@ -141,6 +153,8 @@
csharp/src/Google.Protobuf.Test.TestProtos/UnittestImport.cs \
csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs \
csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3.cs \
+ csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3Optional.cs \
+ csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs \
csharp/src/Google.Protobuf.Test.TestProtos/UnittestWellKnownTypes.cs \
csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs \
csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs \
@@ -173,6 +187,7 @@
csharp/src/Google.Protobuf/FieldMaskTree.cs \
csharp/src/Google.Protobuf/FrameworkPortability.cs \
csharp/src/Google.Protobuf/Google.Protobuf.csproj \
+ csharp/src/Google.Protobuf/IBufferMessage.cs \
csharp/src/Google.Protobuf/ICustomDiagnosticMessage.cs \
csharp/src/Google.Protobuf/IDeepCloneable.cs \
csharp/src/Google.Protobuf/IExtendableMessage.cs \
@@ -187,7 +202,13 @@
csharp/src/Google.Protobuf/MessageExtensions.cs \
csharp/src/Google.Protobuf/MessageParser.cs \
csharp/src/Google.Protobuf/ObjectIntPair.cs \
+ csharp/src/Google.Protobuf/ParseContext.cs \
+ csharp/src/Google.Protobuf/ParserInternalState.cs \
+ csharp/src/Google.Protobuf/ParsingPrimitives.cs \
+ csharp/src/Google.Protobuf/ParsingPrimitivesMessages.cs \
+ csharp/src/Google.Protobuf/ParsingPrimitivesWrappers.cs \
csharp/src/Google.Protobuf/ProtoPreconditions.cs \
+ csharp/src/Google.Protobuf/SegmentedBufferHelper.cs \
csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs \
csharp/src/Google.Protobuf/Reflection/CustomOptions.cs \
csharp/src/Google.Protobuf/Reflection/Descriptor.cs \
@@ -243,6 +264,7 @@
java_EXTRA_DIST= \
java/README.md \
java/bom/pom.xml \
+ java/core/BUILD \
java/core/generate-sources-build.xml \
java/core/generate-test-sources-build.xml \
java/core/pom.xml \
@@ -498,6 +520,7 @@
java/core/src/test/proto/com/google/protobuf/test_extra_interfaces.proto \
java/core/src/test/proto/com/google/protobuf/wrappers_test.proto \
java/lite.md \
+ java/lite/BUILD \
java/lite/generate-sources-build.xml \
java/lite/generate-test-sources-build.xml \
java/lite/lite.awk \
@@ -506,6 +529,7 @@
java/lite/src/test/java/com/google/protobuf/LiteTest.java \
java/lite/src/test/java/com/google/protobuf/Proto2MessageLiteInfoFactory.java \
java/pom.xml \
+ java/util/BUILD \
java/util/pom.xml \
java/util/src/main/java/com/google/protobuf/util/Durations.java \
java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java \
@@ -524,6 +548,7 @@
java/util/src/test/proto/com/google/protobuf/util/json_test.proto
objectivec_EXTRA_DIST= \
+ objectivec/.clang-format \
objectivec/DevTools/check_version_stamps.sh \
objectivec/DevTools/compile_testing_protos.sh \
objectivec/DevTools/full_mac_build.sh \
@@ -531,25 +556,19 @@
objectivec/DevTools/pddm_tests.py \
objectivec/generate_well_known_types.sh \
objectivec/google/protobuf/Any.pbobjc.h \
- objectivec/google/protobuf/Any.pbobjc.m \
objectivec/google/protobuf/Api.pbobjc.h \
- objectivec/google/protobuf/Api.pbobjc.m \
objectivec/google/protobuf/Duration.pbobjc.h \
- objectivec/google/protobuf/Duration.pbobjc.m \
objectivec/google/protobuf/Empty.pbobjc.h \
- objectivec/google/protobuf/Empty.pbobjc.m \
objectivec/google/protobuf/FieldMask.pbobjc.h \
- objectivec/google/protobuf/FieldMask.pbobjc.m \
objectivec/google/protobuf/SourceContext.pbobjc.h \
- objectivec/google/protobuf/SourceContext.pbobjc.m \
objectivec/google/protobuf/Struct.pbobjc.h \
- objectivec/google/protobuf/Struct.pbobjc.m \
objectivec/google/protobuf/Timestamp.pbobjc.h \
- objectivec/google/protobuf/Timestamp.pbobjc.m \
objectivec/google/protobuf/Type.pbobjc.h \
- objectivec/google/protobuf/Type.pbobjc.m \
objectivec/google/protobuf/Wrappers.pbobjc.h \
- objectivec/google/protobuf/Wrappers.pbobjc.m \
+ objectivec/GPBAny.pbobjc.h \
+ objectivec/GPBAny.pbobjc.m \
+ objectivec/GPBApi.pbobjc.h \
+ objectivec/GPBApi.pbobjc.m \
objectivec/GPBArray.h \
objectivec/GPBArray.m \
objectivec/GPBArray_PackagePrivate.h \
@@ -566,10 +585,16 @@
objectivec/GPBDictionary.h \
objectivec/GPBDictionary.m \
objectivec/GPBDictionary_PackagePrivate.h \
+ objectivec/GPBDuration.pbobjc.h \
+ objectivec/GPBDuration.pbobjc.m \
+ objectivec/GPBEmpty.pbobjc.h \
+ objectivec/GPBEmpty.pbobjc.m \
objectivec/GPBExtensionInternals.h \
objectivec/GPBExtensionInternals.m \
objectivec/GPBExtensionRegistry.h \
objectivec/GPBExtensionRegistry.m \
+ objectivec/GPBFieldMask.pbobjc.h \
+ objectivec/GPBFieldMask.pbobjc.m \
objectivec/GPBMessage.h \
objectivec/GPBMessage.m \
objectivec/GPBMessage_PackagePrivate.h \
@@ -580,6 +605,14 @@
objectivec/GPBRootObject.m \
objectivec/GPBRootObject_PackagePrivate.h \
objectivec/GPBRuntimeTypes.h \
+ objectivec/GPBSourceContext.pbobjc.h \
+ objectivec/GPBSourceContext.pbobjc.m \
+ objectivec/GPBStruct.pbobjc.h \
+ objectivec/GPBStruct.pbobjc.m \
+ objectivec/GPBTimestamp.pbobjc.h \
+ objectivec/GPBTimestamp.pbobjc.m \
+ objectivec/GPBType.pbobjc.h \
+ objectivec/GPBType.pbobjc.m \
objectivec/GPBUnknownField.h \
objectivec/GPBUnknownField.m \
objectivec/GPBUnknownField_PackagePrivate.h \
@@ -593,6 +626,8 @@
objectivec/GPBWellKnownTypes.m \
objectivec/GPBWireFormat.h \
objectivec/GPBWireFormat.m \
+ objectivec/GPBWrappers.pbobjc.h \
+ objectivec/GPBWrappers.pbobjc.m \
objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj \
objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata \
objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist \
@@ -681,6 +716,7 @@
objectivec/Tests/GPBDictionaryTests.m \
objectivec/Tests/GPBDictionaryTests.pddm \
objectivec/Tests/GPBExtensionRegistryTest.m \
+ objectivec/Tests/GPBMessageTests+ClassNames.m \
objectivec/Tests/GPBMessageTests+Merge.m \
objectivec/Tests/GPBMessageTests+Runtime.m \
objectivec/Tests/GPBMessageTests+Serialization.m \
@@ -877,6 +913,8 @@
php/tests/generated_service_test.php \
php/tests/map_field_test.php \
php/tests/memory_leak_test.php \
+ php/tests/multirequest.php \
+ php/tests/multirequest.sh \
php/tests/php_implementation_test.php \
php/tests/proto/empty/echo.proto \
php/tests/proto/test.proto \
@@ -953,6 +991,7 @@
python/google/protobuf/internal/service_reflection_test.py \
python/google/protobuf/internal/symbol_database_test.py \
python/google/protobuf/internal/test_bad_identifiers.proto \
+ python/google/protobuf/internal/test_proto3_optional.proto \
python/google/protobuf/internal/test_util.py \
python/google/protobuf/internal/testing_refleaks.py \
python/google/protobuf/internal/text_encoding_test.py \
@@ -1167,6 +1206,10 @@
js/data.proto \
js/debug.js \
js/debug_test.js \
+ js/experimental/runtime/kernel/message_set.js \
+ js/experimental/runtime/kernel/message_set_test.js \
+ js/experimental/runtime/kernel/tag.js \
+ js/experimental/runtime/kernel/tag_test.js \
js/gulpfile.js \
js/jasmine.json \
js/map.js \
@@ -1192,7 +1235,79 @@
js/test15.proto \
js/test_bootstrap.js \
js/testbinary.proto \
- js/testempty.proto
+ js/testempty.proto \
+ js/testlargenumbers.proto \
+ js/experimental/runtime/testing/jasmine_protobuf.js \
+ js/experimental/runtime/testing/ensure_custom_equality_test.js \
+ js/experimental/runtime/testing/binary/test_message.js \
+ js/experimental/runtime/kernel/writer_test.js \
+ js/experimental/runtime/kernel/writer.js \
+ js/experimental/runtime/kernel/wire_type.js \
+ js/experimental/runtime/kernel/uint8arrays_test.js \
+ js/experimental/runtime/kernel/uint8arrays.js \
+ js/experimental/runtime/kernel/uint32_test_pairs.js \
+ js/experimental/runtime/kernel/typed_arrays_test.js \
+ js/experimental/runtime/kernel/typed_arrays.js \
+ js/experimental/runtime/kernel/textencoding_test.js \
+ js/experimental/runtime/kernel/textencoding.js \
+ js/experimental/runtime/kernel/storage.js \
+ js/experimental/runtime/kernel/sint64_test_pairs.js \
+ js/experimental/runtime/kernel/sint32_test_pairs.js \
+ js/experimental/runtime/kernel/sfixed64_test_pairs.js \
+ js/experimental/runtime/kernel/sfixed32_test_pairs.js \
+ js/experimental/runtime/kernel/reader_test.js \
+ js/experimental/runtime/kernel/reader.js \
+ js/experimental/runtime/kernel/packed_uint32_test_pairs.js \
+ js/experimental/runtime/kernel/packed_sint64_test_pairs.js \
+ js/experimental/runtime/kernel/packed_sint32_test_pairs.js \
+ js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js \
+ js/experimental/runtime/kernel/packed_sfixed32_test_pairs.js \
+ js/experimental/runtime/kernel/packed_int64_test_pairs.js \
+ js/experimental/runtime/kernel/packed_int32_test_pairs.js \
+ js/experimental/runtime/kernel/packed_float_test_pairs.js \
+ js/experimental/runtime/kernel/packed_fixed32_test_pairs.js \
+ js/experimental/runtime/kernel/packed_double_test_pairs.js \
+ js/experimental/runtime/kernel/packed_bool_test_pairs.js \
+ js/experimental/runtime/kernel/kernel_test.js \
+ js/experimental/runtime/kernel/kernel_repeated_test.js \
+ js/experimental/runtime/kernel/kernel_compatibility_test.js \
+ js/experimental/runtime/kernel/kernel.js \
+ js/experimental/runtime/kernel/internal_message.js \
+ js/experimental/runtime/kernel/int64_test_pairs.js \
+ js/experimental/runtime/kernel/int32_test_pairs.js \
+ js/experimental/runtime/kernel/indexer_test.js \
+ js/experimental/runtime/kernel/indexer.js \
+ js/experimental/runtime/kernel/float_test_pairs.js \
+ js/experimental/runtime/kernel/fixed32_test_pairs.js \
+ js/experimental/runtime/kernel/field.js \
+ js/experimental/runtime/kernel/double_test_pairs.js \
+ js/experimental/runtime/kernel/conformance/wire_format.js \
+ js/experimental/runtime/kernel/conformance/test_all_types_proto3.js \
+ js/experimental/runtime/kernel/conformance/test_all_types_proto2.js \
+ js/experimental/runtime/kernel/conformance/conformance_testee_runner_node.js \
+ js/experimental/runtime/kernel/conformance/conformance_testee.js \
+ js/experimental/runtime/kernel/conformance/conformance_response.js \
+ js/experimental/runtime/kernel/conformance/conformance_request.js \
+ js/experimental/runtime/kernel/buffer_decoder_test.js \
+ js/experimental/runtime/kernel/buffer_decoder_helper.js \
+ js/experimental/runtime/kernel/buffer_decoder.js \
+ js/experimental/runtime/kernel/bool_test_pairs.js \
+ js/experimental/runtime/kernel/binary_storage_test.js \
+ js/experimental/runtime/kernel/binary_storage.js \
+ js/experimental/runtime/internal/checks_test.js \
+ js/experimental/runtime/internal/checks.js \
+ js/experimental/runtime/int64_test.js \
+ js/experimental/runtime/int64.js \
+ js/experimental/runtime/bytestring_test.js \
+ js/experimental/runtime/bytestring_internal.js \
+ js/experimental/runtime/bytestring.js \
+ js/experimental/benchmarks/code_size/kernel/popular_types.js \
+ js/experimental/benchmarks/code_size/kernel/all_types.js \
+ js/experimental/benchmarks/code_size/code_size_base.js \
+ js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js \
+ js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto2.js \
+ js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js \
+ js/experimental/benchmarks/code_size/apps_jspb/all_types_proto2.js
all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST)
@@ -1208,7 +1323,7 @@
WORKSPACE \
cmake/CMakeLists.txt \
cmake/README.md \
- cmake/conformance.cmake \
+ cmake/conformance.cmake \
cmake/examples.cmake \
cmake/extract_includes.bat.in \
cmake/install.cmake \
@@ -1225,6 +1340,8 @@
cmake/tests.cmake \
cmake/version.rc.in \
compiler_config_setting.bzl \
+ build_files_updated_unittest.sh \
+ cc_proto_blacklist_test.bzl \
editors/README.txt \
editors/proto.vim \
editors/protobuf-mode.el \
diff --git a/Protobuf-C++.podspec b/Protobuf-C++.podspec
index 63909d3..f6536fd 100644
--- a/Protobuf-C++.podspec
+++ b/Protobuf-C++.podspec
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'Protobuf-C++'
- s.version = '3.11.0-rc1'
+ s.version = '3.12.0-rc2'
s.summary = 'Protocol Buffers v3 runtime library for C++.'
s.homepage = 'https://github.com/google/protobuf'
s.license = '3-Clause BSD License'
diff --git a/Protobuf.podspec b/Protobuf.podspec
index a4b3f4b..5fe982a 100644
--- a/Protobuf.podspec
+++ b/Protobuf.podspec
@@ -5,28 +5,27 @@
# dependent projects use the :git notation to refer to the library.
Pod::Spec.new do |s|
s.name = 'Protobuf'
- s.version = '3.11.0-rc1'
+ s.version = '3.12.0-rc2'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
s.homepage = 'https://github.com/protocolbuffers/protobuf'
s.license = '3-Clause BSD License'
s.authors = { 'The Protocol Buffers contributors' => 'protobuf@googlegroups.com' }
s.cocoapods_version = '>= 1.0'
- s.module_name = 'protobuf'
s.source = { :git => 'https://github.com/protocolbuffers/protobuf.git',
:tag => "v#{s.version}" }
s.source_files = 'objectivec/*.{h,m}',
- 'objectivec/google/protobuf/Any.pbobjc.{h,m}',
- 'objectivec/google/protobuf/Api.pbobjc.{h,m}',
- 'objectivec/google/protobuf/Duration.pbobjc.{h,m}',
- 'objectivec/google/protobuf/Empty.pbobjc.{h,m}',
- 'objectivec/google/protobuf/FieldMask.pbobjc.{h,m}',
- 'objectivec/google/protobuf/SourceContext.pbobjc.{h,m}',
- 'objectivec/google/protobuf/Struct.pbobjc.{h,m}',
- 'objectivec/google/protobuf/Timestamp.pbobjc.{h,m}',
- 'objectivec/google/protobuf/Type.pbobjc.{h,m}',
- 'objectivec/google/protobuf/Wrappers.pbobjc.{h,m}'
+ 'objectivec/google/protobuf/Any.pbobjc.h',
+ 'objectivec/google/protobuf/Api.pbobjc.h',
+ 'objectivec/google/protobuf/Duration.pbobjc.h',
+ 'objectivec/google/protobuf/Empty.pbobjc.h',
+ 'objectivec/google/protobuf/FieldMask.pbobjc.h',
+ 'objectivec/google/protobuf/SourceContext.pbobjc.h',
+ 'objectivec/google/protobuf/Struct.pbobjc.h',
+ 'objectivec/google/protobuf/Timestamp.pbobjc.h',
+ 'objectivec/google/protobuf/Type.pbobjc.h',
+ 'objectivec/google/protobuf/Wrappers.pbobjc.h'
# The following would cause duplicate symbol definitions. GPBProtocolBuffers is expected to be
# left out, as it's an umbrella implementation file.
s.exclude_files = 'objectivec/GPBProtocolBuffers.m'
diff --git a/README.md b/README.md
index 0e5ae61..2f42c6c 100644
--- a/README.md
+++ b/README.md
@@ -56,7 +56,7 @@
|--------------------------------------|-------------------------------------------------------------|--------|-------|---------|
| C++ (include C++ runtime and protoc) | [src](src) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fbazel%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fdist_install%2Fcontinuous) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) | [](https://ci.appveyor.com/project/protobuf/protobuf) |
| Java | [java](java) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_compatibility%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_jdk7%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_oracle7%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_linkage_monitor%2Fcontinuous) | | |
-| Python | [python](python) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython27%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython33%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython34%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython35%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython36%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython37%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython27_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython33_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython34_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython35_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython36_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython37_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_release%2Fcontinuous) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_release%2Fcontinuous) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fwindows%2Fpython_release%2Fcontinuous) |
+| Python | [python](python) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython27%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython35%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython36%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython37%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython27_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython35_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython36_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython37_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_release%2Fcontinuous) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_release%2Fcontinuous) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fwindows%2Fpython_release%2Fcontinuous) |
| Objective-C | [objectivec](objectivec) | | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_cocoapods_integration%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_debug%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_release%2Fcontinuous)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_osx%2Fcontinuous) | |
| C# | [csharp](csharp) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcsharp%2Fcontinuous) | | [](https://ci.appveyor.com/project/protobuf/protobuf)<br/>[](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fwindows%2Fcsharp_release%2Fcontinuous) |
| JavaScript | [js](js) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjavascript%2Fcontinuous) | [](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjavascript%2Fcontinuous) | |
diff --git a/WORKSPACE b/WORKSPACE
index 35ef1d5..cb16ae8 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -1,13 +1,20 @@
workspace(name = "com_google_protobuf")
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+
local_repository(
name = "com_google_protobuf_examples",
path = "examples",
)
-local_repository(
- name = "submodule_gmock",
- path = "third_party/googletest",
+http_archive(
+ name = "com_google_googletest",
+ sha256 = "9dc9157a9a1551ec7a7e43daea9a694a0bb5fb8bec81235d8a1e6ef64c716dcb",
+ strip_prefix = "googletest-release-1.10.0",
+ urls = [
+ "https://mirror.bazel.build/github.com/google/googletest/archive/release-1.10.0.tar.gz",
+ "https://github.com/google/googletest/archive/release-1.10.0.tar.gz",
+ ],
)
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
@@ -15,25 +22,33 @@
# Load common dependencies.
protobuf_deps()
+load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
bind(
name = "python_headers",
actual = "//util/python:python_headers",
)
+# TODO(yannic): Remove in 3.13.0.
bind(
name = "gtest",
- actual = "@submodule_gmock//:gtest",
+ actual = "@com_google_googletest//:gtest",
)
+# TODO(yannic): Remove in 3.13.0.
bind(
name = "gtest_main",
- actual = "@submodule_gmock//:gtest_main",
+ actual = "@com_google_googletest//:gtest_main",
)
-maven_jar(
+jvm_maven_import_external(
name = "guava_maven",
artifact = "com.google.guava:guava:18.0",
+ artifact_sha256 = "d664fbfc03d2e5ce9cab2a44fb01f1d0bf9dfebeccc1a473b1f9ea31f79f6f99",
+ server_urls = [
+ "https://jcenter.bintray.com/",
+ "https://repo1.maven.org/maven2",
+ ],
)
bind(
@@ -41,9 +56,14 @@
actual = "@guava_maven//jar",
)
-maven_jar(
+jvm_maven_import_external(
name = "gson_maven",
artifact = "com.google.code.gson:gson:2.7",
+ artifact_sha256 = "2d43eb5ea9e133d2ee2405cc14f5ee08951b8361302fdd93494a3a997b508d32",
+ server_urls = [
+ "https://jcenter.bintray.com/",
+ "https://repo1.maven.org/maven2",
+ ],
)
bind(
@@ -51,12 +71,22 @@
actual = "@gson_maven//jar",
)
-maven_jar(
+jvm_maven_import_external(
name = "error_prone_annotations_maven",
artifact = "com.google.errorprone:error_prone_annotations:2.3.2",
+ artifact_sha256 = "357cd6cfb067c969226c442451502aee13800a24e950fdfde77bcdb4565a668d",
+ server_urls = [
+ "https://jcenter.bintray.com/",
+ "https://repo1.maven.org/maven2",
+ ],
)
bind(
name = "error_prone_annotations",
actual = "@error_prone_annotations_maven//jar",
)
+
+# For `cc_proto_blacklist_test`.
+load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
+
+bazel_skylib_workspace()
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 9711fa1..436c148 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -16,7 +16,7 @@
You need to install [cmake](https://cmake.org/) before building the benchmark.
We are using [google/benchmark](https://github.com/google/benchmark) as the
-benchmark tool for testing cpp. This will be automaticly made during build the
+benchmark tool for testing cpp. This will be automatically made during build the
cpp benchmark.
The cpp protobuf performance can be improved by linking with [tcmalloc library](
@@ -28,7 +28,7 @@
We're using maven to build the java benchmarks, which is the same as to build
the Java protobuf. There're no other tools need to install. We're using
[google/caliper](https://github.com/google/caliper) as benchmark tool, which
-can be automaticly included by maven.
+can be automatically included by maven.
### Python
We're using python C++ API for testing the generated
@@ -59,7 +59,7 @@
The second command adds the `bin` directory to your `PATH` so that `protoc` can locate the plugin later.
### PHP
-PHP benchmark's requirement is the same as PHP protobuf's requirements. The benchmark will automaticly
+PHP benchmark's requirement is the same as PHP protobuf's requirements. The benchmark will automatically
include PHP protobuf's src and build the c extension if required.
### Node.js
@@ -168,7 +168,7 @@
### Python:
-For Python benchmark we have `--json` for outputing the json result
+For Python benchmark we have `--json` for outputting the json result
#### Pure Python:
diff --git a/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto b/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto
index 2126190..e404b9f 100644
--- a/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto
+++ b/benchmarks/datasets/google_message1/proto2/benchmark_message1_proto2.proto
@@ -1,3 +1,33 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
// Benchmark messages for proto2.
syntax = "proto2";
diff --git a/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto b/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto
index 090b554..8aee2f6 100644
--- a/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto
+++ b/benchmarks/datasets/google_message1/proto3/benchmark_message1_proto3.proto
@@ -1,3 +1,33 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
// Benchmark messages for proto3.
syntax = "proto3";
diff --git a/benchmarks/datasets/google_message2/benchmark_message2.proto b/benchmarks/datasets/google_message2/benchmark_message2.proto
index 820630e..500c5d6 100644
--- a/benchmarks/datasets/google_message2/benchmark_message2.proto
+++ b/benchmarks/datasets/google_message2/benchmark_message2.proto
@@ -1,3 +1,35 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// LINT: ALLOW_GROUPS
+
// Benchmark messages for proto2.
syntax = "proto2";
diff --git a/benchmarks/datasets/google_message3/benchmark_message3.proto b/benchmarks/datasets/google_message3/benchmark_message3.proto
index d6f0d14..82422f9 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3.proto
@@ -1,5 +1,39 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message3;
+
import "datasets/google_message3/benchmark_message3_1.proto";
import "datasets/google_message3/benchmark_message3_2.proto";
import "datasets/google_message3/benchmark_message3_3.proto";
@@ -7,7 +41,6 @@
import "datasets/google_message3/benchmark_message3_5.proto";
import "datasets/google_message3/benchmark_message3_7.proto";
import "datasets/google_message3/benchmark_message3_8.proto";
-package benchmarks.google_message3;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
@@ -531,4 +564,3 @@
repeated .benchmarks.google_message3.Message0 field17617 = 1080;
repeated int32 field17618 = 1084;
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_1.proto b/benchmarks/datasets/google_message3/benchmark_message3_1.proto
index 3219553..1ee5c9e 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_1.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_1.proto
@@ -1,11 +1,44 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message3;
+
import "datasets/google_message3/benchmark_message3_2.proto";
import "datasets/google_message3/benchmark_message3_3.proto";
import "datasets/google_message3/benchmark_message3_5.proto";
import "datasets/google_message3/benchmark_message3_7.proto";
import "datasets/google_message3/benchmark_message3_8.proto";
-package benchmarks.google_message3;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
@@ -100,15 +133,13 @@
optional int32 field37047 = 115;
optional int32 field37048 = 157;
}
- repeated group Message36878 = 168 {
- }
+ repeated group Message36878 = 168 {}
repeated group Message36879 = 55 {
required string field37050 = 56;
optional int32 field37051 = 69;
}
repeated .benchmarks.google_message3.UnusedEmptyMessage field36984 = 78;
- optional group Message36880 = 137 {
- }
+ optional group Message36880 = 137 {}
optional uint64 field36986 = 59;
optional bytes field36987 = 121;
optional .benchmarks.google_message3.UnusedEmptyMessage field36988 = 2;
@@ -124,11 +155,9 @@
optional int32 field36998 = 47;
optional int32 field36999 = 48;
optional .benchmarks.google_message3.UnusedEmptyMessage field37000 = 68;
- repeated group Message36881 = 23 {
- }
+ repeated group Message36881 = 23 {}
optional .benchmarks.google_message3.Message4144 field37002 = 125;
- repeated group Message36882 = 35 {
- }
+ repeated group Message36882 = 35 {}
optional .benchmarks.google_message3.UnusedEmptyMessage field37004 = 49;
optional .benchmarks.google_message3.Message18921 field37005 = 52;
optional .benchmarks.google_message3.Message36858 field37006 = 46;
@@ -141,20 +170,15 @@
optional .benchmarks.google_message3.Message0 field37013 = 143;
optional .benchmarks.google_message3.UnusedEmptyMessage field37014 = 53;
optional .benchmarks.google_message3.Message36869 field37015 = 15;
- optional group Message36883 = 3 {
- }
- repeated group Message36884 = 16 {
- }
- repeated group Message36885 = 27 {
- }
- optional group Message36886 = 32 {
- }
+ optional group Message36883 = 3 {}
+ repeated group Message36884 = 16 {}
+ repeated group Message36885 = 27 {}
+ optional group Message36886 = 32 {}
repeated .benchmarks.google_message3.UnusedEnum field37020 = 71;
repeated int32 field37021 = 70;
optional .benchmarks.google_message3.UnusedEmptyMessage field37022 = 66;
optional .benchmarks.google_message3.Message13090 field37023 = 67;
- optional group Message36887 = 62 {
- }
+ optional group Message36887 = 62 {}
repeated .benchmarks.google_message3.Message10155 field37025 = 50;
repeated .benchmarks.google_message3.Message11874 field37026 = 151;
optional string field37027 = 12;
@@ -202,8 +226,7 @@
optional int32 field37118 = 160;
repeated string field37119 = 161;
}
- repeated group Message36910 = 119 {
- }
+ repeated group Message36910 = 119 {}
optional group Message36911 = 126 {
optional .benchmarks.google_message3.UnusedEmptyMessage field37121 = 127;
optional .benchmarks.google_message3.Message35538 field37122 = 130;
@@ -217,11 +240,9 @@
optional .benchmarks.google_message3.UnusedEmptyMessage field37042 = 155;
}
-message Message1328 {
-}
+message Message1328 {}
-message Message6850 {
-}
+message Message6850 {}
message Message6863 {
optional .benchmarks.google_message3.Enum6858 field6931 = 1;
@@ -259,8 +280,7 @@
optional bool field6963 = 34;
}
-message Message6871 {
-}
+message Message6871 {}
message Message7547 {
required bytes field7549 = 1;
@@ -282,8 +302,7 @@
optional bool field7680 = 12;
}
-message Message7865 {
-}
+message Message7865 {}
message Message7928 {
optional string field7940 = 1;
@@ -1277,4 +1296,3 @@
optional .benchmarks.google_message3.Message16945 field17025 = 22068132;
}
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_2.proto b/benchmarks/datasets/google_message3/benchmark_message3_2.proto
index 7ab993b..d123a72 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_2.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_2.proto
@@ -1,11 +1,44 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message3;
+
import "datasets/google_message3/benchmark_message3_3.proto";
import "datasets/google_message3/benchmark_message3_4.proto";
import "datasets/google_message3/benchmark_message3_5.proto";
import "datasets/google_message3/benchmark_message3_7.proto";
import "datasets/google_message3/benchmark_message3_8.proto";
-package benchmarks.google_message3;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
@@ -79,8 +112,7 @@
repeated string field24655 = 6;
}
-message Message27454 {
-}
+message Message27454 {}
message Message27357 {
optional string field27410 = 1;
@@ -162,8 +194,7 @@
}
message Message33968 {
- repeated group Message33969 = 1 {
- }
+ repeated group Message33969 = 1 {}
repeated .benchmarks.google_message3.Message33958 field33989 = 3;
optional .benchmarks.google_message3.UnusedEmptyMessage field33990 = 106;
optional bool field33991 = 108;
@@ -238,8 +269,7 @@
optional string field35696 = 1000;
optional string field35697 = 1004;
optional int32 field35698 = 1003;
- repeated group Message35574 = 1012 {
- }
+ repeated group Message35574 = 1012 {}
optional int64 field35700 = 1011;
optional int64 field35701 = 1005;
optional int64 field35702 = 1006;
@@ -496,4 +526,3 @@
optional .benchmarks.google_message3.UnusedEnum field4000 = 6;
optional int32 field4001 = 5;
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_3.proto b/benchmarks/datasets/google_message3/benchmark_message3_3.proto
index e71d266..2e534a6 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_3.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_3.proto
@@ -1,10 +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.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message3;
+
import "datasets/google_message3/benchmark_message3_4.proto";
import "datasets/google_message3/benchmark_message3_5.proto";
import "datasets/google_message3/benchmark_message3_7.proto";
import "datasets/google_message3/benchmark_message3_8.proto";
-package benchmarks.google_message3;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
@@ -66,8 +99,7 @@
optional bytes field2410 = 124;
}
optional string field2389 = 120;
- optional group Message2358 = 107 {
- }
+ optional group Message2358 = 107 {}
repeated group Message2359 = 40 {
optional string field2413 = 41;
optional string field2414 = 42;
@@ -408,8 +440,7 @@
optional bool field16773 = 13;
}
-message Message17728 {
-}
+message Message17728 {}
message Message24356 {
optional string field24559 = 1;
@@ -463,4 +494,3 @@
repeated string field24587 = 8;
repeated string field24588 = 11;
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_4.proto b/benchmarks/datasets/google_message3/benchmark_message3_4.proto
index 597cec6..b304148 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_4.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_4.proto
@@ -1,16 +1,48 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message3;
+
import "datasets/google_message3/benchmark_message3_5.proto";
import "datasets/google_message3/benchmark_message3_6.proto";
import "datasets/google_message3/benchmark_message3_7.proto";
import "datasets/google_message3/benchmark_message3_8.proto";
-package benchmarks.google_message3;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
-message Message24346 {
-}
+message Message24346 {}
message Message24401 {
optional .benchmarks.google_message3.Message24400 field24679 = 1;
@@ -189,12 +221,9 @@
optional float field13099 = 45;
optional uint64 field13100 = 46;
optional float field13101 = 47;
- optional group Message13085 = 16 {
- }
- repeated group Message13086 = 23 {
- }
- repeated group Message13087 = 29 {
- }
+ optional group Message13085 = 16 {}
+ repeated group Message13086 = 23 {}
+ repeated group Message13087 = 29 {}
optional .benchmarks.google_message3.UnusedEmptyMessage field13105 = 43;
}
@@ -262,12 +291,10 @@
optional float field16826 = 1;
optional .benchmarks.google_message3.Enum16819 field16827 = 2;
optional float field16828 = 3;
- repeated group Message16817 = 4 {
- }
+ repeated group Message16817 = 4 {}
optional bool field16830 = 7;
optional bool field16831 = 8;
- repeated group Message16818 = 12 {
- }
+ repeated group Message16818 = 12 {}
optional string field16833 = 10;
optional bool field16834 = 13;
optional bool field16835 = 14;
@@ -308,11 +335,9 @@
optional string field1376 = 2;
}
-message Message18943 {
-}
+message Message18943 {}
-message Message18944 {
-}
+message Message18944 {}
message Message18856 {
optional string field18857 = 1;
@@ -436,8 +461,7 @@
optional int64 field8482 = 2;
}
-message Message12559 {
-}
+message Message12559 {}
message Message12817 {
optional int32 field12826 = 1;
@@ -488,4 +512,3 @@
repeated string field24473 = 27;
optional bool field24474 = 40;
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_5.proto b/benchmarks/datasets/google_message3/benchmark_message3_5.proto
index bc6cbc1..e72d7ee 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_5.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_5.proto
@@ -1,18 +1,49 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message3;
+
import "datasets/google_message3/benchmark_message3_6.proto";
import "datasets/google_message3/benchmark_message3_7.proto";
import "datasets/google_message3/benchmark_message3_8.proto";
-package benchmarks.google_message3;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
-message Message24377 {
-}
+message Message24377 {}
-message Message24378 {
-}
+message Message24378 {}
message Message24400 {
optional int32 field24674 = 1;
@@ -22,11 +53,9 @@
optional int32 field24678 = 5;
}
-message Message24380 {
-}
+message Message24380 {}
-message Message24381 {
-}
+message Message24381 {}
message Message719 {
repeated string field881 = 1;
@@ -103,6 +132,7 @@
message Message0 {
option message_set_wire_format = true;
+
extensions 4 to 2147483646;
}
@@ -193,7 +223,8 @@
optional fixed64 field10232 = 13;
optional fixed64 field10233 = 20;
optional bool field10234 = 79;
- repeated .benchmarks.google_message3.Enum10167 field10235 = 80 [packed = true];
+ repeated .benchmarks.google_message3.Enum10167 field10235 = 80
+ [packed = true];
optional int32 field10236 = 14;
optional int32 field10237 = 15;
optional int32 field10238 = 28;
@@ -285,25 +316,20 @@
extensions 1000 to 536870911;
}
-message Message16686 {
-}
+message Message16686 {}
message Message12796 {
repeated fixed64 field12800 = 1;
optional uint64 field12801 = 2;
}
-message Message6722 {
-}
+message Message6722 {}
-message Message6727 {
-}
+message Message6727 {}
-message Message6724 {
-}
+message Message6724 {}
-message Message6735 {
-}
+message Message6735 {}
message Message8183 {
optional string field8226 = 1;
@@ -325,8 +351,7 @@
extensions 64 to 536870911;
}
-message Message8456 {
-}
+message Message8456 {}
message Message8302 {
optional string field8339 = 1;
@@ -353,8 +378,7 @@
extensions 64 to 536870911;
}
-message Message8457 {
-}
+message Message8457 {}
message Message8449 {
optional string field8458 = 1;
@@ -470,4 +494,3 @@
optional int64 field785 = 7;
repeated string field786 = 8;
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_6.proto b/benchmarks/datasets/google_message3/benchmark_message3_6.proto
index 98e1529..c766f7c 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_6.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_6.proto
@@ -1,14 +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.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message3;
+
import "datasets/google_message3/benchmark_message3_7.proto";
import "datasets/google_message3/benchmark_message3_8.proto";
-package benchmarks.google_message3;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
-message Message10576 {
-}
+message Message10576 {}
message Message10154 {
optional bytes field10192 = 1;
@@ -343,8 +375,7 @@
optional string field9012 = 3;
repeated string field9013 = 4;
optional string field9014 = 5;
- repeated group Message8940 = 11 {
- }
+ repeated group Message8940 = 11 {}
optional int64 field9016 = 21;
optional int64 field9017 = 22;
optional int64 field9018 = 23;
@@ -423,8 +454,7 @@
optional float field9672 = 5;
}
-message Message11020 {
-}
+message Message11020 {}
message Message11013 {
optional bytes field11757 = 19;
@@ -451,4 +481,3 @@
optional .benchmarks.google_message3.UnusedEmptyMessage field11778 = 23;
repeated .benchmarks.google_message3.Message11011 field11779 = 22;
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_7.proto b/benchmarks/datasets/google_message3/benchmark_message3_7.proto
index 2497db5..0f8f10c 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_7.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_7.proto
@@ -1,3 +1,33 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
syntax = "proto2";
package benchmarks.google_message3;
@@ -5,8 +35,7 @@
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
-message Message11018 {
-}
+message Message11018 {}
message Message10800 {
optional string field10808 = 1;
@@ -15,8 +44,7 @@
optional float field10811 = 4;
}
-message Message10802 {
-}
+message Message10802 {}
message Message10748 {
optional string field10750 = 1;
@@ -39,18 +67,15 @@
repeated string field828 = 5;
}
-message Message8942 {
-}
+message Message8942 {}
message Message11011 {
required bytes field11752 = 1;
required bytes field11753 = 2;
}
-message UnusedEmptyMessage {
-}
+message UnusedEmptyMessage {}
message Message741 {
repeated string field936 = 1;
}
-
diff --git a/benchmarks/datasets/google_message3/benchmark_message3_8.proto b/benchmarks/datasets/google_message3/benchmark_message3_8.proto
index 1d2b147..68fe8e9 100644
--- a/benchmarks/datasets/google_message3/benchmark_message3_8.proto
+++ b/benchmarks/datasets/google_message3/benchmark_message3_8.proto
@@ -1,3 +1,33 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
syntax = "proto2";
package benchmarks.google_message3;
@@ -609,9 +639,7 @@
ENUM_VALUE10334 = 8;
}
-enum Enum10335 {
- ENUM_VALUE10336 = 0;
-}
+enum Enum10335 { ENUM_VALUE10336 = 0; }
enum Enum10337 {
ENUM_VALUE10338 = 0;
@@ -1857,9 +1885,7 @@
ENUM_VALUE33967 = 6;
}
-enum Enum34388 {
- ENUM_VALUE34389 = 1;
-}
+enum Enum34388 { ENUM_VALUE34389 = 1; }
enum Enum35477 {
ENUM_VALUE35478 = 4;
@@ -1897,4 +1923,3 @@
ENUM_VALUE36891 = 0;
ENUM_VALUE36892 = 1;
}
-
diff --git a/benchmarks/datasets/google_message4/benchmark_message4.proto b/benchmarks/datasets/google_message4/benchmark_message4.proto
index 2161393..424ed10 100644
--- a/benchmarks/datasets/google_message4/benchmark_message4.proto
+++ b/benchmarks/datasets/google_message4/benchmark_message4.proto
@@ -1,9 +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.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message4;
+
import "datasets/google_message4/benchmark_message4_1.proto";
import "datasets/google_message4/benchmark_message4_2.proto";
import "datasets/google_message4/benchmark_message4_3.proto";
-package benchmarks.google_message4;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
@@ -146,8 +179,7 @@
optional .benchmarks.google_message4.UnusedEnum field455 = 37;
optional .benchmarks.google_message4.UnusedEnum field456 = 34;
optional int32 field457 = 35;
- repeated group Message178 = 101 {
- }
+ repeated group Message178 = 101 {}
optional bool field459 = 52;
optional uint64 field460 = 58;
optional uint64 field461 = 59;
@@ -428,10 +460,8 @@
optional bytes field2410 = 124;
}
optional string field2389 = 120;
- optional group Message2358 = 107 {
- }
- repeated group Message2359 = 40 {
- }
+ optional group Message2358 = 107 {}
+ repeated group Message2359 = 40 {}
optional int32 field2392 = 50;
optional .benchmarks.google_message4.UnusedEmptyMessage field2393 = 60;
optional .benchmarks.google_message4.UnusedEmptyMessage field2394 = 70;
@@ -443,6 +473,7 @@
message Message0 {
option message_set_wire_format = true;
+
extensions 4 to 2147483646;
}
@@ -451,4 +482,3 @@
optional int32 field973 = 2;
optional bool field974 = 3;
}
-
diff --git a/benchmarks/datasets/google_message4/benchmark_message4_1.proto b/benchmarks/datasets/google_message4/benchmark_message4_1.proto
index e769748..c5deecd 100644
--- a/benchmarks/datasets/google_message4/benchmark_message4_1.proto
+++ b/benchmarks/datasets/google_message4/benchmark_message4_1.proto
@@ -1,8 +1,41 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// LINT: ALLOW_GROUPS
+
syntax = "proto2";
+package benchmarks.google_message4;
+
import "datasets/google_message4/benchmark_message4_2.proto";
import "datasets/google_message4/benchmark_message4_3.proto";
-package benchmarks.google_message4;
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
@@ -16,8 +49,7 @@
optional .benchmarks.google_message4.Message12685 field12700 = 2;
}
-message Message11949 {
-}
+message Message11949 {}
message Message11975 {
optional string field11992 = 1;
@@ -104,8 +136,7 @@
}
optional .benchmarks.google_message4.UnusedEmptyMessage field3315 = 39;
optional int32 field3316 = 76;
- optional group Message3065 = 63 {
- }
+ optional group Message3065 = 63 {}
optional .benchmarks.google_message4.Enum2806 field3318 = 54;
optional int32 field3319 = 46;
repeated string field3320 = 24;
@@ -133,8 +164,7 @@
optional int32 field3333 = 17;
}
-message Message12949 {
-}
+message Message12949 {}
message Message8572 {
optional bytes field8647 = 1;
@@ -239,11 +269,9 @@
repeated .benchmarks.google_message4.UnusedEmptyMessage field12868 = 7;
}
-message Message8590 {
-}
+message Message8590 {}
-message Message8587 {
-}
+message Message8587 {}
message Message1374 {
required string field1375 = 1;
@@ -423,8 +451,7 @@
optional string field3262 = 9;
}
-message Message8575 {
-}
+message Message8575 {}
message Message7843 {
optional bool field7844 = 5;
@@ -471,4 +498,3 @@
repeated bytes field7960 = 11;
optional int64 field7961 = 16;
}
-
diff --git a/benchmarks/datasets/google_message4/benchmark_message4_2.proto b/benchmarks/datasets/google_message4/benchmark_message4_2.proto
index d5e9da5..0c4cdfd 100644
--- a/benchmarks/datasets/google_message4/benchmark_message4_2.proto
+++ b/benchmarks/datasets/google_message4/benchmark_message4_2.proto
@@ -1,8 +1,39 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
syntax = "proto2";
-import "datasets/google_message4/benchmark_message4_3.proto";
package benchmarks.google_message4;
+import "datasets/google_message4/benchmark_message4_3.proto";
+
option cc_enable_arenas = true;
option java_package = "com.google.protobuf.benchmarks";
@@ -102,8 +133,7 @@
optional .benchmarks.google_message4.Message5880 field5902 = 6;
}
-message Message6110 {
-}
+message Message6110 {}
message Message6107 {
optional .benchmarks.google_message4.Message4016 field6134 = 1;
@@ -181,8 +211,7 @@
optional bool field3929 = 14;
}
-message Message7865 {
-}
+message Message7865 {}
message Message7511 {
optional bool field7523 = 1;
@@ -194,8 +223,7 @@
optional int32 field7529 = 7;
}
-message Message3920 {
-}
+message Message3920 {}
message Message7928 {
optional string field7940 = 1;
@@ -231,8 +259,7 @@
optional string field6090 = 2;
}
-message Message6127 {
-}
+message Message6127 {}
message Message6052 {
required string field6084 = 1;
@@ -272,8 +299,7 @@
required int32 field4020 = 4;
}
-message Message6108 {
-}
+message Message6108 {}
message Message5907 {
optional .benchmarks.google_message4.Message5903 field5967 = 1;
@@ -282,11 +308,9 @@
optional .benchmarks.google_message4.Message5903 field5970 = 4;
}
-message UnusedEmptyMessage {
-}
+message UnusedEmptyMessage {}
message Message5903 {
required int32 field5965 = 1;
optional .benchmarks.google_message4.Enum5904 field5966 = 2;
}
-
diff --git a/benchmarks/datasets/google_message4/benchmark_message4_3.proto b/benchmarks/datasets/google_message4/benchmark_message4_3.proto
index 544fad2..42e254b 100644
--- a/benchmarks/datasets/google_message4/benchmark_message4_3.proto
+++ b/benchmarks/datasets/google_message4/benchmark_message4_3.proto
@@ -1,3 +1,33 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
syntax = "proto2";
package benchmarks.google_message4;
@@ -47,6 +77,7 @@
enum Enum2851 {
option allow_alias = true;
+
ENUM_VALUE2852 = 0;
ENUM_VALUE2853 = 0;
ENUM_VALUE2854 = 1;
@@ -717,9 +748,7 @@
ENUM_VALUE10334 = 8;
}
-enum Enum10335 {
- ENUM_VALUE10336 = 0;
-}
+enum Enum10335 { ENUM_VALUE10336 = 0; }
enum Enum10337 {
ENUM_VALUE10338 = 0;
@@ -748,4 +777,3 @@
ENUM_VALUE12876 = 5;
ENUM_VALUE12877 = 6;
}
-
diff --git a/benchmarks/python/py_benchmark.py b/benchmarks/python/py_benchmark.py
old mode 100755
new mode 100644
diff --git a/benchmarks/util/result_parser.py b/benchmarks/util/result_parser.py
old mode 100755
new mode 100644
diff --git a/benchmarks/util/result_uploader.py b/benchmarks/util/result_uploader.py
old mode 100755
new mode 100644
diff --git a/cc_proto_blacklist_test.bzl b/cc_proto_blacklist_test.bzl
new file mode 100644
index 0000000..df54293
--- /dev/null
+++ b/cc_proto_blacklist_test.bzl
@@ -0,0 +1,38 @@
+"""Contains a unittest to verify that `cc_proto_library` does not generate code for blacklisted `.proto` sources (i.e. WKPs)."""
+
+load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
+
+def _cc_proto_blacklist_test_impl(ctx):
+ """Verifies that there are no C++ compile actions for Well-Known-Protos.
+
+ Args:
+ ctx: The rule context.
+
+ Returns: A (not further specified) sequence of providers.
+ """
+
+ env = unittest.begin(ctx)
+
+ for dep in ctx.attr.deps:
+ files = len(dep.files.to_list())
+ asserts.equals(
+ env,
+ 0,
+ files,
+ "Expected that target '{}' does not provide files, got {}".format(
+ dep.label,
+ files,
+ ),
+ )
+
+ return unittest.end(env)
+
+cc_proto_blacklist_test = unittest.make(
+ impl = _cc_proto_blacklist_test_impl,
+ attrs = {
+ "deps": attr.label_list(
+ mandatory = True,
+ providers = [CcInfo],
+ ),
+ },
+)
diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt
index 0ae5435..9ca31ac 100644
--- a/cmake/CMakeLists.txt
+++ b/cmake/CMakeLists.txt
@@ -28,7 +28,18 @@
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
+# The Intel compiler isn't able to deal with noinline member functions of
+# template classses defined in headers. As such it spams the output with
+# warning #2196: routine is both "inline" and "noinline"
+# This silences that warning.
+if (CMAKE_CXX_COMPILER_ID MATCHES Intel)
+ string(APPEND CMAKE_CXX_FLAGS " -diag-disable=2196")
+endif()
+
# Options
+if(WITH_PROTOC)
+ set(protobuf_PROTOC_EXE ${WITH_PROTOC} CACHE FILEPATH "Protocol Buffer Compiler executable" FORCE)
+endif()
option(protobuf_BUILD_TESTS "Build tests" ON)
option(protobuf_BUILD_CONFORMANCE "Build conformance tests" OFF)
option(protobuf_BUILD_EXAMPLES "Build examples" OFF)
@@ -40,6 +51,8 @@
endif (BUILD_SHARED_LIBS)
option(protobuf_BUILD_SHARED_LIBS "Build Shared Libraries" ${protobuf_BUILD_SHARED_LIBS_DEFAULT})
include(CMakeDependentOption)
+cmake_dependent_option(protobuf_MSVC_STATIC_RUNTIME "Link static runtime libraries" ON
+ "NOT protobuf_BUILD_SHARED_LIBS" OFF)
set(protobuf_WITH_ZLIB_DEFAULT ON)
option(protobuf_WITH_ZLIB "Build with zlib support" ${protobuf_WITH_ZLIB_DEFAULT})
set(protobuf_DEBUG_POSTFIX "d"
@@ -48,6 +61,12 @@
# User options
include(protobuf-options.cmake)
+# Overrides for option dependencies
+if (protobuf_BUILD_PROTOC_BINARIES OR protobuf_BUILD_TESTS)
+ set(protobuf_BUILD_LIBPROTOC ON)
+else()
+ set(protobuf_BUILD_LIBPROTOC OFF)
+endif ()
# Path to main configure script
set(protobuf_CONFIGURE_SCRIPT "../configure.ac")
@@ -153,22 +172,22 @@
set(protobuf_SHARED_OR_STATIC "SHARED")
else (protobuf_BUILD_SHARED_LIBS)
set(protobuf_SHARED_OR_STATIC "STATIC")
+ # In case we are building static libraries, link also the runtime library statically
+ # so that MSVCR*.DLL is not required at runtime.
+ # https://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
+ # This is achieved by replacing msvc option /MD with /MT and /MDd with /MTd
+ # http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
+ if (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
+ foreach(flag_var
+ CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
+ CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
+ if(${flag_var} MATCHES "/MD")
+ string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
+ endif(${flag_var} MATCHES "/MD")
+ endforeach(flag_var)
+ endif (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
endif (protobuf_BUILD_SHARED_LIBS)
-# In case we are linking the runtime library statically so that MSVCR*.DLL is not required at runtime.
-# https://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
-# This is achieved by replacing msvc option /MD with /MT and /MDd with /MTd
-# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
-if (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
- foreach(flag_var
- CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
- CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
- if(${flag_var} MATCHES "/MD")
- string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
- endif(${flag_var} MATCHES "/MD")
- endforeach(flag_var)
-endif (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
-
if (MSVC)
# Build with multiple processes
add_definitions(/MP)
@@ -232,11 +251,29 @@
include(libprotobuf-lite.cmake)
include(libprotobuf.cmake)
-if (protobuf_BUILD_PROTOC_BINARIES)
+if (protobuf_BUILD_LIBPROTOC)
include(libprotoc.cmake)
+endif (protobuf_BUILD_LIBPROTOC)
+if (protobuf_BUILD_PROTOC_BINARIES)
include(protoc.cmake)
+ if (NOT DEFINED protobuf_PROTOC_EXE)
+ set(protobuf_PROTOC_EXE protoc)
+ endif (NOT DEFINED protobuf_PROTOC_EXE)
endif (protobuf_BUILD_PROTOC_BINARIES)
+# Ensure we have a protoc executable if we need one
+if (protobuf_BUILD_TESTS OR protobuf_BUILD_CONFORMANCE OR protobuf_BUILD_EXAMPLES)
+ if (NOT DEFINED protobuf_PROTOC_EXE)
+ find_program(protobuf_PROTOC_EXE protoc)
+ if (NOT protobuf_PROTOC_EXE)
+ message(FATAL "Build requires 'protoc' but binary not found and not building protoc.")
+ endif ()
+ endif ()
+ if(protobuf_VERBOSE)
+ message(STATUS "Using protoc : ${protobuf_PROTOC_EXE}")
+ endif(protobuf_VERBOSE)
+endif ()
+
if (protobuf_BUILD_TESTS)
include(tests.cmake)
endif (protobuf_BUILD_TESTS)
@@ -252,5 +289,5 @@
endif (protobuf_BUILD_EXAMPLES)
if(protobuf_VERBOSE)
- message(STATUS "Protocol Buffers Configuring done")
-endif()
+ message(STATUS "Protocol Buffers Configuring done")
+endif(protobuf_VERBOSE)
diff --git a/cmake/README.md b/cmake/README.md
index 89d00c1..ed30d24 100644
--- a/cmake/README.md
+++ b/cmake/README.md
@@ -343,3 +343,23 @@
nevertheless. So, we disable it. Unfortunately, this warning will also be
produced when compiling code which merely uses protocol buffers, meaning you
may have to disable it in your code too.
+
+Cross-compiling
+===============
+
+When cross-compiling you will need to disable building the tests which are ON
+by default. You can do so by specifying the following flags when configuring
+your build:
+
+ -Dprotobuf_BUILD_TESTS=OFF
+
+Alternatively you can compile (or download) 'protoc' for your host machine
+prior to configuring your target build. To specify an existing 'protoc' binary
+for your build, specify the following flag:
+
+ -DWITH_PROTOC=<path to your protoc binary>
+
+You can also save compilation time by disabling building 'protoc' for your
+target build:
+
+ -Dprotobuf_BUILD_PROTOC_BINARIES=OFF
diff --git a/cmake/conformance.cmake b/cmake/conformance.cmake
index 82b4cf5..76eae8a 100644
--- a/cmake/conformance.cmake
+++ b/cmake/conformance.cmake
@@ -1,8 +1,8 @@
add_custom_command(
OUTPUT ${protobuf_source_dir}/conformance/conformance.pb.cc
- DEPENDS protoc ${protobuf_source_dir}/conformance/conformance.proto
- COMMAND protoc ${protobuf_source_dir}/conformance/conformance.proto
+ DEPENDS ${protobuf_PROTOC_EXE} ${protobuf_source_dir}/conformance/conformance.proto
+ COMMAND ${protobuf_PROTOC_EXE} ${protobuf_source_dir}/conformance/conformance.proto
--proto_path=${protobuf_source_dir}/conformance
--cpp_out=${protobuf_source_dir}/conformance
)
@@ -10,9 +10,9 @@
add_custom_command(
OUTPUT ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc
${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc
- DEPENDS protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto
- protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.proto
- COMMAND protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto
+ DEPENDS ${protobuf_PROTOC_EXE} ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto
+ ${protobuf_PROTOC_EXE} ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.proto
+ COMMAND ${protobuf_PROTOC_EXE} ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto
${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.proto
--proto_path=${protobuf_source_dir}/src
--cpp_out=${protobuf_source_dir}/src
diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in
index 29e39d8..11b85d3 100644
--- a/cmake/protobuf-config.cmake.in
+++ b/cmake/protobuf-config.cmake.in
@@ -11,7 +11,7 @@
include(CMakeParseArguments)
set(_options APPEND_PATH)
- set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO PROTOC_OUT_DIR)
+ set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO PROTOC_OUT_DIR PLUGIN)
if(COMMAND target_sources)
list(APPEND _singleargs TARGET)
endif()
@@ -41,6 +41,10 @@
if(protobuf_generate_EXPORT_MACRO AND protobuf_generate_LANGUAGE STREQUAL cpp)
set(_dll_export_decl "dllexport_decl=${protobuf_generate_EXPORT_MACRO}:")
endif()
+
+ if(protobuf_generate_PLUGIN)
+ set(_plugin "--plugin=${protobuf_generate_PLUGIN}")
+ endif()
if(NOT protobuf_generate_GENERATE_EXTENSIONS)
if(protobuf_generate_LANGUAGE STREQUAL cpp)
@@ -77,8 +81,6 @@
list(APPEND _protobuf_include_path -I ${_abs_path})
endif()
endforeach()
- else()
- set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
endif()
foreach(DIR ${protobuf_generate_IMPORT_DIRS})
@@ -89,12 +91,31 @@
endif()
endforeach()
+ if(NOT _protobuf_include_path)
+ set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
+ endif()
+
set(_generated_srcs_all)
foreach(_proto ${protobuf_generate_PROTOS})
get_filename_component(_abs_file ${_proto} ABSOLUTE)
get_filename_component(_abs_dir ${_abs_file} DIRECTORY)
- get_filename_component(_basename ${_proto} NAME_WE)
- file(RELATIVE_PATH _rel_dir ${CMAKE_CURRENT_SOURCE_DIR} ${_abs_dir})
+ get_filename_component(_basename ${_proto} NAME_WLE)
+
+ set(_suitable_include_found FALSE)
+ foreach(DIR ${_protobuf_include_path})
+ if(NOT DIR STREQUAL "-I")
+ file(RELATIVE_PATH _rel_dir ${DIR} ${_abs_dir})
+ if(NOT "${_rel_dir}" MATCHES "^\.\.[/\\].*")
+ set(_suitable_include_found TRUE)
+ break()
+ endif()
+ endif()
+ endforeach()
+
+ if(NOT _suitable_include_found)
+ message(SEND_ERROR "Error: protobuf_generate could not find any correct proto include directory.")
+ return()
+ endif()
set(_generated_srcs)
foreach(_ext ${protobuf_generate_GENERATE_EXTENSIONS})
@@ -105,7 +126,7 @@
add_custom_command(
OUTPUT ${_generated_srcs}
COMMAND protobuf::protoc
- ARGS --${protobuf_generate_LANGUAGE}_out ${_dll_export_decl}${protobuf_generate_PROTOC_OUT_DIR} ${_protobuf_include_path} ${_abs_file}
+ ARGS --${protobuf_generate_LANGUAGE}_out ${_dll_export_decl}${protobuf_generate_PROTOC_OUT_DIR} ${_plugin} ${_protobuf_include_path} ${_abs_file}
DEPENDS ${_abs_file} protobuf::protoc
COMMENT "Running ${protobuf_generate_LANGUAGE} protocol buffer compiler on ${_proto}"
VERBATIM )
diff --git a/cmake/tests.cmake b/cmake/tests.cmake
index d4b47c5..da62c1b 100644
--- a/cmake/tests.cmake
+++ b/cmake/tests.cmake
@@ -67,6 +67,7 @@
google/protobuf/unittest_proto3_arena.proto
google/protobuf/unittest_proto3_arena_lite.proto
google/protobuf/unittest_proto3_lite.proto
+ google/protobuf/unittest_proto3_optional.proto
google/protobuf/unittest_well_known_types.proto
google/protobuf/util/internal/testdata/anys.proto
google/protobuf/util/internal/testdata/books.proto
@@ -89,10 +90,11 @@
get_filename_component(basename ${filename} NAME_WE)
add_custom_command(
OUTPUT ${protobuf_source_dir}/src/${dirname}/${basename}.pb.cc
- DEPENDS protoc ${protobuf_source_dir}/src/${dirname}/${basename}.proto
- COMMAND protoc ${protobuf_source_dir}/src/${dirname}/${basename}.proto
+ DEPENDS ${protobuf_PROTOC_EXE} ${protobuf_source_dir}/src/${dirname}/${basename}.proto
+ COMMAND ${protobuf_PROTOC_EXE} ${protobuf_source_dir}/src/${dirname}/${basename}.proto
--proto_path=${protobuf_source_dir}/src
--cpp_out=${protobuf_source_dir}/src
+ --experimental_allow_proto3_optional
)
endmacro(compile_proto_file)
diff --git a/compiler_config_setting.bzl b/compiler_config_setting.bzl
index 5e52a65..f4d1f7b 100644
--- a/compiler_config_setting.bzl
+++ b/compiler_config_setting.bzl
@@ -1,6 +1,6 @@
"""Creates config_setting that allows selecting based on 'compiler' value."""
-def create_compiler_config_setting(name, value):
+def create_compiler_config_setting(name, value, visibility = None):
# The "do_not_use_tools_cpp_compiler_present" attribute exists to
# distinguish between older versions of Bazel that do not support
# "@bazel_tools//tools/cpp:compiler" flag_value, and newer ones that do.
@@ -13,9 +13,11 @@
flag_values = {
"@bazel_tools//tools/cpp:compiler": value,
},
+ visibility = visibility,
)
else:
native.config_setting(
name = name,
values = {"compiler": value},
+ visibility = visibility,
)
diff --git a/configure.ac b/configure.ac
index af2d980..b94fe10 100644
--- a/configure.ac
+++ b/configure.ac
@@ -17,7 +17,7 @@
# 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.11.0-rc-1],[protobuf@googlegroups.com],[protobuf])
+AC_INIT([Protocol Buffers],[3.12.0-rc-2],[protobuf@googlegroups.com],[protobuf])
AM_MAINTAINER_MODE([enable])
diff --git a/conformance/Makefile.am b/conformance/Makefile.am
index 4eff3e1..6815c73 100644
--- a/conformance/Makefile.am
+++ b/conformance/Makefile.am
@@ -218,7 +218,7 @@
nodist_conformance_test_runner_SOURCES = conformance.pb.cc google/protobuf/test_messages_proto3.pb.cc google/protobuf/test_messages_proto2.pb.cc
conformance_test_runner_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)
conformance_test_runner_CXXFLAGS = -std=c++11
-# Explicit deps beacuse BUILT_SOURCES are only done before a "make all/check"
+# Explicit deps because BUILT_SOURCES are only done before a "make all/check"
# so a direct "make test_cpp" could fail if parallel enough.
conformance_test_runner-conformance_test.$(OBJEXT): conformance.pb.h
conformance_test_runner-conformance_test_runner.$(OBJEXT): conformance.pb.h
@@ -227,7 +227,7 @@
conformance_cpp_SOURCES = conformance_cpp.cc
nodist_conformance_cpp_SOURCES = conformance.pb.cc google/protobuf/test_messages_proto3.pb.cc google/protobuf/test_messages_proto2.pb.cc
conformance_cpp_CPPFLAGS = -I$(top_srcdir)/src
-# Explicit dep beacuse BUILT_SOURCES are only done before a "make all/check"
+# Explicit dep because BUILT_SOURCES are only done before a "make all/check"
# so a direct "make test_cpp" could fail if parallel enough.
conformance_cpp-conformance_cpp.$(OBJEXT): conformance.pb.h
@@ -243,7 +243,7 @@
# setup for Xcode and old frameworks are being found.
conformance_objc_CPPFLAGS = -I$(top_srcdir)/objectivec -isysroot `xcrun --sdk macosx --show-sdk-path`
conformance_objc_LDFLAGS = -framework Foundation
-# Explicit dep beacuse BUILT_SOURCES are only done before a "make all/check"
+# Explicit dep because BUILT_SOURCES are only done before a "make all/check"
# so a direct "make test_objc" could fail if parallel enough.
conformance_objc-conformance_objc.$(OBJEXT): Conformance.pbobjc.h google/protobuf/TestMessagesProto2.pbobjc.h google/protobuf/TestMessagesProto3.pbobjc.h
@@ -353,8 +353,8 @@
test_php_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs)
./conformance-test-runner --enforce_recommended --failure_list failure_list_php_c.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php-c
-test_php_zts_c: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs)
- ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_zts_c.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php-c
+test_php_c_32: protoc_middleman conformance-test-runner conformance-php-c $(other_language_protoc_outputs)
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_php_c_32.txt --text_format_failure_list text_format_failure_list_php.txt ./conformance-php-c
# These depend on library paths being properly set up. The easiest way to
# run them is to just use "tox" from the python dir.
diff --git a/conformance/binary_json_conformance_suite.cc b/conformance/binary_json_conformance_suite.cc
index d297ae3..f62c705 100644
--- a/conformance/binary_json_conformance_suite.cc
+++ b/conformance/binary_json_conformance_suite.cc
@@ -556,24 +556,24 @@
equivalent_text_format, is_proto3);
}
-// According to proto3 JSON specification, JSON serializers follow more strict
+// According to proto JSON specification, JSON serializers follow more strict
// rules than parsers (e.g., a serializer must serialize int32 values as JSON
// numbers while the parser is allowed to accept them as JSON strings). This
-// method allows strict checking on a proto3 JSON serializer by inspecting
+// method allows strict checking on a proto JSON serializer by inspecting
// the JSON output directly.
void BinaryAndJsonConformanceSuite::RunValidJsonTestWithValidator(
const string& test_name, ConformanceLevel level, const string& input_json,
- const Validator& validator) {
- TestAllTypesProto3 prototype;
- ConformanceRequestSetting setting(
- level, conformance::JSON, conformance::JSON,
- conformance::JSON_TEST,
- prototype, test_name, input_json);
+ const Validator& validator, bool is_proto3) {
+ std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
+ ConformanceRequestSetting setting(level, conformance::JSON, conformance::JSON,
+ conformance::JSON_TEST, *prototype,
+ test_name, input_json);
const ConformanceRequest& request = setting.GetRequest();
ConformanceResponse response;
string effective_test_name =
StrCat(setting.ConformanceLevelToString(level),
- ".Proto3.JsonInput.", test_name, ".Validator");
+ is_proto3 ? ".Proto3.JsonInput." : ".Proto2.JsonInput.",
+ test_name, ".Validator");
RunTest(effective_test_name, request, &response);
@@ -1800,7 +1800,8 @@
value.isMember("fieldName2") &&
value.isMember("FieldName3") &&
value.isMember("fieldName4");
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"FieldNameWithNumbers", REQUIRED,
R"({
@@ -1810,7 +1811,8 @@
[](const Json::Value& value) {
return value.isMember("field0name5") &&
value.isMember("field0Name6");
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"FieldNameWithMixedCases", REQUIRED,
R"({
@@ -1828,7 +1830,8 @@
value.isMember("FieldName10") &&
value.isMember("FIELDNAME11") &&
value.isMember("FIELDName12");
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"FieldNameWithDoubleUnderscores", RECOMMENDED,
R"({
@@ -1846,7 +1849,32 @@
value.isMember("fieldName16") &&
value.isMember("fieldName17") &&
value.isMember("FieldName18");
- });
+ },
+ true);
+ RunValidJsonTestWithValidator(
+ "StoresDefaultPrimitive", REQUIRED,
+ R"({
+ "FieldName13": 0
+ })",
+ [](const Json::Value& value) { return value.isMember("FieldName13"); },
+ false);
+ RunValidJsonTestWithValidator(
+ "SkipsDefaultPrimitive", REQUIRED,
+ R"({
+ "FieldName13": 0
+ })",
+ [](const Json::Value& value) { return !value.isMember("FieldName13"); },
+ true);
+ RunValidJsonTestWithValidator(
+ "FieldNameExtension", RECOMMENDED,
+ R"({
+ "[protobuf_test_messages.proto2.extension_int32]": 1
+ })",
+ [](const Json::Value& value) {
+ return value.isMember(
+ "[protobuf_test_messages.proto2.extension_int32]");
+ },
+ false);
}
void BinaryAndJsonConformanceSuite::RunJsonTestsForNonRepeatedTypes() {
@@ -1973,7 +2001,7 @@
ExpectParseFailureForJson(
"Uint64FieldNotNumber", REQUIRED,
R"({"optionalUint64": "3x3"})");
- // JSON does not allow "+" on numric values.
+ // JSON does not allow "+" on numeric values.
ExpectParseFailureForJson(
"Int32FieldPlusSign", REQUIRED,
R"({"optionalInt32": +1})");
@@ -1995,19 +2023,19 @@
// 64-bit values are serialized as strings.
RunValidJsonTestWithValidator(
- "Int64FieldBeString", RECOMMENDED,
- R"({"optionalInt64": 1})",
+ "Int64FieldBeString", RECOMMENDED, R"({"optionalInt64": 1})",
[](const Json::Value& value) {
return value["optionalInt64"].type() == Json::stringValue &&
value["optionalInt64"].asString() == "1";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
- "Uint64FieldBeString", RECOMMENDED,
- R"({"optionalUint64": 1})",
+ "Uint64FieldBeString", RECOMMENDED, R"({"optionalUint64": 1})",
[](const Json::Value& value) {
return value["optionalUint64"].type() == Json::stringValue &&
value["optionalUint64"].asString() == "1";
- });
+ },
+ true);
// Bool fields.
RunValidJsonTest(
@@ -2080,7 +2108,7 @@
"FloatFieldNegativeInfinity", REQUIRED,
R"({"optionalFloat": "-Infinity"})",
"optional_float: -inf");
- // Non-cannonical Nan will be correctly normalized.
+ // Non-canonical Nan will be correctly normalized.
{
TestAllTypesProto3 message;
// IEEE floating-point standard 32-bit quiet NaN:
@@ -2139,7 +2167,7 @@
"DoubleFieldQuotedValue", REQUIRED,
R"({"optionalDouble": "1"})",
"optional_double: 1");
- // Speical values.
+ // Special values.
RunValidJsonTest(
"DoubleFieldNan", REQUIRED,
R"({"optionalDouble": "NaN"})",
@@ -2152,16 +2180,16 @@
"DoubleFieldNegativeInfinity", REQUIRED,
R"({"optionalDouble": "-Infinity"})",
"optional_double: -inf");
- // Non-cannonical Nan will be correctly normalized.
+ // Non-canonical Nan will be correctly normalized.
{
TestAllTypesProto3 message;
message.set_optional_double(
- WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
+ WireFormatLite::DecodeDouble(int64{0x7FFA123456789ABC}));
RunValidJsonTestWithProtobufInput(
"DoubleFieldNormalizeQuietNan", REQUIRED, message,
"optional_double: nan");
message.set_optional_double(
- WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
+ WireFormatLite::DecodeDouble(uint64{0xFFFBCBA987654321}));
RunValidJsonTestWithProtobufInput(
"DoubleFieldNormalizeSignalingNan", REQUIRED, message,
"optional_double: nan");
@@ -2223,12 +2251,12 @@
"optional_nested_enum: BAR");
// Unknown enum values are represented as numeric values.
RunValidJsonTestWithValidator(
- "EnumFieldUnknownValue", REQUIRED,
- R"({"optionalNestedEnum": 123})",
+ "EnumFieldUnknownValue", REQUIRED, R"({"optionalNestedEnum": 123})",
[](const Json::Value& value) {
return value["optionalNestedEnum"].type() == Json::intValue &&
value["optionalNestedEnum"].asInt() == 123;
- });
+ },
+ true);
// String fields.
RunValidJsonTest(
@@ -2712,25 +2740,29 @@
R"({"optionalDuration": "1.000000000s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1s";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"DurationHas3FractionalDigits", RECOMMENDED,
R"({"optionalDuration": "1.010000000s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1.010s";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"DurationHas6FractionalDigits", RECOMMENDED,
R"({"optionalDuration": "1.000010000s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1.000010s";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"DurationHas9FractionalDigits", RECOMMENDED,
R"({"optionalDuration": "1.000000010s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1.000000010s";
- });
+ },
+ true);
// Timestamp
RunValidJsonTest(
@@ -2794,34 +2826,39 @@
R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() == "1970-01-01T00:00:00Z";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"TimestampHasZeroFractionalDigit", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() == "1970-01-01T00:00:00Z";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"TimestampHas3FractionalDigits", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
"1970-01-01T00:00:00.010Z";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"TimestampHas6FractionalDigits", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
"1970-01-01T00:00:00.000010Z";
- });
+ },
+ true);
RunValidJsonTestWithValidator(
"TimestampHas9FractionalDigits", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
"1970-01-01T00:00:00.000000010Z";
- });
+ },
+ true);
}
void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldMask() {
diff --git a/conformance/binary_json_conformance_suite.h b/conformance/binary_json_conformance_suite.h
index aaf8bb4..0a17526 100644
--- a/conformance/binary_json_conformance_suite.h
+++ b/conformance/binary_json_conformance_suite.h
@@ -53,35 +53,34 @@
void RunJsonTestsForStruct();
void RunJsonTestsForValue();
void RunJsonTestsForAny();
- void RunValidJsonTest(const string& test_name,
- ConformanceLevel level,
- const string& input_json,
- const string& equivalent_text_format);
+ void RunValidJsonTest(const std::string& test_name, ConformanceLevel level,
+ const std::string& input_json,
+ const std::string& equivalent_text_format);
void RunValidJsonTestWithProtobufInput(
- const string& test_name,
- ConformanceLevel level,
+ const std::string& test_name, ConformanceLevel level,
const protobuf_test_messages::proto3::TestAllTypesProto3& input,
- const string& equivalent_text_format);
- void RunValidJsonIgnoreUnknownTest(
- const string& test_name, ConformanceLevel level, const string& input_json,
- const string& equivalent_text_format);
- void RunValidProtobufTest(const string& test_name, ConformanceLevel level,
- const string& input_protobuf,
- const string& equivalent_text_format,
+ const std::string& equivalent_text_format);
+ void RunValidJsonIgnoreUnknownTest(const std::string& test_name,
+ ConformanceLevel level,
+ const std::string& input_json,
+ const std::string& equivalent_text_format);
+ void RunValidProtobufTest(const std::string& test_name,
+ ConformanceLevel level,
+ const std::string& input_protobuf,
+ const std::string& equivalent_text_format,
bool is_proto3);
- void RunValidBinaryProtobufTest(const string& test_name,
+ void RunValidBinaryProtobufTest(const std::string& test_name,
ConformanceLevel level,
- const string& input_protobuf,
+ const std::string& input_protobuf,
bool is_proto3);
- void RunValidBinaryProtobufTest(const string& test_name,
+ void RunValidBinaryProtobufTest(const std::string& test_name,
ConformanceLevel level,
- const string& input_protobuf,
- const string& expected_protobuf,
+ const std::string& input_protobuf,
+ const std::string& expected_protobuf,
bool is_proto3);
void RunValidProtobufTestWithMessage(
- const string& test_name, ConformanceLevel level,
- const Message *input,
- const string& equivalent_text_format,
+ const std::string& test_name, ConformanceLevel level,
+ const Message* input, const std::string& equivalent_text_format,
bool is_proto3);
bool ParseJsonResponse(
@@ -93,20 +92,21 @@
Message* test_message) override;
typedef std::function<bool(const Json::Value&)> Validator;
- void RunValidJsonTestWithValidator(const string& test_name,
+ void RunValidJsonTestWithValidator(const std::string& test_name,
ConformanceLevel level,
- const string& input_json,
- const Validator& validator);
- void ExpectParseFailureForJson(const string& test_name,
+ const std::string& input_json,
+ const Validator& validator,
+ bool is_proto3);
+ void ExpectParseFailureForJson(const std::string& test_name,
ConformanceLevel level,
- const string& input_json);
- void ExpectSerializeFailureForJson(const string& test_name,
+ const std::string& input_json);
+ void ExpectSerializeFailureForJson(const std::string& test_name,
ConformanceLevel level,
- const string& text_format);
- void ExpectParseFailureForProtoWithProtoVersion (const string& proto,
- const string& test_name,
- ConformanceLevel level,
- bool is_proto3);
+ const std::string& text_format);
+ void ExpectParseFailureForProtoWithProtoVersion(const std::string& proto,
+ const std::string& test_name,
+ ConformanceLevel level,
+ bool is_proto3);
void ExpectParseFailureForProto(const std::string& proto,
const std::string& test_name,
ConformanceLevel level);
diff --git a/conformance/conformance.proto b/conformance/conformance.proto
index 54da406..26c0bd2 100644
--- a/conformance/conformance.proto
+++ b/conformance/conformance.proto
@@ -113,7 +113,7 @@
string message_type = 4;
// Each test is given a specific test category. Some category may need
- // spedific support in testee programs. Refer to the defintion of TestCategory
+ // spedific support in testee programs. Refer to the definition of TestCategory
// for more information.
TestCategory test_category = 5;
@@ -170,7 +170,7 @@
// Encoding options for jspb format.
message JspbEncodingConfig {
- // Encode the value field of Any as jspb array if ture, otherwise binary.
+ // Encode the value field of Any as jspb array if true, otherwise binary.
bool use_jspb_array_any_format = 1;
}
diff --git a/conformance/conformance_php.php b/conformance/conformance_php.php
old mode 100755
new mode 100644
diff --git a/conformance/conformance_test.h b/conformance/conformance_test.h
index 9f4ce37..76bd1bc 100644
--- a/conformance/conformance_test.h
+++ b/conformance/conformance_test.h
@@ -88,7 +88,7 @@
const std::vector<ConformanceTestSuite*>& suites);
ForkPipeRunner(const std::string& executable,
- const std::vector<string>& executable_args)
+ const std::vector<std::string>& executable_args)
: child_pid_(-1),
executable_(executable),
executable_args_(executable_args) {}
@@ -113,7 +113,7 @@
int read_fd_;
pid_t child_pid_;
std::string executable_;
- const std::vector<string> executable_args_;
+ const std::vector<std::string> executable_args_;
std::string current_test_name_;
};
@@ -168,9 +168,7 @@
// Gets the flag name to the failure list file.
// By default, this would return --failure_list
- string GetFailureListFlagName() {
- return failure_list_flag_name_;
- }
+ std::string GetFailureListFlagName() { return failure_list_flag_name_; }
void SetFailureListFlagName(const std::string& failure_list_flag_name) {
failure_list_flag_name_ = failure_list_flag_name;
@@ -191,7 +189,7 @@
// 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
+ // parser implementation 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
@@ -207,18 +205,18 @@
class ConformanceRequestSetting {
public:
- ConformanceRequestSetting(
- ConformanceLevel level,
- conformance::WireFormat input_format,
- conformance::WireFormat output_format,
- conformance::TestCategory test_category,
- const Message& prototype_message,
- const string& test_name, const string& input);
+ ConformanceRequestSetting(ConformanceLevel level,
+ conformance::WireFormat input_format,
+ conformance::WireFormat output_format,
+ conformance::TestCategory test_category,
+ const Message& prototype_message,
+ const std::string& test_name,
+ const std::string& input);
virtual ~ConformanceRequestSetting() {}
std::unique_ptr<Message> NewTestMessage() const;
- string GetTestName() const;
+ std::string GetTestName() const;
const conformance::ConformanceRequest& GetRequest() const {
return request_;
@@ -228,7 +226,7 @@
return level_;
}
- string ConformanceLevelToString(ConformanceLevel level) const;
+ std::string ConformanceLevelToString(ConformanceLevel level) const;
void SetPrintUnknownFields(bool print_unknown_fields) {
request_.set_print_unknown_fields(true);
@@ -239,8 +237,9 @@
}
protected:
- virtual string InputFormatString(conformance::WireFormat format) const;
- virtual string OutputFormatString(conformance::WireFormat format) const;
+ virtual std::string InputFormatString(conformance::WireFormat format) const;
+ virtual std::string OutputFormatString(
+ conformance::WireFormat format) const;
conformance::ConformanceRequest request_;
private:
@@ -249,12 +248,12 @@
::conformance::WireFormat output_format_;
const Message& prototype_message_;
std::unique_ptr<Message> prototype_message_for_compare_;
- string test_name_;
+ std::string test_name_;
};
- bool CheckSetEmpty(const std::set<string>& set_to_check,
+ bool CheckSetEmpty(const std::set<std::string>& set_to_check,
const std::string& write_to_file, const std::string& msg);
- string WireFormatToString(conformance::WireFormat wire_format);
+ std::string WireFormatToString(conformance::WireFormat wire_format);
// Parse payload in the response to the given message. Returns true on
// success.
@@ -264,24 +263,23 @@
Message* test_message) = 0;
void VerifyResponse(const ConformanceRequestSetting& setting,
- const string& equivalent_wire_format,
+ const std::string& equivalent_wire_format,
const conformance::ConformanceResponse& response,
bool need_report_success, bool require_same_wire_format);
void ReportSuccess(const std::string& test_name);
- void ReportFailure(const string& test_name,
- ConformanceLevel level,
+ void ReportFailure(const std::string& test_name, ConformanceLevel level,
const conformance::ConformanceRequest& request,
const conformance::ConformanceResponse& response,
const char* fmt, ...);
- void ReportSkip(const string& test_name,
+ void ReportSkip(const std::string& test_name,
const conformance::ConformanceRequest& request,
const conformance::ConformanceResponse& response);
void RunValidInputTest(const ConformanceRequestSetting& setting,
- const string& equivalent_text_format);
+ const std::string& equivalent_text_format);
void RunValidBinaryInputTest(const ConformanceRequestSetting& setting,
- const string& equivalent_wire_format,
+ const std::string& equivalent_wire_format,
bool require_same_wire_format = false);
void RunTest(const std::string& test_name,
diff --git a/conformance/failure_list_cpp.txt b/conformance/failure_list_cpp.txt
index 0c01e1e..d55fa9f 100644
--- a/conformance/failure_list_cpp.txt
+++ b/conformance/failure_list_cpp.txt
@@ -34,3 +34,4 @@
Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithNewlines
Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithSpace
Recommended.Proto3.JsonInput.TrailingCommaInAnObjectWithSpaceCommaSpace
+Recommended.Proto2.JsonInput.FieldNameExtension.Validator
diff --git a/conformance/failure_list_csharp.txt b/conformance/failure_list_csharp.txt
index 2adb30f..f82f0f2 100644
--- a/conformance/failure_list_csharp.txt
+++ b/conformance/failure_list_csharp.txt
@@ -1,33 +1,4 @@
-Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.UnpackedOutput.ProtobufOutput
-Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.DefaultOutput.ProtobufOutput
-Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.UnpackedOutput.ProtobufOutput
-Recommended.Proto2.ProtobufInput.ValidDataScalarBinary.BOOL[4].ProtobufOutput
-Recommended.Proto2.ProtobufInput.ValidDataScalarBinary.BOOL[6].ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.DefaultOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.UnpackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.DefaultOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.UnpackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataScalarBinary.BOOL[4].ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataScalarBinary.BOOL[6].ProtobufOutput
-Required.Proto2.ProtobufInput.RepeatedScalarSelectsLast.BOOL.ProtobufOutput
-Required.Proto2.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.ProtobufOutput
-Required.Proto2.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.ProtobufOutput
-Required.Proto2.ProtobufInput.ValidDataScalar.BOOL[4].ProtobufOutput
-Required.Proto2.ProtobufInput.ValidDataScalar.BOOL[6].ProtobufOutput
-Required.Proto3.ProtobufInput.RepeatedScalarSelectsLast.BOOL.JsonOutput
-Required.Proto3.ProtobufInput.RepeatedScalarSelectsLast.BOOL.ProtobufOutput
-Required.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.JsonOutput
-Required.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.ProtobufOutput
-Required.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.JsonOutput
-Required.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.ProtobufOutput
-Required.Proto3.ProtobufInput.ValidDataScalar.BOOL[4].JsonOutput
-Required.Proto3.ProtobufInput.ValidDataScalar.BOOL[4].ProtobufOutput
-Required.Proto3.ProtobufInput.ValidDataScalar.BOOL[6].JsonOutput
-Required.Proto3.ProtobufInput.ValidDataScalar.BOOL[6].ProtobufOutput
-Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.DefaultOutput.ProtobufOutput
Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Required.Proto2.JsonInput.StoresDefaultPrimitive.Validator
+Recommended.Proto2.JsonInput.FieldNameExtension.Validator
diff --git a/conformance/failure_list_java.txt b/conformance/failure_list_java.txt
index dc1f9ba..e84e0ba 100644
--- a/conformance/failure_list_java.txt
+++ b/conformance/failure_list_java.txt
@@ -34,6 +34,7 @@
Recommended.Proto3.JsonInput.StringFieldUnpairedLowSurrogate
Recommended.Proto3.JsonInput.Uint32MapFieldKeyNotQuoted
Recommended.Proto3.JsonInput.Uint64MapFieldKeyNotQuoted
+Recommended.Proto2.JsonInput.FieldNameExtension.Validator
Required.Proto3.JsonInput.EnumFieldNotQuoted
Required.Proto3.JsonInput.Int32FieldLeadingZero
Required.Proto3.JsonInput.Int32FieldNegativeWithLeadingZero
@@ -45,3 +46,4 @@
Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.Proto2.JsonInput.StoresDefaultPrimitive.Validator
diff --git a/conformance/failure_list_php.txt b/conformance/failure_list_php.txt
index d30fb3d..1c7f92b 100644
--- a/conformance/failure_list_php.txt
+++ b/conformance/failure_list_php.txt
@@ -1,6 +1,7 @@
Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.Proto2.JsonInput.FieldNameExtension.Validator
Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter
@@ -61,10 +62,10 @@
Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.DefaultOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.PackedOutput.ProtobufOutput
+Required.Proto2.JsonInput.StoresDefaultPrimitive.Validator
Required.Proto3.JsonInput.DoubleFieldTooSmall
Required.Proto3.JsonInput.FloatFieldTooLarge
Required.Proto3.JsonInput.FloatFieldTooSmall
-Required.Proto3.JsonInput.Int32FieldLeadingSpace
Required.Proto3.JsonInput.Int32FieldNotInteger
Required.Proto3.JsonInput.Int64FieldNotInteger
Required.Proto3.JsonInput.OneofFieldDuplicate
@@ -76,8 +77,8 @@
Required.Proto3.JsonInput.Uint64FieldNotInteger
Required.Proto3.ProtobufInput.RepeatedScalarMessageMerge.JsonOutput
Required.Proto3.ProtobufInput.RepeatedScalarMessageMerge.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataOneof.MESSAGE.Merge.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataOneof.MESSAGE.Merge.ProtobufOutput
Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.JsonOutput
Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.JsonOutput
Required.Proto3.ProtobufInput.ValidDataScalar.FLOAT[2].JsonOutput
-Required.Proto3.ProtobufInput.ValidDataOneof.MESSAGE.Merge.JsonOutput
-Required.Proto3.ProtobufInput.ValidDataOneof.MESSAGE.Merge.ProtobufOutput
diff --git a/conformance/failure_list_php_c.txt b/conformance/failure_list_php_c.txt
index 5950c57..f6c6bc8 100644
--- a/conformance/failure_list_php_c.txt
+++ b/conformance/failure_list_php_c.txt
@@ -1,6 +1,7 @@
Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.Proto2.JsonInput.FieldNameExtension.Validator
Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator
@@ -18,37 +19,68 @@
Recommended.Proto3.JsonInput.TimestampHas6FractionalDigits.Validator
Recommended.Proto3.ProtobufInput.OneofZeroBytes.JsonOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.UnpackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.UnpackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.PackedOutput.ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataScalarBinary.ENUM[3].ProtobufOutput
Recommended.Proto3.ProtobufInput.ValidDataScalarBinary.ENUM[4].ProtobufOutput
Required.DurationProtoInputTooLarge.JsonOutput
Required.DurationProtoInputTooSmall.JsonOutput
+Required.Proto2.JsonInput.StoresDefaultPrimitive.Validator
Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
@@ -67,6 +99,7 @@
Required.Proto3.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
Required.Proto3.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
Required.Proto3.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataOneof.BYTES.DefaultValue.JsonOutput
Required.Proto3.ProtobufInput.ValidDataRepeated.BYTES.JsonOutput
Required.Proto3.ProtobufInput.ValidDataRepeated.BYTES.ProtobufOutput
Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.JsonOutput
@@ -76,34 +109,3 @@
Required.Proto3.ProtobufInput.ValidDataScalar.FLOAT[2].JsonOutput
Required.TimestampProtoInputTooLarge.JsonOutput
Required.TimestampProtoInputTooSmall.JsonOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.UnpackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.UnpackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.UnpackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.PackedOutput.ProtobufOutput
-Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.PackedOutput.ProtobufOutput
-Required.Proto3.ProtobufInput.ValidDataOneof.BYTES.DefaultValue.JsonOutput
diff --git a/conformance/failure_list_php_c_32.txt b/conformance/failure_list_php_c_32.txt
new file mode 100644
index 0000000..280e5ff
--- /dev/null
+++ b/conformance/failure_list_php_c_32.txt
@@ -0,0 +1,144 @@
+Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
+Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
+Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.Proto2.JsonInput.FieldNameExtension.Validator
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
+Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
+Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas6FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHas9FractionalDigits.Validator
+Recommended.Proto3.JsonInput.DurationHasZeroFractionalDigit.Validator
+Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter
+Recommended.Proto3.JsonInput.MapFieldValueIsNull
+Recommended.Proto3.JsonInput.OneofZeroBytes.JsonOutput
+Recommended.Proto3.JsonInput.RepeatedFieldMessageElementIsNull
+Recommended.Proto3.JsonInput.RepeatedFieldPrimitiveElementIsNull
+Recommended.Proto3.JsonInput.StringEndsWithEscapeChar
+Recommended.Proto3.JsonInput.StringFieldSurrogateInWrongOrder
+Recommended.Proto3.JsonInput.StringFieldUnpairedHighSurrogate
+Recommended.Proto3.JsonInput.StringFieldUnpairedLowSurrogate
+Recommended.Proto3.JsonInput.TimestampHas3FractionalDigits.Validator
+Recommended.Proto3.JsonInput.TimestampHas6FractionalDigits.Validator
+Recommended.Proto3.JsonInput.TimestampHas9FractionalDigits.Validator
+Recommended.Proto3.JsonInput.TimestampHasZeroFractionalDigit.Validator
+Recommended.Proto3.JsonInput.TimestampZeroNormalized.Validator
+Recommended.Proto3.ProtobufInput.OneofZeroBytes.JsonOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.UnpackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.UnpackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.DefaultOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.PackedOutput.ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataScalarBinary.ENUM[3].ProtobufOutput
+Recommended.Proto3.ProtobufInput.ValidDataScalarBinary.ENUM[4].ProtobufOutput
+Required.DurationProtoInputTooLarge.JsonOutput
+Required.DurationProtoInputTooSmall.JsonOutput
+Required.Proto2.JsonInput.StoresDefaultPrimitive.Validator
+Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
+Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
+Required.Proto3.JsonInput.DoubleFieldNan.JsonOutput
+Required.Proto3.JsonInput.DurationMaxValue.JsonOutput
+Required.Proto3.JsonInput.DurationMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.DurationMinValue.JsonOutput
+Required.Proto3.JsonInput.DurationMinValue.ProtobufOutput
+Required.Proto3.JsonInput.DurationRepeatedValue.JsonOutput
+Required.Proto3.JsonInput.DurationRepeatedValue.ProtobufOutput
+Required.Proto3.JsonInput.FloatFieldInfinity.JsonOutput
+Required.Proto3.JsonInput.FloatFieldNan.JsonOutput
+Required.Proto3.JsonInput.FloatFieldNegativeInfinity.JsonOutput
+Required.Proto3.JsonInput.Int64FieldMaxValue.JsonOutput
+Required.Proto3.JsonInput.Int64FieldMaxValueNotQuoted.JsonOutput
+Required.Proto3.JsonInput.Int64FieldMaxValueNotQuoted.ProtobufOutput
+Required.Proto3.JsonInput.Int64FieldMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.Int64FieldMinValue.JsonOutput
+Required.Proto3.JsonInput.Int64FieldMinValueNotQuoted.JsonOutput
+Required.Proto3.JsonInput.Int64FieldMinValueNotQuoted.ProtobufOutput
+Required.Proto3.JsonInput.Int64FieldMinValue.ProtobufOutput
+Required.Proto3.JsonInput.OneofFieldDuplicate
+Required.Proto3.JsonInput.RejectTopLevelNull
+Required.Proto3.JsonInput.StringFieldSurrogatePair.JsonOutput
+Required.Proto3.JsonInput.StringFieldSurrogatePair.ProtobufOutput
+Required.Proto3.JsonInput.TimestampLeap.JsonOutput
+Required.Proto3.JsonInput.TimestampLeap.ProtobufOutput
+Required.Proto3.JsonInput.TimestampMaxValue.JsonOutput
+Required.Proto3.JsonInput.TimestampMaxValue.ProtobufOutput
+Required.Proto3.JsonInput.TimestampMinValue.JsonOutput
+Required.Proto3.JsonInput.TimestampMinValue.ProtobufOutput
+Required.Proto3.JsonInput.TimestampRepeatedValue.JsonOutput
+Required.Proto3.JsonInput.TimestampRepeatedValue.ProtobufOutput
+Required.Proto3.JsonInput.TimestampWithNegativeOffset.JsonOutput
+Required.Proto3.JsonInput.TimestampWithNegativeOffset.ProtobufOutput
+Required.Proto3.JsonInput.TimestampWithPositiveOffset.JsonOutput
+Required.Proto3.JsonInput.TimestampWithPositiveOffset.ProtobufOutput
+Required.Proto3.JsonInput.Uint64FieldMaxValue.JsonOutput
+Required.Proto3.JsonInput.Uint64FieldMaxValueNotQuoted.JsonOutput
+Required.Proto3.JsonInput.Uint64FieldMaxValueNotQuoted.ProtobufOutput
+Required.Proto3.JsonInput.Uint64FieldMaxValue.ProtobufOutput
+Required.Proto3.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
+Required.Proto3.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
+Required.Proto3.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataOneof.BYTES.DefaultValue.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.BYTES.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.BYTES.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.STRING.JsonOutput
+Required.Proto3.ProtobufInput.ValidDataRepeated.STRING.ProtobufOutput
+Required.Proto3.ProtobufInput.ValidDataScalar.FLOAT[2].JsonOutput
+Required.TimestampProtoInputTooLarge.JsonOutput
+Required.TimestampProtoInputTooSmall.JsonOutput
diff --git a/conformance/failure_list_php_zts_c.txt b/conformance/failure_list_php_zts_c.txt
deleted file mode 100644
index d9a8fe3..0000000
--- a/conformance/failure_list_php_zts_c.txt
+++ /dev/null
@@ -1,225 +0,0 @@
-Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
-Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
-Recommended.FieldMaskTooManyUnderscore.JsonOutput
-Recommended.JsonInput.BoolFieldIntegerOne
-Recommended.JsonInput.BoolFieldIntegerZero
-Recommended.JsonInput.DurationHas3FractionalDigits.Validator
-Recommended.JsonInput.DurationHas6FractionalDigits.Validator
-Recommended.JsonInput.DurationHas9FractionalDigits.Validator
-Recommended.JsonInput.DurationHasZeroFractionalDigit.Validator
-Recommended.JsonInput.Int64FieldBeString.Validator
-Recommended.JsonInput.OneofZeroBytes.JsonOutput
-Recommended.JsonInput.OneofZeroBytes.ProtobufOutput
-Recommended.JsonInput.OneofZeroDouble.JsonOutput
-Recommended.JsonInput.OneofZeroDouble.ProtobufOutput
-Recommended.JsonInput.OneofZeroFloat.JsonOutput
-Recommended.JsonInput.OneofZeroFloat.ProtobufOutput
-Recommended.JsonInput.OneofZeroString.JsonOutput
-Recommended.JsonInput.OneofZeroString.ProtobufOutput
-Recommended.JsonInput.OneofZeroUint32.JsonOutput
-Recommended.JsonInput.OneofZeroUint32.ProtobufOutput
-Recommended.JsonInput.OneofZeroUint64.JsonOutput
-Recommended.JsonInput.OneofZeroUint64.ProtobufOutput
-Recommended.JsonInput.StringEndsWithEscapeChar
-Recommended.JsonInput.StringFieldSurrogateInWrongOrder
-Recommended.JsonInput.StringFieldUnpairedHighSurrogate
-Recommended.JsonInput.StringFieldUnpairedLowSurrogate
-Recommended.JsonInput.TimestampHas3FractionalDigits.Validator
-Recommended.JsonInput.TimestampHas6FractionalDigits.Validator
-Recommended.JsonInput.TimestampHas9FractionalDigits.Validator
-Recommended.JsonInput.TimestampHasZeroFractionalDigit.Validator
-Recommended.JsonInput.TimestampZeroNormalized.Validator
-Recommended.JsonInput.Uint64FieldBeString.Validator
-Recommended.ProtobufInput.OneofZeroBytes.JsonOutput
-Recommended.ProtobufInput.OneofZeroBytes.ProtobufOutput
-Recommended.ProtobufInput.OneofZeroString.JsonOutput
-Recommended.ProtobufInput.OneofZeroString.ProtobufOutput
-Required.DurationProtoInputTooLarge.JsonOutput
-Required.DurationProtoInputTooSmall.JsonOutput
-Required.JsonInput.AllFieldAcceptNull.ProtobufOutput
-Required.JsonInput.Any.JsonOutput
-Required.JsonInput.Any.ProtobufOutput
-Required.JsonInput.AnyNested.JsonOutput
-Required.JsonInput.AnyNested.ProtobufOutput
-Required.JsonInput.AnyUnorderedTypeTag.JsonOutput
-Required.JsonInput.AnyUnorderedTypeTag.ProtobufOutput
-Required.JsonInput.AnyWithDuration.JsonOutput
-Required.JsonInput.AnyWithDuration.ProtobufOutput
-Required.JsonInput.AnyWithFieldMask.JsonOutput
-Required.JsonInput.AnyWithFieldMask.ProtobufOutput
-Required.JsonInput.AnyWithInt32ValueWrapper.JsonOutput
-Required.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput
-Required.JsonInput.AnyWithStruct.JsonOutput
-Required.JsonInput.AnyWithStruct.ProtobufOutput
-Required.JsonInput.AnyWithTimestamp.JsonOutput
-Required.JsonInput.AnyWithTimestamp.ProtobufOutput
-Required.JsonInput.AnyWithValueForInteger.JsonOutput
-Required.JsonInput.AnyWithValueForInteger.ProtobufOutput
-Required.JsonInput.AnyWithValueForJsonObject.JsonOutput
-Required.JsonInput.AnyWithValueForJsonObject.ProtobufOutput
-Required.JsonInput.BoolFieldFalse.ProtobufOutput
-Required.JsonInput.BoolMapField.JsonOutput
-Required.JsonInput.DoubleFieldInfinity.JsonOutput
-Required.JsonInput.DoubleFieldInfinity.ProtobufOutput
-Required.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
-Required.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
-Required.JsonInput.DoubleFieldMaxPositiveValue.JsonOutput
-Required.JsonInput.DoubleFieldMaxPositiveValue.ProtobufOutput
-Required.JsonInput.DoubleFieldMinNegativeValue.JsonOutput
-Required.JsonInput.DoubleFieldMinNegativeValue.ProtobufOutput
-Required.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
-Required.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
-Required.JsonInput.DoubleFieldNan.JsonOutput
-Required.JsonInput.DoubleFieldNan.ProtobufOutput
-Required.JsonInput.DoubleFieldNegativeInfinity.JsonOutput
-Required.JsonInput.DoubleFieldNegativeInfinity.ProtobufOutput
-Required.JsonInput.DoubleFieldQuotedValue.JsonOutput
-Required.JsonInput.DoubleFieldQuotedValue.ProtobufOutput
-Required.JsonInput.DurationMaxValue.JsonOutput
-Required.JsonInput.DurationMaxValue.ProtobufOutput
-Required.JsonInput.DurationMinValue.JsonOutput
-Required.JsonInput.DurationMinValue.ProtobufOutput
-Required.JsonInput.DurationRepeatedValue.JsonOutput
-Required.JsonInput.DurationRepeatedValue.ProtobufOutput
-Required.JsonInput.EnumField.ProtobufOutput
-Required.JsonInput.EnumFieldNumericValueNonZero.JsonOutput
-Required.JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
-Required.JsonInput.EnumFieldNumericValueZero.JsonOutput
-Required.JsonInput.EnumFieldNumericValueZero.ProtobufOutput
-Required.JsonInput.EnumFieldUnknownValue.Validator
-Required.JsonInput.FieldMask.JsonOutput
-Required.JsonInput.FieldMask.ProtobufOutput
-Required.JsonInput.FloatFieldInfinity.JsonOutput
-Required.JsonInput.FloatFieldInfinity.ProtobufOutput
-Required.JsonInput.FloatFieldNan.JsonOutput
-Required.JsonInput.FloatFieldNan.ProtobufOutput
-Required.JsonInput.FloatFieldNegativeInfinity.JsonOutput
-Required.JsonInput.FloatFieldNegativeInfinity.ProtobufOutput
-Required.JsonInput.FloatFieldQuotedValue.JsonOutput
-Required.JsonInput.FloatFieldQuotedValue.ProtobufOutput
-Required.JsonInput.FloatFieldTooLarge
-Required.JsonInput.FloatFieldTooSmall
-Required.JsonInput.Int32FieldExponentialFormat.JsonOutput
-Required.JsonInput.Int32FieldExponentialFormat.ProtobufOutput
-Required.JsonInput.Int32FieldFloatTrailingZero.JsonOutput
-Required.JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
-Required.JsonInput.Int32FieldMaxFloatValue.JsonOutput
-Required.JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
-Required.JsonInput.Int32FieldMinFloatValue.JsonOutput
-Required.JsonInput.Int32FieldMinFloatValue.ProtobufOutput
-Required.JsonInput.Int32FieldStringValue.JsonOutput
-Required.JsonInput.Int32FieldStringValue.ProtobufOutput
-Required.JsonInput.Int32FieldStringValueEscaped.JsonOutput
-Required.JsonInput.Int32FieldStringValueEscaped.ProtobufOutput
-Required.JsonInput.Int32MapEscapedKey.JsonOutput
-Required.JsonInput.Int32MapEscapedKey.ProtobufOutput
-Required.JsonInput.Int32MapField.JsonOutput
-Required.JsonInput.Int32MapField.ProtobufOutput
-Required.JsonInput.Int64FieldMaxValue.JsonOutput
-Required.JsonInput.Int64FieldMaxValue.ProtobufOutput
-Required.JsonInput.Int64FieldMinValue.JsonOutput
-Required.JsonInput.Int64FieldMinValue.ProtobufOutput
-Required.JsonInput.Int64MapEscapedKey.JsonOutput
-Required.JsonInput.Int64MapEscapedKey.ProtobufOutput
-Required.JsonInput.Int64MapField.JsonOutput
-Required.JsonInput.Int64MapField.ProtobufOutput
-Required.JsonInput.MessageField.JsonOutput
-Required.JsonInput.MessageField.ProtobufOutput
-Required.JsonInput.MessageMapField.JsonOutput
-Required.JsonInput.MessageMapField.ProtobufOutput
-Required.JsonInput.MessageRepeatedField.JsonOutput
-Required.JsonInput.MessageRepeatedField.ProtobufOutput
-Required.JsonInput.OptionalBoolWrapper.JsonOutput
-Required.JsonInput.OptionalBoolWrapper.ProtobufOutput
-Required.JsonInput.OptionalBytesWrapper.JsonOutput
-Required.JsonInput.OptionalBytesWrapper.ProtobufOutput
-Required.JsonInput.OptionalDoubleWrapper.JsonOutput
-Required.JsonInput.OptionalDoubleWrapper.ProtobufOutput
-Required.JsonInput.OptionalFloatWrapper.JsonOutput
-Required.JsonInput.OptionalFloatWrapper.ProtobufOutput
-Required.JsonInput.OptionalInt32Wrapper.JsonOutput
-Required.JsonInput.OptionalInt32Wrapper.ProtobufOutput
-Required.JsonInput.OptionalInt64Wrapper.JsonOutput
-Required.JsonInput.OptionalInt64Wrapper.ProtobufOutput
-Required.JsonInput.OptionalStringWrapper.JsonOutput
-Required.JsonInput.OptionalStringWrapper.ProtobufOutput
-Required.JsonInput.OptionalUint32Wrapper.JsonOutput
-Required.JsonInput.OptionalUint32Wrapper.ProtobufOutput
-Required.JsonInput.OptionalUint64Wrapper.JsonOutput
-Required.JsonInput.OptionalUint64Wrapper.ProtobufOutput
-Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput
-Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput
-Required.JsonInput.PrimitiveRepeatedField.JsonOutput
-Required.JsonInput.PrimitiveRepeatedField.ProtobufOutput
-Required.JsonInput.RepeatedBoolWrapper.JsonOutput
-Required.JsonInput.RepeatedBoolWrapper.ProtobufOutput
-Required.JsonInput.RepeatedBytesWrapper.JsonOutput
-Required.JsonInput.RepeatedBytesWrapper.ProtobufOutput
-Required.JsonInput.RepeatedDoubleWrapper.JsonOutput
-Required.JsonInput.RepeatedDoubleWrapper.ProtobufOutput
-Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
-Required.JsonInput.RepeatedFloatWrapper.JsonOutput
-Required.JsonInput.RepeatedFloatWrapper.ProtobufOutput
-Required.JsonInput.RepeatedInt32Wrapper.JsonOutput
-Required.JsonInput.RepeatedInt32Wrapper.ProtobufOutput
-Required.JsonInput.RepeatedInt64Wrapper.JsonOutput
-Required.JsonInput.RepeatedInt64Wrapper.ProtobufOutput
-Required.JsonInput.RepeatedStringWrapper.JsonOutput
-Required.JsonInput.RepeatedStringWrapper.ProtobufOutput
-Required.JsonInput.RepeatedUint32Wrapper.JsonOutput
-Required.JsonInput.RepeatedUint32Wrapper.ProtobufOutput
-Required.JsonInput.RepeatedUint64Wrapper.JsonOutput
-Required.JsonInput.RepeatedUint64Wrapper.ProtobufOutput
-Required.JsonInput.StringFieldEscape.JsonOutput
-Required.JsonInput.StringFieldEscape.ProtobufOutput
-Required.JsonInput.StringFieldNotAString
-Required.JsonInput.StringFieldSurrogatePair.JsonOutput
-Required.JsonInput.StringFieldSurrogatePair.ProtobufOutput
-Required.JsonInput.StringFieldUnicodeEscape.JsonOutput
-Required.JsonInput.StringFieldUnicodeEscape.ProtobufOutput
-Required.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.JsonOutput
-Required.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.ProtobufOutput
-Required.JsonInput.Struct.JsonOutput
-Required.JsonInput.Struct.ProtobufOutput
-Required.JsonInput.TimestampMaxValue.JsonOutput
-Required.JsonInput.TimestampMaxValue.ProtobufOutput
-Required.JsonInput.TimestampMinValue.JsonOutput
-Required.JsonInput.TimestampMinValue.ProtobufOutput
-Required.JsonInput.TimestampRepeatedValue.JsonOutput
-Required.JsonInput.TimestampRepeatedValue.ProtobufOutput
-Required.JsonInput.TimestampWithNegativeOffset.JsonOutput
-Required.JsonInput.TimestampWithNegativeOffset.ProtobufOutput
-Required.JsonInput.TimestampWithPositiveOffset.JsonOutput
-Required.JsonInput.TimestampWithPositiveOffset.ProtobufOutput
-Required.JsonInput.Uint32FieldMaxFloatValue.JsonOutput
-Required.JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
-Required.JsonInput.Uint32MapField.JsonOutput
-Required.JsonInput.Uint32MapField.ProtobufOutput
-Required.JsonInput.Uint64FieldMaxValue.JsonOutput
-Required.JsonInput.Uint64FieldMaxValue.ProtobufOutput
-Required.JsonInput.Uint64MapField.JsonOutput
-Required.JsonInput.Uint64MapField.ProtobufOutput
-Required.JsonInput.ValueAcceptBool.JsonOutput
-Required.JsonInput.ValueAcceptBool.ProtobufOutput
-Required.JsonInput.ValueAcceptFloat.JsonOutput
-Required.JsonInput.ValueAcceptFloat.ProtobufOutput
-Required.JsonInput.ValueAcceptInteger.JsonOutput
-Required.JsonInput.ValueAcceptInteger.ProtobufOutput
-Required.JsonInput.ValueAcceptList.JsonOutput
-Required.JsonInput.ValueAcceptList.ProtobufOutput
-Required.JsonInput.ValueAcceptNull.JsonOutput
-Required.JsonInput.ValueAcceptNull.ProtobufOutput
-Required.JsonInput.ValueAcceptObject.JsonOutput
-Required.JsonInput.ValueAcceptObject.ProtobufOutput
-Required.JsonInput.ValueAcceptString.JsonOutput
-Required.JsonInput.ValueAcceptString.ProtobufOutput
-Required.JsonInput.WrapperTypesWithNullValue.ProtobufOutput
-Required.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
-Required.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
-Required.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
-Required.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
-Required.ProtobufInput.RepeatedScalarSelectsLast.FIXED32.ProtobufOutput
-Required.ProtobufInput.RepeatedScalarSelectsLast.FIXED64.ProtobufOutput
-Required.ProtobufInput.RepeatedScalarSelectsLast.UINT64.ProtobufOutput
-Required.TimestampProtoInputTooLarge.JsonOutput
-Required.TimestampProtoInputTooSmall.JsonOutput
diff --git a/conformance/failure_list_ruby.txt b/conformance/failure_list_ruby.txt
index 4573c59..ff206dc 100644
--- a/conformance/failure_list_ruby.txt
+++ b/conformance/failure_list_ruby.txt
@@ -1,6 +1,7 @@
Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.Proto2.JsonInput.FieldNameExtension.Validator
Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput
Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput
Recommended.Proto3.JsonInput.DurationHas3FractionalDigits.Validator
@@ -77,6 +78,7 @@
Recommended.Proto3.ProtobufInput.ValidDataScalarBinary.ENUM[4].ProtobufOutput
Required.DurationProtoInputTooLarge.JsonOutput
Required.DurationProtoInputTooSmall.JsonOutput
+Required.Proto2.JsonInput.StoresDefaultPrimitive.Validator
Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
Required.Proto3.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
Required.Proto3.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
@@ -94,25 +96,7 @@
Required.Proto3.JsonInput.IgnoreUnknownJsonString.ProtobufOutput
Required.Proto3.JsonInput.IgnoreUnknownJsonTrue.ProtobufOutput
Required.Proto3.JsonInput.OneofFieldDuplicate
-Required.Proto3.JsonInput.OptionalBoolWrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalBytesWrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalDoubleWrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalFloatWrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalInt32Wrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalInt64Wrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalStringWrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalUint32Wrapper.JsonOutput
-Required.Proto3.JsonInput.OptionalUint64Wrapper.JsonOutput
Required.Proto3.JsonInput.RejectTopLevelNull
-Required.Proto3.JsonInput.RepeatedBoolWrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedBytesWrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedDoubleWrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedFloatWrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedInt32Wrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedInt64Wrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedStringWrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedUint32Wrapper.JsonOutput
-Required.Proto3.JsonInput.RepeatedUint64Wrapper.JsonOutput
Required.Proto3.JsonInput.StringFieldSurrogatePair.JsonOutput
Required.Proto3.JsonInput.StringFieldSurrogatePair.ProtobufOutput
Required.Proto3.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
diff --git a/conformance/text_format_conformance_suite.cc b/conformance/text_format_conformance_suite.cc
index fc7b251..6574b10 100644
--- a/conformance/text_format_conformance_suite.cc
+++ b/conformance/text_format_conformance_suite.cc
@@ -313,6 +313,66 @@
}
}
)");
+
+ // Map fields
+ TestAllTypesProto3 prototype;
+ (*prototype.mutable_map_string_string())["c"] = "value";
+ (*prototype.mutable_map_string_string())["b"] = "value";
+ (*prototype.mutable_map_string_string())["a"] = "value";
+ RunValidTextFormatTestWithMessage("AlphabeticallySortedMapStringKeys",
+ REQUIRED,
+ R"(
+ map_string_string {
+ key: "a"
+ value: "value"
+ }
+ map_string_string {
+ key: "b"
+ value: "value"
+ }
+ map_string_string {
+ key: "c"
+ value: "value"
+ }
+ )",
+ prototype);
+
+ prototype.Clear();
+ (*prototype.mutable_map_int32_int32())[3] = 0;
+ (*prototype.mutable_map_int32_int32())[2] = 0;
+ (*prototype.mutable_map_int32_int32())[1] = 0;
+ RunValidTextFormatTestWithMessage("AlphabeticallySortedMapIntKeys", REQUIRED,
+ R"(
+ map_int32_int32 {
+ key: 1
+ value: 0
+ }
+ map_int32_int32 {
+ key: 2
+ value: 0
+ }
+ map_int32_int32 {
+ key: 3
+ value: 0
+ }
+ )",
+ prototype);
+
+ prototype.Clear();
+ (*prototype.mutable_map_bool_bool())[true] = false;
+ (*prototype.mutable_map_bool_bool())[false] = false;
+ RunValidTextFormatTestWithMessage("AlphabeticallySortedMapBoolKeys", REQUIRED,
+ R"(
+ map_bool_bool {
+ key: false
+ value: false
+ }
+ map_bool_bool {
+ key: true
+ value: false
+ }
+ )",
+ prototype);
}
} // namespace protobuf
diff --git a/conformance/text_format_conformance_suite.h b/conformance/text_format_conformance_suite.h
index dd258f5..d68f4aa 100644
--- a/conformance/text_format_conformance_suite.h
+++ b/conformance/text_format_conformance_suite.h
@@ -42,19 +42,19 @@
private:
void RunSuiteImpl();
- void RunValidTextFormatTest(const string& test_name, ConformanceLevel level,
- const string& input);
- void RunValidTextFormatTestProto2(const string& test_name,
+ void RunValidTextFormatTest(const std::string& test_name,
+ ConformanceLevel level, const std::string& input);
+ void RunValidTextFormatTestProto2(const std::string& test_name,
ConformanceLevel level,
- const string& input);
- void RunValidTextFormatTestWithMessage(const string& test_name,
+ const std::string& input);
+ void RunValidTextFormatTestWithMessage(const std::string& test_name,
ConformanceLevel level,
- const string& input_text,
+ const std::string& input_text,
const Message& prototype);
- void RunValidUnknownTextFormatTest(const string& test_name,
+ void RunValidUnknownTextFormatTest(const std::string& test_name,
const Message& message);
- void ExpectParseFailure(const string& test_name, ConformanceLevel level,
- const string& input);
+ void ExpectParseFailure(const std::string& test_name, ConformanceLevel level,
+ const std::string& input);
bool ParseTextFormatResponse(const conformance::ConformanceResponse& response,
const ConformanceRequestSetting& setting,
Message* test_message);
diff --git a/conformance/text_format_failure_list_java.txt b/conformance/text_format_failure_list_java.txt
old mode 100755
new mode 100644
diff --git a/conformance/third_party/jsoncpp/json.h b/conformance/third_party/jsoncpp/json.h
index 32fd072..5639c92 100644
--- a/conformance/third_party/jsoncpp/json.h
+++ b/conformance/third_party/jsoncpp/json.h
@@ -1019,7 +1019,7 @@
* - ".name1.name2.name3"
* - ".[0][1][2].name1[3]"
* - ".%" => member name is provided as parameter
- * - ".[%]" => index is provied as parameter
+ * - ".[%]" => index is provided as parameter
*/
class JSON_API Path {
public:
@@ -1371,7 +1371,7 @@
*/
std::string getFormattedErrorMessages() const;
- /** \brief Returns a vector of structured erros encounted while parsing.
+ /** \brief Returns a vector of structured errors encounted while parsing.
* \return A (possibly empty) vector of StructuredError objects. Currently
* only one error can be returned, but the caller should tolerate
* multiple
@@ -1816,7 +1816,7 @@
*
* The JSON document is written in a single line. It is not intended for 'human'
*consumption,
- * but may be usefull to support feature such as RPC where bandwith is limited.
+ * but may be useful to support feature such as RPC where bandwidth is limited.
* \sa Reader, Value
* \deprecated Use StreamWriterBuilder.
*/
diff --git a/conformance/third_party/jsoncpp/jsoncpp.cpp b/conformance/third_party/jsoncpp/jsoncpp.cpp
index 4d3e0f2..d313d05 100644
--- a/conformance/third_party/jsoncpp/jsoncpp.cpp
+++ b/conformance/third_party/jsoncpp/jsoncpp.cpp
@@ -4112,7 +4112,7 @@
sprintf(formatString, "%%.%dg", precision);
// Print into the buffer. We need not request the alternative representation
- // that always has a decimal point because JSON doesn't distingish the
+ // that always has a decimal point because JSON doesn't distinguish the
// concepts of reals and integers.
if (isfinite(value)) {
len = snprintf(buffer, sizeof(buffer), formatString, value);
diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec
index d1a5338..e2a46ce 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.11.0-rc1</version>
+ <version>3.12.0-rc2</version>
<authors>Google Inc.</authors>
<owners>protobuf-packages</owners>
<licenseUrl>https://github.com/protocolbuffers/protobuf/blob/master/LICENSE</licenseUrl>
@@ -20,7 +20,6 @@
<file src="protoc\windows_x64\protoc.exe" target="tools\windows_x64\protoc.exe"/>
<file src="protoc\linux_x86\protoc" target="tools\linux_x86\protoc"/>
<file src="protoc\linux_x64\protoc" target="tools\linux_x64\protoc"/>
- <file src="protoc\macosx_x86\protoc" target="tools\macosx_x86\protoc"/>
<file src="protoc\macosx_x64\protoc" target="tools\macosx_x64\protoc"/>
<file src="..\src\google\protobuf\any.proto" target="tools\google\protobuf"/>
<file src="..\src\google\protobuf\api.proto" target="tools\google\protobuf"/>
diff --git a/csharp/build_tools.sh b/csharp/build_tools.sh
index 182c5c5..771affd 100755
--- a/csharp/build_tools.sh
+++ b/csharp/build_tools.sh
@@ -19,7 +19,6 @@
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 \
diff --git a/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_proto3.proto b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_proto3.proto
index f59d217..6235d3d 100644
--- a/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_proto3.proto
+++ b/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_proto3.proto
@@ -142,7 +142,7 @@
}
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
NestedTestAllTypes child = 1;
TestAllTypes payload = 2;
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs
index 73a578d..11d06f1 100644
--- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs
@@ -201,29 +201,29 @@
[Test]
public void DecodeZigZag32()
{
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
- Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
- Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
- Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
- Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
- Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(0));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(1));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(2));
+ Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag32(3));
+ Assert.AreEqual(0x3FFFFFFF, ParsingPrimitives.DecodeZigZag32(0x7FFFFFFE));
+ Assert.AreEqual(unchecked((int) 0xC0000000), ParsingPrimitives.DecodeZigZag32(0x7FFFFFFF));
+ Assert.AreEqual(0x7FFFFFFF, ParsingPrimitives.DecodeZigZag32(0xFFFFFFFE));
+ Assert.AreEqual(unchecked((int) 0x80000000), ParsingPrimitives.DecodeZigZag32(0xFFFFFFFF));
}
[Test]
public void DecodeZigZag64()
{
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
- Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
- Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
- Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
- Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
- Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
- Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
- Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(0));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(1));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(2));
+ Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag64(3));
+ Assert.AreEqual(0x000000003FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFFL));
+ Assert.AreEqual(0x000000007FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFFL));
+ Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0x8000000000000000L), ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
[Test]
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
index 01bd321..f25e14e 100644
--- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
@@ -247,26 +247,26 @@
{
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
- Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
- Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
+ Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
+ Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
}
[Test]
public void RoundTripZigZag64()
{
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
- Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
- Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
+ Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
+ Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
Assert.AreEqual(856912304801416L,
- CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
+ ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
Assert.AreEqual(-75123905439571256L,
- CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
+ ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
}
[Test]
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs
index 3907666..a5825a0 100644
--- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs
+++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/FieldCodecTest.cs
@@ -128,7 +128,7 @@
codedOutput.Flush();
stream.Position = 0;
var codedInput = new CodedInputStream(stream);
- Assert.AreEqual(sampleValue, codec.ValueReader(codedInput));
+ Assert.AreEqual(sampleValue, codec.Read(codedInput));
Assert.IsTrue(codedInput.IsAtEnd);
}
@@ -178,7 +178,7 @@
Assert.AreEqual(stream.Position, codec.ValueSizeCalculator(codec.DefaultValue));
stream.Position = 0;
var codedInput = new CodedInputStream(stream);
- Assert.AreEqual(codec.DefaultValue, codec.ValueReader(codedInput));
+ Assert.AreEqual(codec.DefaultValue, codec.Read(codedInput));
}
}
diff --git a/csharp/compatibility_tests/v3.0.0/test.sh b/csharp/compatibility_tests/v3.0.0/test.sh
index 4ee88fc..f893d64 100755
--- a/csharp/compatibility_tests/v3.0.0/test.sh
+++ b/csharp/compatibility_tests/v3.0.0/test.sh
@@ -37,10 +37,10 @@
# The old version of protobuf that we are testing compatibility against. This
# is usually the same as TEST_VERSION (i.e., we use the tests extracted from
# that version to test compatibility of the newest runtime against it), but it
-# is also possible to use this same test set to test the compatibiilty of the
+# is also possible to use this same test set to test the compatibility of the
# latest version against other versions.
OLD_VERSION=$1
-OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
+OLD_VERSION_PROTOC=https://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
echo "Running compatibility tests with $OLD_VERSION"
diff --git a/csharp/generate_protos.sh b/csharp/generate_protos.sh
index 66d87c0..49a5a42 100755
--- a/csharp/generate_protos.sh
+++ b/csharp/generate_protos.sh
@@ -58,9 +58,14 @@
csharp/protos/unittest.proto \
csharp/protos/unittest_import.proto \
csharp/protos/unittest_import_public.proto \
+ csharp/protos/unittest_issue6936_a.proto \
+ csharp/protos/unittest_issue6936_b.proto \
+ csharp/protos/unittest_issue6936_c.proto \
+ csharp/protos/unittest_selfreferential_options.proto \
src/google/protobuf/unittest_well_known_types.proto \
src/google/protobuf/test_messages_proto3.proto \
- src/google/protobuf/test_messages_proto2.proto
+ src/google/protobuf/test_messages_proto2.proto \
+ src/google/protobuf/unittest_proto3_optional.proto
# AddressBook sample protos
$PROTOC -Iexamples -Isrc --csharp_out=csharp/src/AddressBook \
diff --git a/csharp/install_dotnet_sdk.ps1 b/csharp/install_dotnet_sdk.ps1
old mode 100644
new mode 100755
index b4132ab..9e300ed
--- a/csharp/install_dotnet_sdk.ps1
+++ b/csharp/install_dotnet_sdk.ps1
@@ -19,3 +19,6 @@
Write-Host "Downloading install script: $InstallScriptUrl => $InstallScriptPath"
Invoke-WebRequest -Uri $InstallScriptUrl -OutFile $InstallScriptPath
&$InstallScriptPath -Version $SDKVersion
+
+# Also install dotnet SDK LTS which is required to run some of the tests
+&$InstallScriptPath -Version 2.1.802
diff --git a/csharp/protos/unittest.proto b/csharp/protos/unittest.proto
index f47c7bf..9628b9e 100644
--- a/csharp/protos/unittest.proto
+++ b/csharp/protos/unittest.proto
@@ -182,7 +182,7 @@
}
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
optional NestedTestAllTypes child = 1;
optional TestAllTypes payload = 2;
diff --git a/csharp/protos/unittest_custom_options_proto3.proto b/csharp/protos/unittest_custom_options_proto3.proto
index 87bd0f7..0e7c2e2 100644
--- a/csharp/protos/unittest_custom_options_proto3.proto
+++ b/csharp/protos/unittest_custom_options_proto3.proto
@@ -286,7 +286,7 @@
}
// Allow Aggregate to be used as an option at all possible locations
-// in the .proto grammer.
+// in the .proto grammar.
extend google.protobuf.FileOptions { Aggregate fileopt = 15478479; }
extend google.protobuf.MessageOptions { Aggregate msgopt = 15480088; }
extend google.protobuf.FieldOptions { Aggregate fieldopt = 15481374; }
diff --git a/csharp/protos/unittest_issue6936_a.proto b/csharp/protos/unittest_issue6936_a.proto
new file mode 100644
index 0000000..097d083
--- /dev/null
+++ b/csharp/protos/unittest_issue6936_a.proto
@@ -0,0 +1,15 @@
+syntax = "proto3";
+
+package unittest_issues;
+
+option csharp_namespace = "UnitTest.Issues.TestProtos";
+
+// This file is used as part of a unit test for issue 6936
+// We don't need to use it, we just have to import it in both
+// "extensions_issue6936_b.proto" and "extensions_issue6936_c.proto"
+
+import "google/protobuf/descriptor.proto";
+
+extend google.protobuf.MessageOptions {
+ string opt = 50000;
+}
\ No newline at end of file
diff --git a/csharp/protos/unittest_issue6936_b.proto b/csharp/protos/unittest_issue6936_b.proto
new file mode 100644
index 0000000..8f71683
--- /dev/null
+++ b/csharp/protos/unittest_issue6936_b.proto
@@ -0,0 +1,14 @@
+syntax = "proto3";
+
+import "unittest_issue6936_a.proto";
+
+package unittest_issues;
+
+option csharp_namespace = "UnitTest.Issues.TestProtos";
+
+// This file is used as part of a unit test for issue 6936
+// We don't need to use it, we just have to import it in "unittest_issue6936_c.proto"
+
+message Foo {
+ option (opt) = "foo";
+}
\ No newline at end of file
diff --git a/csharp/protos/unittest_issue6936_c.proto b/csharp/protos/unittest_issue6936_c.proto
new file mode 100644
index 0000000..40004ec
--- /dev/null
+++ b/csharp/protos/unittest_issue6936_c.proto
@@ -0,0 +1,16 @@
+syntax = "proto3";
+
+import "unittest_issue6936_a.proto";
+import "unittest_issue6936_b.proto";
+
+package unittest_issues;
+
+option csharp_namespace = "UnitTest.Issues.TestProtos";
+
+// This file is used as part of a unit test for issue 6936
+// We don't need to use it, we just have to load it at runtime
+
+message Bar {
+ option (opt) = "bar";
+ Foo foo = 1;
+}
\ No newline at end of file
diff --git a/csharp/protos/unittest_proto3.proto b/csharp/protos/unittest_proto3.proto
index 884beae..8c2f2c9 100644
--- a/csharp/protos/unittest_proto3.proto
+++ b/csharp/protos/unittest_proto3.proto
@@ -130,7 +130,7 @@
}
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
NestedTestAllTypes child = 1;
TestAllTypes payload = 2;
diff --git a/csharp/protos/unittest_selfreferential_options.proto b/csharp/protos/unittest_selfreferential_options.proto
new file mode 100644
index 0000000..22f16cf
--- /dev/null
+++ b/csharp/protos/unittest_selfreferential_options.proto
@@ -0,0 +1,64 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+syntax = "proto2";
+
+package protobuf_unittest_selfreferential_options;
+option csharp_namespace = "UnitTest.Issues.TestProtos.SelfreferentialOptions";
+
+import "google/protobuf/descriptor.proto";
+
+message FooOptions {
+ // Custom field option used in definition of the extension message.
+ optional int32 int_opt = 1 [(foo_options) = {
+ int_opt: 1
+ [foo_int_opt]: 2
+ [foo_foo_opt]: {
+ int_opt: 3
+ }
+ }];
+
+ // Custom field option used in definition of the custom option's message.
+ optional int32 foo = 2 [(foo_options) = {foo: 1234}];
+
+ extensions 1000 to max;
+}
+
+extend google.protobuf.FieldOptions {
+ // Custom field option used on the definition of that field option.
+ optional int32 bar_options = 1000 [(bar_options) = 1234];
+
+ optional FooOptions foo_options = 1001;
+}
+
+extend FooOptions {
+ optional int32 foo_int_opt = 1000;
+ optional FooOptions foo_foo_opt = 1001;
+}
diff --git a/csharp/src/AddressBook/Addressbook.cs b/csharp/src/AddressBook/Addressbook.cs
index cbd9772..3b1da4d 100644
--- a/csharp/src/AddressBook/Addressbook.cs
+++ b/csharp/src/AddressBook/Addressbook.cs
@@ -49,7 +49,7 @@
/// <summary>
/// [START messages]
/// </summary>
- public sealed partial class Person : pb::IMessage<Person> {
+ public sealed partial class Person : pb::IMessage<Person>, pb::IBufferMessage {
private static readonly pb::MessageParser<Person> _parser = new pb::MessageParser<Person>(() => new Person());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -256,11 +256,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -275,7 +280,7 @@
break;
}
case 34: {
- phones_.AddEntriesFrom(input, _repeated_phones_codec);
+ phones_.AddEntriesFrom(ref input, _repeated_phones_codec);
break;
}
case 42: {
@@ -299,7 +304,7 @@
[pbr::OriginalName("WORK")] Work = 2,
}
- public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber> {
+ public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber>, pb::IBufferMessage {
private static readonly pb::MessageParser<PhoneNumber> _parser = new pb::MessageParser<PhoneNumber>(() => new PhoneNumber());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -436,11 +441,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Number = input.ReadString();
@@ -464,7 +474,7 @@
/// <summary>
/// Our address book file is just one of these.
/// </summary>
- public sealed partial class AddressBook : pb::IMessage<AddressBook> {
+ public sealed partial class AddressBook : pb::IMessage<AddressBook>, pb::IBufferMessage {
private static readonly pb::MessageParser<AddressBook> _parser = new pb::MessageParser<AddressBook>(() => new AddressBook());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -569,14 +579,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- people_.AddEntriesFrom(input, _repeated_people_codec);
+ people_.AddEntriesFrom(ref input, _repeated_people_codec);
break;
}
}
diff --git a/csharp/src/Google.Protobuf.Benchmarks/SerializationConfig.cs b/csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs
similarity index 88%
rename from csharp/src/Google.Protobuf.Benchmarks/SerializationConfig.cs
rename to csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs
index 679f16c..c075419 100644
--- a/csharp/src/Google.Protobuf.Benchmarks/SerializationConfig.cs
+++ b/csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs
@@ -43,20 +43,20 @@
/// <summary>
/// The configuration for a single serialization test, loaded from a dataset.
/// </summary>
- public class SerializationConfig
+ public class BenchmarkDatasetConfig
{
private static readonly Dictionary<string, MessageParser> parsersByMessageName =
- typeof(SerializationBenchmark).Assembly.GetTypes()
+ typeof(GoogleMessageBenchmark).Assembly.GetTypes()
.Where(t => typeof(IMessage).IsAssignableFrom(t))
.ToDictionary(
t => ((MessageDescriptor) t.GetProperty("Descriptor", BindingFlags.Static | BindingFlags.Public).GetValue(null)).FullName,
t => ((MessageParser) t.GetProperty("Parser", BindingFlags.Static | BindingFlags.Public).GetValue(null)));
public MessageParser Parser { get; }
- public IEnumerable<ByteString> Payloads { get; }
+ public List<byte[]> Payloads { get; }
public string Name { get; }
- public SerializationConfig(string resource)
+ public BenchmarkDatasetConfig(string resource, string shortName = null)
{
var data = LoadData(resource);
var dataset = BenchmarkDataset.Parser.ParseFrom(data);
@@ -66,13 +66,13 @@
throw new ArgumentException($"No parser for message {dataset.MessageName} in this assembly");
}
Parser = parser;
- Payloads = dataset.Payload;
- Name = dataset.Name;
+ Payloads = new List<byte[]>(dataset.Payload.Select(p => p.ToByteArray()));
+ Name = shortName ?? dataset.Name;
}
private static byte[] LoadData(string resource)
{
- using (var stream = typeof(SerializationBenchmark).Assembly.GetManifestResourceStream($"Google.Protobuf.Benchmarks.{resource}"))
+ using (var stream = typeof(GoogleMessageBenchmark).Assembly.GetManifestResourceStream($"Google.Protobuf.Benchmarks.{resource}"))
{
if (stream == null)
{
diff --git a/csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs b/csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs
index 9e8c330..291a585 100644
--- a/csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs
+++ b/csharp/src/Google.Protobuf.Benchmarks/BenchmarkMessage1Proto3.cs
@@ -64,7 +64,7 @@
}
#region Messages
- public sealed partial class GoogleMessage1 : pb::IMessage<GoogleMessage1> {
+ public sealed partial class GoogleMessage1 : pb::IMessage<GoogleMessage1>, pb::IBufferMessage {
private static readonly pb::MessageParser<GoogleMessage1> _parser = new pb::MessageParser<GoogleMessage1>(() => new GoogleMessage1());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1132,11 +1132,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Field1 = input.ReadString();
@@ -1156,7 +1161,7 @@
}
case 42:
case 41: {
- field5_.AddEntriesFrom(input, _repeated_field5_codec);
+ field5_.AddEntriesFrom(ref input, _repeated_field5_codec);
break;
}
case 48: {
@@ -1312,7 +1317,7 @@
}
- public sealed partial class GoogleMessage1SubMessage : pb::IMessage<GoogleMessage1SubMessage> {
+ public sealed partial class GoogleMessage1SubMessage : pb::IMessage<GoogleMessage1SubMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<GoogleMessage1SubMessage> _parser = new pb::MessageParser<GoogleMessage1SubMessage>(() => new GoogleMessage1SubMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1881,11 +1886,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Field1 = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs b/csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs
index 01dfcd7..456edbf 100644
--- a/csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs
+++ b/csharp/src/Google.Protobuf.Benchmarks/Benchmarks.cs
@@ -38,7 +38,7 @@
}
#region Messages
- public sealed partial class BenchmarkDataset : pb::IMessage<BenchmarkDataset> {
+ public sealed partial class BenchmarkDataset : pb::IMessage<BenchmarkDataset>, pb::IBufferMessage {
private static readonly pb::MessageParser<BenchmarkDataset> _parser = new pb::MessageParser<BenchmarkDataset>(() => new BenchmarkDataset());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -219,11 +219,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -234,7 +239,7 @@
break;
}
case 26: {
- payload_.AddEntriesFrom(input, _repeated_payload_codec);
+ payload_.AddEntriesFrom(ref input, _repeated_payload_codec);
break;
}
}
diff --git a/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj b/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj
index ecc064e..7432168 100644
--- a/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj
+++ b/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj
@@ -3,6 +3,9 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
+ <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
+ <SignAssembly>true</SignAssembly>
+ <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<IsPackable>False</IsPackable>
</PropertyGroup>
diff --git a/csharp/src/Google.Protobuf.Benchmarks/SerializationBenchmark.cs b/csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs
similarity index 74%
rename from csharp/src/Google.Protobuf.Benchmarks/SerializationBenchmark.cs
rename to csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs
index d8c2ec1..132967e 100644
--- a/csharp/src/Google.Protobuf.Benchmarks/SerializationBenchmark.cs
+++ b/csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs
@@ -38,23 +38,27 @@
namespace Google.Protobuf.Benchmarks
{
/// <summary>
- /// Benchmark for serializing (to a MemoryStream) and deserializing (from a ByteString).
+ /// Benchmark for serializing and deserializing of standard datasets that are also
+ /// measured by benchmarks in other languages.
/// Over time we may wish to test the various different approaches to serialization and deserialization separately.
+ /// See https://github.com/protocolbuffers/protobuf/blob/master/benchmarks/README.md
+ /// See https://github.com/protocolbuffers/protobuf/blob/master/docs/performance.md
/// </summary>
[MemoryDiagnoser]
- public class SerializationBenchmark
+ public class GoogleMessageBenchmark
{
/// <summary>
- /// All the configurations to be tested. Add more datasets to the array as they're available.
+ /// All the datasets to be tested. Add more datasets to the array as they're available.
/// (When C# supports proto2, this will increase significantly.)
/// </summary>
- public static SerializationConfig[] Configurations => new[]
+ public static BenchmarkDatasetConfig[] DatasetConfigurations => new[]
{
- new SerializationConfig("dataset.google_message1_proto3.pb")
+ // short name is specified to make results table more readable
+ new BenchmarkDatasetConfig("dataset.google_message1_proto3.pb", "goog_msg1_proto3")
};
- [ParamsSource(nameof(Configurations))]
- public SerializationConfig Configuration { get; set; }
+ [ParamsSource(nameof(DatasetConfigurations))]
+ public BenchmarkDatasetConfig Dataset { get; set; }
private MessageParser parser;
/// <summary>
@@ -67,8 +71,8 @@
[GlobalSetup]
public void GlobalSetup()
{
- parser = Configuration.Parser;
- subTests = Configuration.Payloads.Select(p => new SubTest(p, parser.ParseFrom(p))).ToList();
+ parser = Dataset.Parser;
+ subTests = Dataset.Payloads.Select(p => new SubTest(p, parser.ParseFrom(p))).ToList();
}
[Benchmark]
@@ -78,7 +82,7 @@
public void ToByteArray() => subTests.ForEach(item => item.ToByteArray());
[Benchmark]
- public void ParseFromByteString() => subTests.ForEach(item => item.ParseFromByteString(parser));
+ public void ParseFromByteArray() => subTests.ForEach(item => item.ParseFromByteArray(parser));
[Benchmark]
public void ParseFromStream() => subTests.ForEach(item => item.ParseFromStream(parser));
@@ -87,13 +91,13 @@
{
private readonly Stream destinationStream;
private readonly Stream sourceStream;
- private readonly ByteString data;
+ private readonly byte[] data;
private readonly IMessage message;
- public SubTest(ByteString data, IMessage message)
+ public SubTest(byte[] data, IMessage message)
{
destinationStream = new MemoryStream(data.Length);
- sourceStream = new MemoryStream(data.ToByteArray());
+ sourceStream = new MemoryStream(data);
this.data = data;
this.message = message;
}
@@ -108,7 +112,7 @@
public void ToByteArray() => message.ToByteArray();
- public void ParseFromByteString(MessageParser parser) => parser.ParseFrom(data);
+ public void ParseFromByteArray(MessageParser parser) => parser.ParseFrom(data);
public void ParseFromStream(MessageParser parser)
{
diff --git a/csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs b/csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs
new file mode 100644
index 0000000..30f3e9e
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs
@@ -0,0 +1,219 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2019 Google Inc. All rights reserved.
+// https://github.com/protocolbuffers/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using BenchmarkDotNet.Attributes;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Buffers;
+using Google.Protobuf.WellKnownTypes;
+
+namespace Google.Protobuf.Benchmarks
+{
+ /// <summary>
+ /// Benchmark that tests parsing performance for various messages.
+ /// </summary>
+ [MemoryDiagnoser]
+ public class ParseMessagesBenchmark
+ {
+ const int MaxMessages = 100;
+
+ SubTest manyWrapperFieldsTest = new SubTest(CreateManyWrapperFieldsMessage(), ManyWrapperFieldsMessage.Parser, () => new ManyWrapperFieldsMessage(), MaxMessages);
+ SubTest manyPrimitiveFieldsTest = new SubTest(CreateManyPrimitiveFieldsMessage(), ManyPrimitiveFieldsMessage.Parser, () => new ManyPrimitiveFieldsMessage(), MaxMessages);
+ SubTest emptyMessageTest = new SubTest(new Empty(), Empty.Parser, () => new Empty(), MaxMessages);
+
+ public IEnumerable<int> MessageCountValues => new[] { 10, 100 };
+
+ [GlobalSetup]
+ public void GlobalSetup()
+ {
+ }
+
+ [Benchmark]
+ public IMessage ManyWrapperFieldsMessage_ParseFromByteArray()
+ {
+ return manyWrapperFieldsTest.ParseFromByteArray();
+ }
+
+ [Benchmark]
+ public IMessage ManyWrapperFieldsMessage_ParseFromReadOnlySequence()
+ {
+ return manyWrapperFieldsTest.ParseFromReadOnlySequence();
+ }
+
+ [Benchmark]
+ public IMessage ManyPrimitiveFieldsMessage_ParseFromByteArray()
+ {
+ return manyPrimitiveFieldsTest.ParseFromByteArray();
+ }
+
+ [Benchmark]
+ public IMessage ManyPrimitiveFieldsMessage_ParseFromReadOnlySequence()
+ {
+ return manyPrimitiveFieldsTest.ParseFromReadOnlySequence();
+ }
+
+ [Benchmark]
+ public IMessage EmptyMessage_ParseFromByteArray()
+ {
+ return emptyMessageTest.ParseFromByteArray();
+ }
+
+ [Benchmark]
+ public IMessage EmptyMessage_ParseFromReadOnlySequence()
+ {
+ return emptyMessageTest.ParseFromReadOnlySequence();
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(MessageCountValues))]
+ public void ManyWrapperFieldsMessage_ParseDelimitedMessagesFromByteArray(int messageCount)
+ {
+ manyWrapperFieldsTest.ParseDelimitedMessagesFromByteArray(messageCount);
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(MessageCountValues))]
+ public void ManyWrapperFieldsMessage_ParseDelimitedMessagesFromReadOnlySequence(int messageCount)
+ {
+ manyWrapperFieldsTest.ParseDelimitedMessagesFromReadOnlySequence(messageCount);
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(MessageCountValues))]
+ public void ManyPrimitiveFieldsMessage_ParseDelimitedMessagesFromByteArray(int messageCount)
+ {
+ manyPrimitiveFieldsTest.ParseDelimitedMessagesFromByteArray(messageCount);
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(MessageCountValues))]
+ public void ManyPrimitiveFieldsMessage_ParseDelimitedMessagesFromReadOnlySequence(int messageCount)
+ {
+ manyPrimitiveFieldsTest.ParseDelimitedMessagesFromReadOnlySequence(messageCount);
+ }
+
+ private static ManyWrapperFieldsMessage CreateManyWrapperFieldsMessage()
+ {
+ // Example data match data of an internal benchmarks
+ return new ManyWrapperFieldsMessage()
+ {
+ Int64Field19 = 123,
+ Int64Field37 = 1000032,
+ Int64Field26 = 3453524500,
+ DoubleField79 = 1.2,
+ DoubleField25 = 234,
+ DoubleField9 = 123.3,
+ DoubleField28 = 23,
+ DoubleField7 = 234,
+ DoubleField50 = 2.45
+ };
+ }
+
+ private static ManyPrimitiveFieldsMessage CreateManyPrimitiveFieldsMessage()
+ {
+ // Example data match data of an internal benchmarks
+ return new ManyPrimitiveFieldsMessage()
+ {
+ Int64Field19 = 123,
+ Int64Field37 = 1000032,
+ Int64Field26 = 3453524500,
+ DoubleField79 = 1.2,
+ DoubleField25 = 234,
+ DoubleField9 = 123.3,
+ DoubleField28 = 23,
+ DoubleField7 = 234,
+ DoubleField50 = 2.45
+ };
+ }
+
+ private class SubTest
+ {
+ private readonly IMessage message;
+ private readonly MessageParser parser;
+ private readonly Func<IMessage> factory;
+ private readonly byte[] data;
+ private readonly byte[] multipleMessagesData;
+
+ private ReadOnlySequence<byte> dataSequence;
+ private ReadOnlySequence<byte> multipleMessagesDataSequence;
+
+ public SubTest(IMessage message, MessageParser parser, Func<IMessage> factory, int maxMessageCount)
+ {
+ this.message = message;
+ this.parser = parser;
+ this.factory = factory;
+ this.data = message.ToByteArray();
+ this.multipleMessagesData = CreateBufferWithMultipleMessages(message, maxMessageCount);
+ this.dataSequence = new ReadOnlySequence<byte>(this.data);
+ this.multipleMessagesDataSequence = new ReadOnlySequence<byte>(this.multipleMessagesData);
+ }
+
+ public IMessage ParseFromByteArray() => parser.ParseFrom(data);
+
+ public IMessage ParseFromReadOnlySequence() => parser.ParseFrom(dataSequence);
+
+ public void ParseDelimitedMessagesFromByteArray(int messageCount)
+ {
+ var input = new CodedInputStream(multipleMessagesData);
+ for (int i = 0; i < messageCount; i++)
+ {
+ var msg = factory();
+ input.ReadMessage(msg);
+ }
+ }
+
+ public void ParseDelimitedMessagesFromReadOnlySequence(int messageCount)
+ {
+ ParseContext.Initialize(multipleMessagesDataSequence, out ParseContext ctx);
+ for (int i = 0; i < messageCount; i++)
+ {
+ var msg = factory();
+ ctx.ReadMessage(msg);
+ }
+ }
+
+ private static byte[] CreateBufferWithMultipleMessages(IMessage msg, int msgCount)
+ {
+ var ms = new MemoryStream();
+ var cos = new CodedOutputStream(ms);
+ for (int i = 0; i < msgCount; i++)
+ {
+ cos.WriteMessage(msg);
+ }
+ cos.Flush();
+ return ms.ToArray();
+ }
+ }
+ }
+}
diff --git a/csharp/src/Google.Protobuf.Benchmarks/ParseRawPrimitivesBenchmark.cs b/csharp/src/Google.Protobuf.Benchmarks/ParseRawPrimitivesBenchmark.cs
new file mode 100644
index 0000000..863e74d
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Benchmarks/ParseRawPrimitivesBenchmark.cs
@@ -0,0 +1,461 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2019 Google Inc. All rights reserved.
+// https://github.com/protocolbuffers/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using BenchmarkDotNet.Attributes;
+using System;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.Buffers;
+
+namespace Google.Protobuf.Benchmarks
+{
+ /// <summary>
+ /// Benchmarks throughput when parsing raw primitives.
+ /// </summary>
+ [MemoryDiagnoser]
+ public class ParseRawPrimitivesBenchmark
+ {
+ // key is the encodedSize of varint values
+ Dictionary<int, byte[]> varintInputBuffers;
+
+ byte[] doubleInputBuffer;
+ byte[] floatInputBuffer;
+ byte[] fixedIntInputBuffer;
+
+ // key is the encodedSize of string values
+ Dictionary<int, byte[]> stringInputBuffers;
+
+ Random random = new Random(417384220); // random but deterministic seed
+
+ public IEnumerable<int> StringEncodedSizes => new[] { 1, 4, 10, 105, 10080 };
+
+ [GlobalSetup]
+ public void GlobalSetup()
+ {
+ // add some extra values that we won't read just to make sure we are far enough from the end of the buffer
+ // which allows the parser fastpath to always kick in.
+ const int paddingValueCount = 100;
+
+ varintInputBuffers = new Dictionary<int, byte[]>();
+ for (int encodedSize = 1; encodedSize <= 10; encodedSize++)
+ {
+ byte[] buffer = CreateBufferWithRandomVarints(random, BytesToParse / encodedSize, encodedSize, paddingValueCount);
+ varintInputBuffers.Add(encodedSize, buffer);
+ }
+
+ doubleInputBuffer = CreateBufferWithRandomDoubles(random, BytesToParse / sizeof(double), paddingValueCount);
+ floatInputBuffer = CreateBufferWithRandomFloats(random, BytesToParse / sizeof(float), paddingValueCount);
+ fixedIntInputBuffer = CreateBufferWithRandomData(random, BytesToParse / sizeof(long), sizeof(long), paddingValueCount);
+
+ stringInputBuffers = new Dictionary<int, byte[]>();
+ foreach(var encodedSize in StringEncodedSizes)
+ {
+ byte[] buffer = CreateBufferWithStrings(BytesToParse / encodedSize, encodedSize, encodedSize < 10 ? 10 : 1 );
+ stringInputBuffers.Add(encodedSize, buffer);
+ }
+ }
+
+ // Total number of bytes that each benchmark will parse.
+ // Measuring the time taken to parse buffer of given size makes it easier to compare parsing speed for different
+ // types and makes it easy to calculate the througput (in MB/s)
+ // 10800 bytes is chosen because it is divisible by all possible encoded sizes for all primitive types {1..10}
+ [Params(10080)]
+ public int BytesToParse { get; set; }
+
+ [Benchmark]
+ [Arguments(1)]
+ [Arguments(2)]
+ [Arguments(3)]
+ [Arguments(4)]
+ [Arguments(5)]
+ public int ParseRawVarint32_CodedInputStream(int encodedSize)
+ {
+ CodedInputStream cis = new CodedInputStream(varintInputBuffers[encodedSize]);
+ int sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadInt32();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ [Arguments(1)]
+ [Arguments(2)]
+ [Arguments(3)]
+ [Arguments(4)]
+ [Arguments(5)]
+ public int ParseRawVarint32_ParseContext(int encodedSize)
+ {
+ InitializeParseContext(varintInputBuffers[encodedSize], out ParseContext ctx);
+ int sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadInt32();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ [Arguments(1)]
+ [Arguments(2)]
+ [Arguments(3)]
+ [Arguments(4)]
+ [Arguments(5)]
+ [Arguments(6)]
+ [Arguments(7)]
+ [Arguments(8)]
+ [Arguments(9)]
+ [Arguments(10)]
+ public long ParseRawVarint64_CodedInputStream(int encodedSize)
+ {
+ CodedInputStream cis = new CodedInputStream(varintInputBuffers[encodedSize]);
+ long sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadInt64();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ [Arguments(1)]
+ [Arguments(2)]
+ [Arguments(3)]
+ [Arguments(4)]
+ [Arguments(5)]
+ [Arguments(6)]
+ [Arguments(7)]
+ [Arguments(8)]
+ [Arguments(9)]
+ [Arguments(10)]
+ public long ParseRawVarint64_ParseContext(int encodedSize)
+ {
+ InitializeParseContext(varintInputBuffers[encodedSize], out ParseContext ctx);
+ long sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadInt64();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public uint ParseFixed32_CodedInputStream()
+ {
+ const int encodedSize = sizeof(uint);
+ CodedInputStream cis = new CodedInputStream(fixedIntInputBuffer);
+ uint sum = 0;
+ for (uint i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadFixed32();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public uint ParseFixed32_ParseContext()
+ {
+ const int encodedSize = sizeof(uint);
+ InitializeParseContext(fixedIntInputBuffer, out ParseContext ctx);
+ uint sum = 0;
+ for (uint i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadFixed32();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public ulong ParseFixed64_CodedInputStream()
+ {
+ const int encodedSize = sizeof(ulong);
+ CodedInputStream cis = new CodedInputStream(fixedIntInputBuffer);
+ ulong sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadFixed64();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public ulong ParseFixed64_ParseContext()
+ {
+ const int encodedSize = sizeof(ulong);
+ InitializeParseContext(fixedIntInputBuffer, out ParseContext ctx);
+ ulong sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadFixed64();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public float ParseRawFloat_CodedInputStream()
+ {
+ const int encodedSize = sizeof(float);
+ CodedInputStream cis = new CodedInputStream(floatInputBuffer);
+ float sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadFloat();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public float ParseRawFloat_ParseContext()
+ {
+ const int encodedSize = sizeof(float);
+ InitializeParseContext(floatInputBuffer, out ParseContext ctx);
+ float sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadFloat();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public double ParseRawDouble_CodedInputStream()
+ {
+ const int encodedSize = sizeof(double);
+ CodedInputStream cis = new CodedInputStream(doubleInputBuffer);
+ double sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadDouble();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ public double ParseRawDouble_ParseContext()
+ {
+ const int encodedSize = sizeof(double);
+ InitializeParseContext(doubleInputBuffer, out ParseContext ctx);
+ double sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadDouble();
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(StringEncodedSizes))]
+ public int ParseString_CodedInputStream(int encodedSize)
+ {
+ CodedInputStream cis = new CodedInputStream(stringInputBuffers[encodedSize]);
+ int sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadString().Length;
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(StringEncodedSizes))]
+ public int ParseString_ParseContext(int encodedSize)
+ {
+ InitializeParseContext(stringInputBuffers[encodedSize], out ParseContext ctx);
+ int sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadString().Length;
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(StringEncodedSizes))]
+ public int ParseBytes_CodedInputStream(int encodedSize)
+ {
+ CodedInputStream cis = new CodedInputStream(stringInputBuffers[encodedSize]);
+ int sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += cis.ReadBytes().Length;
+ }
+ return sum;
+ }
+
+ [Benchmark]
+ [ArgumentsSource(nameof(StringEncodedSizes))]
+ public int ParseBytes_ParseContext(int encodedSize)
+ {
+ InitializeParseContext(stringInputBuffers[encodedSize], out ParseContext ctx);
+ int sum = 0;
+ for (int i = 0; i < BytesToParse / encodedSize; i++)
+ {
+ sum += ctx.ReadBytes().Length;
+ }
+ return sum;
+ }
+
+ private static void InitializeParseContext(byte[] buffer, out ParseContext ctx)
+ {
+ ParseContext.Initialize(new ReadOnlySequence<byte>(buffer), out ctx);
+ }
+
+ private static byte[] CreateBufferWithRandomVarints(Random random, int valueCount, int encodedSize, int paddingValueCount)
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream cos = new CodedOutputStream(ms);
+ for (int i = 0; i < valueCount + paddingValueCount; i++)
+ {
+ cos.WriteUInt64(RandomUnsignedVarint(random, encodedSize));
+ }
+ cos.Flush();
+ var buffer = ms.ToArray();
+
+ if (buffer.Length != encodedSize * (valueCount + paddingValueCount))
+ {
+ throw new InvalidOperationException($"Unexpected output buffer length {buffer.Length}");
+ }
+ return buffer;
+ }
+
+ private static byte[] CreateBufferWithRandomFloats(Random random, int valueCount, int paddingValueCount)
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream cos = new CodedOutputStream(ms);
+ for (int i = 0; i < valueCount + paddingValueCount; i++)
+ {
+ cos.WriteFloat((float)random.NextDouble());
+ }
+ cos.Flush();
+ var buffer = ms.ToArray();
+ return buffer;
+ }
+
+ private static byte[] CreateBufferWithRandomDoubles(Random random, int valueCount, int paddingValueCount)
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream cos = new CodedOutputStream(ms);
+ for (int i = 0; i < valueCount + paddingValueCount; i++)
+ {
+ cos.WriteDouble(random.NextDouble());
+ }
+ cos.Flush();
+ var buffer = ms.ToArray();
+ return buffer;
+ }
+
+ private static byte[] CreateBufferWithRandomData(Random random, int valueCount, int encodedSize, int paddingValueCount)
+ {
+ int bufferSize = (valueCount + paddingValueCount) * encodedSize;
+ byte[] buffer = new byte[bufferSize];
+ random.NextBytes(buffer);
+ return buffer;
+ }
+
+ /// <summary>
+ /// Generate a random value that will take exactly "encodedSize" bytes when varint-encoded.
+ /// </summary>
+ private static ulong RandomUnsignedVarint(Random random, int encodedSize)
+ {
+ Span<byte> randomBytesBuffer = stackalloc byte[8];
+
+ if (encodedSize < 1 || encodedSize > 10)
+ {
+ throw new ArgumentException("Illegal encodedSize value requested", nameof(encodedSize));
+ }
+ const int bitsPerByte = 7;
+
+ ulong result = 0;
+ while (true)
+ {
+ random.NextBytes(randomBytesBuffer);
+ ulong randomValue = BinaryPrimitives.ReadUInt64LittleEndian(randomBytesBuffer);
+
+ // only use the number of random bits we need
+ ulong bitmask = encodedSize < 10 ? ((1UL << (encodedSize * bitsPerByte)) - 1) : ulong.MaxValue;
+ result = randomValue & bitmask;
+
+ if (encodedSize == 10)
+ {
+ // for 10-byte values the highest bit always needs to be set (7*9=63)
+ result |= ulong.MaxValue;
+ break;
+ }
+
+ // some random values won't require the full "encodedSize" bytes, check that at least
+ // one of the top 7 bits is set. Retrying is fine since it only happens rarely
+ if (encodedSize == 1 || (result & (0x7FUL << ((encodedSize - 1) * bitsPerByte))) != 0)
+ {
+ break;
+ }
+ }
+ return result;
+ }
+
+ private static byte[] CreateBufferWithStrings(int valueCount, int encodedSize, int paddingValueCount)
+ {
+ var str = CreateStringWithEncodedSize(encodedSize);
+
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream cos = new CodedOutputStream(ms);
+ for (int i = 0; i < valueCount + paddingValueCount; i++)
+ {
+ cos.WriteString(str);
+ }
+ cos.Flush();
+ var buffer = ms.ToArray();
+
+ if (buffer.Length != encodedSize * (valueCount + paddingValueCount))
+ {
+ throw new InvalidOperationException($"Unexpected output buffer length {buffer.Length}");
+ }
+ return buffer;
+ }
+
+ private static string CreateStringWithEncodedSize(int encodedSize)
+ {
+ var str = new string('a', encodedSize);
+ while (CodedOutputStream.ComputeStringSize(str) > encodedSize)
+ {
+ str = str.Substring(1);
+ }
+
+ if (CodedOutputStream.ComputeStringSize(str) != encodedSize)
+ {
+ throw new InvalidOperationException($"Generated string with wrong encodedSize");
+ }
+ return str;
+ }
+ }
+}
diff --git a/csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmark.cs b/csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmark.cs
deleted file mode 100644
index ae17c18..0000000
--- a/csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmark.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2019 Google Inc. All rights reserved.
-// https://github.com/protocolbuffers/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using BenchmarkDotNet.Attributes;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-
-namespace Google.Protobuf.Benchmarks
-{
- /// <summary>
- /// Benchmark that tests serialization/deserialization of wrapper fields.
- /// </summary>
- [MemoryDiagnoser]
- public class WrapperBenchmark
- {
- byte[] manyWrapperFieldsData;
- byte[] manyPrimitiveFieldsData;
-
- [GlobalSetup]
- public void GlobalSetup()
- {
- manyWrapperFieldsData = CreateManyWrapperFieldsMessage().ToByteArray();
- manyPrimitiveFieldsData = CreateManyPrimitiveFieldsMessage().ToByteArray();
- }
-
- [Benchmark]
- public ManyWrapperFieldsMessage ParseWrapperFields()
- {
- return ManyWrapperFieldsMessage.Parser.ParseFrom(manyWrapperFieldsData);
- }
-
- [Benchmark]
- public ManyPrimitiveFieldsMessage ParsePrimitiveFields()
- {
- return ManyPrimitiveFieldsMessage.Parser.ParseFrom(manyPrimitiveFieldsData);
- }
-
- private static ManyWrapperFieldsMessage CreateManyWrapperFieldsMessage()
- {
- // Example data match data of an internal benchmarks
- return new ManyWrapperFieldsMessage()
- {
- Int64Field19 = 123,
- Int64Field37 = 1000032,
- Int64Field26 = 3453524500,
- DoubleField79 = 1.2,
- DoubleField25 = 234,
- DoubleField9 = 123.3,
- DoubleField28 = 23,
- DoubleField7 = 234,
- DoubleField50 = 2.45
- };
- }
-
- private static ManyPrimitiveFieldsMessage CreateManyPrimitiveFieldsMessage()
- {
- // Example data match data of an internal benchmarks
- return new ManyPrimitiveFieldsMessage()
- {
- Int64Field19 = 123,
- Int64Field37 = 1000032,
- Int64Field26 = 3453524500,
- DoubleField79 = 1.2,
- DoubleField25 = 234,
- DoubleField9 = 123.3,
- DoubleField28 = 23,
- DoubleField7 = 234,
- DoubleField50 = 2.45
- };
- }
- }
-}
diff --git a/csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmarkMessages.cs b/csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmarkMessages.cs
index 0cc86e2..76e95d6 100644
--- a/csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmarkMessages.cs
+++ b/csharp/src/Google.Protobuf.Benchmarks/WrapperBenchmarkMessages.cs
@@ -237,7 +237,7 @@
/// a message that has a large number of wrapper fields
/// obfuscated version of an internal message
/// </summary>
- public sealed partial class ManyWrapperFieldsMessage : pb::IMessage<ManyWrapperFieldsMessage> {
+ public sealed partial class ManyWrapperFieldsMessage : pb::IMessage<ManyWrapperFieldsMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<ManyWrapperFieldsMessage> _parser = new pb::MessageParser<ManyWrapperFieldsMessage>(() => new ManyWrapperFieldsMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3303,434 +3303,439 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- double? value = _single_doubleField1_codec.Read(input);
+ double? value = _single_doubleField1_codec.Read(ref input);
if (doubleField1_ == null || value != 0D) {
DoubleField1 = value;
}
break;
}
case 18: {
- long? value = _single_int64Field2_codec.Read(input);
+ long? value = _single_int64Field2_codec.Read(ref input);
if (int64Field2_ == null || value != 0L) {
Int64Field2 = value;
}
break;
}
case 26: {
- long? value = _single_int64Field3_codec.Read(input);
+ long? value = _single_int64Field3_codec.Read(ref input);
if (int64Field3_ == null || value != 0L) {
Int64Field3 = value;
}
break;
}
case 34: {
- long? value = _single_int64Field4_codec.Read(input);
+ long? value = _single_int64Field4_codec.Read(ref input);
if (int64Field4_ == null || value != 0L) {
Int64Field4 = value;
}
break;
}
case 58: {
- double? value = _single_doubleField7_codec.Read(input);
+ double? value = _single_doubleField7_codec.Read(ref input);
if (doubleField7_ == null || value != 0D) {
DoubleField7 = value;
}
break;
}
case 66: {
- double? value = _single_doubleField8_codec.Read(input);
+ double? value = _single_doubleField8_codec.Read(ref input);
if (doubleField8_ == null || value != 0D) {
DoubleField8 = value;
}
break;
}
case 74: {
- double? value = _single_doubleField9_codec.Read(input);
+ double? value = _single_doubleField9_codec.Read(ref input);
if (doubleField9_ == null || value != 0D) {
DoubleField9 = value;
}
break;
}
case 82: {
- double? value = _single_doubleField10_codec.Read(input);
+ double? value = _single_doubleField10_codec.Read(ref input);
if (doubleField10_ == null || value != 0D) {
DoubleField10 = value;
}
break;
}
case 90: {
- double? value = _single_doubleField11_codec.Read(input);
+ double? value = _single_doubleField11_codec.Read(ref input);
if (doubleField11_ == null || value != 0D) {
DoubleField11 = value;
}
break;
}
case 114: {
- double? value = _single_doubleField14_codec.Read(input);
+ double? value = _single_doubleField14_codec.Read(ref input);
if (doubleField14_ == null || value != 0D) {
DoubleField14 = value;
}
break;
}
case 122: {
- double? value = _single_doubleField15_codec.Read(input);
+ double? value = _single_doubleField15_codec.Read(ref input);
if (doubleField15_ == null || value != 0D) {
DoubleField15 = value;
}
break;
}
case 154: {
- long? value = _single_int64Field19_codec.Read(input);
+ long? value = _single_int64Field19_codec.Read(ref input);
if (int64Field19_ == null || value != 0L) {
Int64Field19 = value;
}
break;
}
case 162: {
- double? value = _single_doubleField20_codec.Read(input);
+ double? value = _single_doubleField20_codec.Read(ref input);
if (doubleField20_ == null || value != 0D) {
DoubleField20 = value;
}
break;
}
case 170: {
- double? value = _single_doubleField21_codec.Read(input);
+ double? value = _single_doubleField21_codec.Read(ref input);
if (doubleField21_ == null || value != 0D) {
DoubleField21 = value;
}
break;
}
case 178: {
- double? value = _single_doubleField22_codec.Read(input);
+ double? value = _single_doubleField22_codec.Read(ref input);
if (doubleField22_ == null || value != 0D) {
DoubleField22 = value;
}
break;
}
case 202: {
- double? value = _single_doubleField25_codec.Read(input);
+ double? value = _single_doubleField25_codec.Read(ref input);
if (doubleField25_ == null || value != 0D) {
DoubleField25 = value;
}
break;
}
case 210: {
- long? value = _single_int64Field26_codec.Read(input);
+ long? value = _single_int64Field26_codec.Read(ref input);
if (int64Field26_ == null || value != 0L) {
Int64Field26 = value;
}
break;
}
case 226: {
- double? value = _single_doubleField28_codec.Read(input);
+ double? value = _single_doubleField28_codec.Read(ref input);
if (doubleField28_ == null || value != 0D) {
DoubleField28 = value;
}
break;
}
case 234: {
- double? value = _single_doubleField29_codec.Read(input);
+ double? value = _single_doubleField29_codec.Read(ref input);
if (doubleField29_ == null || value != 0D) {
DoubleField29 = value;
}
break;
}
case 242: {
- double? value = _single_doubleField30_codec.Read(input);
+ double? value = _single_doubleField30_codec.Read(ref input);
if (doubleField30_ == null || value != 0D) {
DoubleField30 = value;
}
break;
}
case 250: {
- double? value = _single_doubleField31_codec.Read(input);
+ double? value = _single_doubleField31_codec.Read(ref input);
if (doubleField31_ == null || value != 0D) {
DoubleField31 = value;
}
break;
}
case 258: {
- long? value = _single_int64Field32_codec.Read(input);
+ long? value = _single_int64Field32_codec.Read(ref input);
if (int64Field32_ == null || value != 0L) {
Int64Field32 = value;
}
break;
}
case 298: {
- long? value = _single_int64Field37_codec.Read(input);
+ long? value = _single_int64Field37_codec.Read(ref input);
if (int64Field37_ == null || value != 0L) {
Int64Field37 = value;
}
break;
}
case 306: {
- double? value = _single_doubleField38_codec.Read(input);
+ double? value = _single_doubleField38_codec.Read(ref input);
if (doubleField38_ == null || value != 0D) {
DoubleField38 = value;
}
break;
}
case 314: {
- long? value = _single_interactions_codec.Read(input);
+ long? value = _single_interactions_codec.Read(ref input);
if (interactions_ == null || value != 0L) {
Interactions = value;
}
break;
}
case 322: {
- double? value = _single_doubleField40_codec.Read(input);
+ double? value = _single_doubleField40_codec.Read(ref input);
if (doubleField40_ == null || value != 0D) {
DoubleField40 = value;
}
break;
}
case 330: {
- long? value = _single_int64Field41_codec.Read(input);
+ long? value = _single_int64Field41_codec.Read(ref input);
if (int64Field41_ == null || value != 0L) {
Int64Field41 = value;
}
break;
}
case 338: {
- double? value = _single_doubleField42_codec.Read(input);
+ double? value = _single_doubleField42_codec.Read(ref input);
if (doubleField42_ == null || value != 0D) {
DoubleField42 = value;
}
break;
}
case 346: {
- long? value = _single_int64Field43_codec.Read(input);
+ long? value = _single_int64Field43_codec.Read(ref input);
if (int64Field43_ == null || value != 0L) {
Int64Field43 = value;
}
break;
}
case 354: {
- long? value = _single_int64Field44_codec.Read(input);
+ long? value = _single_int64Field44_codec.Read(ref input);
if (int64Field44_ == null || value != 0L) {
Int64Field44 = value;
}
break;
}
case 362: {
- double? value = _single_doubleField45_codec.Read(input);
+ double? value = _single_doubleField45_codec.Read(ref input);
if (doubleField45_ == null || value != 0D) {
DoubleField45 = value;
}
break;
}
case 370: {
- double? value = _single_doubleField46_codec.Read(input);
+ double? value = _single_doubleField46_codec.Read(ref input);
if (doubleField46_ == null || value != 0D) {
DoubleField46 = value;
}
break;
}
case 378: {
- double? value = _single_doubleField47_codec.Read(input);
+ double? value = _single_doubleField47_codec.Read(ref input);
if (doubleField47_ == null || value != 0D) {
DoubleField47 = value;
}
break;
}
case 386: {
- double? value = _single_doubleField48_codec.Read(input);
+ double? value = _single_doubleField48_codec.Read(ref input);
if (doubleField48_ == null || value != 0D) {
DoubleField48 = value;
}
break;
}
case 394: {
- double? value = _single_doubleField49_codec.Read(input);
+ double? value = _single_doubleField49_codec.Read(ref input);
if (doubleField49_ == null || value != 0D) {
DoubleField49 = value;
}
break;
}
case 402: {
- double? value = _single_doubleField50_codec.Read(input);
+ double? value = _single_doubleField50_codec.Read(ref input);
if (doubleField50_ == null || value != 0D) {
DoubleField50 = value;
}
break;
}
case 410: {
- double? value = _single_doubleField51_codec.Read(input);
+ double? value = _single_doubleField51_codec.Read(ref input);
if (doubleField51_ == null || value != 0D) {
DoubleField51 = value;
}
break;
}
case 418: {
- double? value = _single_doubleField52_codec.Read(input);
+ double? value = _single_doubleField52_codec.Read(ref input);
if (doubleField52_ == null || value != 0D) {
DoubleField52 = value;
}
break;
}
case 426: {
- double? value = _single_doubleField53_codec.Read(input);
+ double? value = _single_doubleField53_codec.Read(ref input);
if (doubleField53_ == null || value != 0D) {
DoubleField53 = value;
}
break;
}
case 434: {
- double? value = _single_doubleField54_codec.Read(input);
+ double? value = _single_doubleField54_codec.Read(ref input);
if (doubleField54_ == null || value != 0D) {
DoubleField54 = value;
}
break;
}
case 442: {
- double? value = _single_doubleField55_codec.Read(input);
+ double? value = _single_doubleField55_codec.Read(ref input);
if (doubleField55_ == null || value != 0D) {
DoubleField55 = value;
}
break;
}
case 450: {
- double? value = _single_doubleField56_codec.Read(input);
+ double? value = _single_doubleField56_codec.Read(ref input);
if (doubleField56_ == null || value != 0D) {
DoubleField56 = value;
}
break;
}
case 458: {
- double? value = _single_doubleField57_codec.Read(input);
+ double? value = _single_doubleField57_codec.Read(ref input);
if (doubleField57_ == null || value != 0D) {
DoubleField57 = value;
}
break;
}
case 466: {
- double? value = _single_doubleField58_codec.Read(input);
+ double? value = _single_doubleField58_codec.Read(ref input);
if (doubleField58_ == null || value != 0D) {
DoubleField58 = value;
}
break;
}
case 474: {
- long? value = _single_int64Field59_codec.Read(input);
+ long? value = _single_int64Field59_codec.Read(ref input);
if (int64Field59_ == null || value != 0L) {
Int64Field59 = value;
}
break;
}
case 482: {
- long? value = _single_int64Field60_codec.Read(input);
+ long? value = _single_int64Field60_codec.Read(ref input);
if (int64Field60_ == null || value != 0L) {
Int64Field60 = value;
}
break;
}
case 498: {
- double? value = _single_doubleField62_codec.Read(input);
+ double? value = _single_doubleField62_codec.Read(ref input);
if (doubleField62_ == null || value != 0D) {
DoubleField62 = value;
}
break;
}
case 522: {
- double? value = _single_doubleField65_codec.Read(input);
+ double? value = _single_doubleField65_codec.Read(ref input);
if (doubleField65_ == null || value != 0D) {
DoubleField65 = value;
}
break;
}
case 530: {
- double? value = _single_doubleField66_codec.Read(input);
+ double? value = _single_doubleField66_codec.Read(ref input);
if (doubleField66_ == null || value != 0D) {
DoubleField66 = value;
}
break;
}
case 538: {
- double? value = _single_doubleField67_codec.Read(input);
+ double? value = _single_doubleField67_codec.Read(ref input);
if (doubleField67_ == null || value != 0D) {
DoubleField67 = value;
}
break;
}
case 546: {
- double? value = _single_doubleField68_codec.Read(input);
+ double? value = _single_doubleField68_codec.Read(ref input);
if (doubleField68_ == null || value != 0D) {
DoubleField68 = value;
}
break;
}
case 554: {
- double? value = _single_doubleField69_codec.Read(input);
+ double? value = _single_doubleField69_codec.Read(ref input);
if (doubleField69_ == null || value != 0D) {
DoubleField69 = value;
}
break;
}
case 562: {
- double? value = _single_doubleField70_codec.Read(input);
+ double? value = _single_doubleField70_codec.Read(ref input);
if (doubleField70_ == null || value != 0D) {
DoubleField70 = value;
}
break;
}
case 570: {
- double? value = _single_doubleField71_codec.Read(input);
+ double? value = _single_doubleField71_codec.Read(ref input);
if (doubleField71_ == null || value != 0D) {
DoubleField71 = value;
}
break;
}
case 578: {
- double? value = _single_doubleField72_codec.Read(input);
+ double? value = _single_doubleField72_codec.Read(ref input);
if (doubleField72_ == null || value != 0D) {
DoubleField72 = value;
}
break;
}
case 586: {
- string value = _single_stringField73_codec.Read(input);
+ string value = _single_stringField73_codec.Read(ref input);
if (stringField73_ == null || value != "") {
StringField73 = value;
}
break;
}
case 594: {
- string value = _single_stringField74_codec.Read(input);
+ string value = _single_stringField74_codec.Read(ref input);
if (stringField74_ == null || value != "") {
StringField74 = value;
}
break;
}
case 602: {
- double? value = _single_doubleField75_codec.Read(input);
+ double? value = _single_doubleField75_codec.Read(ref input);
if (doubleField75_ == null || value != 0D) {
DoubleField75 = value;
}
break;
}
case 618: {
- double? value = _single_doubleField77_codec.Read(input);
+ double? value = _single_doubleField77_codec.Read(ref input);
if (doubleField77_ == null || value != 0D) {
DoubleField77 = value;
}
break;
}
case 626: {
- double? value = _single_doubleField78_codec.Read(input);
+ double? value = _single_doubleField78_codec.Read(ref input);
if (doubleField78_ == null || value != 0D) {
DoubleField78 = value;
}
break;
}
case 634: {
- double? value = _single_doubleField79_codec.Read(input);
+ double? value = _single_doubleField79_codec.Read(ref input);
if (doubleField79_ == null || value != 0D) {
DoubleField79 = value;
}
@@ -3745,7 +3750,7 @@
break;
}
case 658: {
- long? value = _single_int64Field82_codec.Read(input);
+ long? value = _single_int64Field82_codec.Read(ref input);
if (int64Field82_ == null || value != 0L) {
Int64Field82 = value;
}
@@ -3756,112 +3761,112 @@
break;
}
case 674: {
- double? value = _single_doubleField84_codec.Read(input);
+ double? value = _single_doubleField84_codec.Read(ref input);
if (doubleField84_ == null || value != 0D) {
DoubleField84 = value;
}
break;
}
case 682: {
- long? value = _single_int64Field85_codec.Read(input);
+ long? value = _single_int64Field85_codec.Read(ref input);
if (int64Field85_ == null || value != 0L) {
Int64Field85 = value;
}
break;
}
case 690: {
- long? value = _single_int64Field86_codec.Read(input);
+ long? value = _single_int64Field86_codec.Read(ref input);
if (int64Field86_ == null || value != 0L) {
Int64Field86 = value;
}
break;
}
case 698: {
- long? value = _single_int64Field87_codec.Read(input);
+ long? value = _single_int64Field87_codec.Read(ref input);
if (int64Field87_ == null || value != 0L) {
Int64Field87 = value;
}
break;
}
case 706: {
- double? value = _single_doubleField88_codec.Read(input);
+ double? value = _single_doubleField88_codec.Read(ref input);
if (doubleField88_ == null || value != 0D) {
DoubleField88 = value;
}
break;
}
case 714: {
- double? value = _single_doubleField89_codec.Read(input);
+ double? value = _single_doubleField89_codec.Read(ref input);
if (doubleField89_ == null || value != 0D) {
DoubleField89 = value;
}
break;
}
case 722: {
- double? value = _single_doubleField90_codec.Read(input);
+ double? value = _single_doubleField90_codec.Read(ref input);
if (doubleField90_ == null || value != 0D) {
DoubleField90 = value;
}
break;
}
case 730: {
- double? value = _single_doubleField91_codec.Read(input);
+ double? value = _single_doubleField91_codec.Read(ref input);
if (doubleField91_ == null || value != 0D) {
DoubleField91 = value;
}
break;
}
case 738: {
- double? value = _single_doubleField92_codec.Read(input);
+ double? value = _single_doubleField92_codec.Read(ref input);
if (doubleField92_ == null || value != 0D) {
DoubleField92 = value;
}
break;
}
case 746: {
- double? value = _single_doubleField93_codec.Read(input);
+ double? value = _single_doubleField93_codec.Read(ref input);
if (doubleField93_ == null || value != 0D) {
DoubleField93 = value;
}
break;
}
case 754: {
- double? value = _single_doubleField94_codec.Read(input);
+ double? value = _single_doubleField94_codec.Read(ref input);
if (doubleField94_ == null || value != 0D) {
DoubleField94 = value;
}
break;
}
case 762: {
- double? value = _single_doubleField95_codec.Read(input);
+ double? value = _single_doubleField95_codec.Read(ref input);
if (doubleField95_ == null || value != 0D) {
DoubleField95 = value;
}
break;
}
case 770: {
- double? value = _single_doubleField96_codec.Read(input);
+ double? value = _single_doubleField96_codec.Read(ref input);
if (doubleField96_ == null || value != 0D) {
DoubleField96 = value;
}
break;
}
case 778: {
- double? value = _single_doubleField97_codec.Read(input);
+ double? value = _single_doubleField97_codec.Read(ref input);
if (doubleField97_ == null || value != 0D) {
DoubleField97 = value;
}
break;
}
case 786: {
- double? value = _single_doubleField98_codec.Read(input);
+ double? value = _single_doubleField98_codec.Read(ref input);
if (doubleField98_ == null || value != 0D) {
DoubleField98 = value;
}
break;
}
case 794: {
- double? value = _single_doubleField99_codec.Read(input);
+ double? value = _single_doubleField99_codec.Read(ref input);
if (doubleField99_ == null || value != 0D) {
DoubleField99 = value;
}
@@ -3869,207 +3874,207 @@
}
case 802:
case 800: {
- repeatedIntField100_.AddEntriesFrom(input, _repeated_repeatedIntField100_codec);
+ repeatedIntField100_.AddEntriesFrom(ref input, _repeated_repeatedIntField100_codec);
break;
}
case 810: {
- double? value = _single_doubleField101_codec.Read(input);
+ double? value = _single_doubleField101_codec.Read(ref input);
if (doubleField101_ == null || value != 0D) {
DoubleField101 = value;
}
break;
}
case 818: {
- double? value = _single_doubleField102_codec.Read(input);
+ double? value = _single_doubleField102_codec.Read(ref input);
if (doubleField102_ == null || value != 0D) {
DoubleField102 = value;
}
break;
}
case 826: {
- double? value = _single_doubleField103_codec.Read(input);
+ double? value = _single_doubleField103_codec.Read(ref input);
if (doubleField103_ == null || value != 0D) {
DoubleField103 = value;
}
break;
}
case 834: {
- double? value = _single_doubleField104_codec.Read(input);
+ double? value = _single_doubleField104_codec.Read(ref input);
if (doubleField104_ == null || value != 0D) {
DoubleField104 = value;
}
break;
}
case 842: {
- double? value = _single_doubleField105_codec.Read(input);
+ double? value = _single_doubleField105_codec.Read(ref input);
if (doubleField105_ == null || value != 0D) {
DoubleField105 = value;
}
break;
}
case 850: {
- double? value = _single_doubleField106_codec.Read(input);
+ double? value = _single_doubleField106_codec.Read(ref input);
if (doubleField106_ == null || value != 0D) {
DoubleField106 = value;
}
break;
}
case 858: {
- long? value = _single_int64Field107_codec.Read(input);
+ long? value = _single_int64Field107_codec.Read(ref input);
if (int64Field107_ == null || value != 0L) {
Int64Field107 = value;
}
break;
}
case 866: {
- double? value = _single_doubleField108_codec.Read(input);
+ double? value = _single_doubleField108_codec.Read(ref input);
if (doubleField108_ == null || value != 0D) {
DoubleField108 = value;
}
break;
}
case 874: {
- double? value = _single_doubleField109_codec.Read(input);
+ double? value = _single_doubleField109_codec.Read(ref input);
if (doubleField109_ == null || value != 0D) {
DoubleField109 = value;
}
break;
}
case 882: {
- long? value = _single_int64Field110_codec.Read(input);
+ long? value = _single_int64Field110_codec.Read(ref input);
if (int64Field110_ == null || value != 0L) {
Int64Field110 = value;
}
break;
}
case 890: {
- double? value = _single_doubleField111_codec.Read(input);
+ double? value = _single_doubleField111_codec.Read(ref input);
if (doubleField111_ == null || value != 0D) {
DoubleField111 = value;
}
break;
}
case 898: {
- long? value = _single_int64Field112_codec.Read(input);
+ long? value = _single_int64Field112_codec.Read(ref input);
if (int64Field112_ == null || value != 0L) {
Int64Field112 = value;
}
break;
}
case 906: {
- double? value = _single_doubleField113_codec.Read(input);
+ double? value = _single_doubleField113_codec.Read(ref input);
if (doubleField113_ == null || value != 0D) {
DoubleField113 = value;
}
break;
}
case 914: {
- long? value = _single_int64Field114_codec.Read(input);
+ long? value = _single_int64Field114_codec.Read(ref input);
if (int64Field114_ == null || value != 0L) {
Int64Field114 = value;
}
break;
}
case 922: {
- long? value = _single_int64Field115_codec.Read(input);
+ long? value = _single_int64Field115_codec.Read(ref input);
if (int64Field115_ == null || value != 0L) {
Int64Field115 = value;
}
break;
}
case 930: {
- double? value = _single_doubleField116_codec.Read(input);
+ double? value = _single_doubleField116_codec.Read(ref input);
if (doubleField116_ == null || value != 0D) {
DoubleField116 = value;
}
break;
}
case 938: {
- long? value = _single_int64Field117_codec.Read(input);
+ long? value = _single_int64Field117_codec.Read(ref input);
if (int64Field117_ == null || value != 0L) {
Int64Field117 = value;
}
break;
}
case 946: {
- double? value = _single_doubleField118_codec.Read(input);
+ double? value = _single_doubleField118_codec.Read(ref input);
if (doubleField118_ == null || value != 0D) {
DoubleField118 = value;
}
break;
}
case 954: {
- double? value = _single_doubleField119_codec.Read(input);
+ double? value = _single_doubleField119_codec.Read(ref input);
if (doubleField119_ == null || value != 0D) {
DoubleField119 = value;
}
break;
}
case 962: {
- double? value = _single_doubleField120_codec.Read(input);
+ double? value = _single_doubleField120_codec.Read(ref input);
if (doubleField120_ == null || value != 0D) {
DoubleField120 = value;
}
break;
}
case 970: {
- double? value = _single_doubleField121_codec.Read(input);
+ double? value = _single_doubleField121_codec.Read(ref input);
if (doubleField121_ == null || value != 0D) {
DoubleField121 = value;
}
break;
}
case 978: {
- double? value = _single_doubleField122_codec.Read(input);
+ double? value = _single_doubleField122_codec.Read(ref input);
if (doubleField122_ == null || value != 0D) {
DoubleField122 = value;
}
break;
}
case 986: {
- double? value = _single_doubleField123_codec.Read(input);
+ double? value = _single_doubleField123_codec.Read(ref input);
if (doubleField123_ == null || value != 0D) {
DoubleField123 = value;
}
break;
}
case 994: {
- double? value = _single_doubleField124_codec.Read(input);
+ double? value = _single_doubleField124_codec.Read(ref input);
if (doubleField124_ == null || value != 0D) {
DoubleField124 = value;
}
break;
}
case 1002: {
- long? value = _single_int64Field125_codec.Read(input);
+ long? value = _single_int64Field125_codec.Read(ref input);
if (int64Field125_ == null || value != 0L) {
Int64Field125 = value;
}
break;
}
case 1010: {
- long? value = _single_int64Field126_codec.Read(input);
+ long? value = _single_int64Field126_codec.Read(ref input);
if (int64Field126_ == null || value != 0L) {
Int64Field126 = value;
}
break;
}
case 1018: {
- long? value = _single_int64Field127_codec.Read(input);
+ long? value = _single_int64Field127_codec.Read(ref input);
if (int64Field127_ == null || value != 0L) {
Int64Field127 = value;
}
break;
}
case 1026: {
- double? value = _single_doubleField128_codec.Read(input);
+ double? value = _single_doubleField128_codec.Read(ref input);
if (doubleField128_ == null || value != 0D) {
DoubleField128 = value;
}
break;
}
case 1034: {
- double? value = _single_doubleField129_codec.Read(input);
+ double? value = _single_doubleField129_codec.Read(ref input);
if (doubleField129_ == null || value != 0D) {
DoubleField129 = value;
}
@@ -4085,7 +4090,7 @@
/// same as ManyWrapperFieldsMessages, but with primitive fields
/// for comparison.
/// </summary>
- public sealed partial class ManyPrimitiveFieldsMessage : pb::IMessage<ManyPrimitiveFieldsMessage> {
+ public sealed partial class ManyPrimitiveFieldsMessage : pb::IMessage<ManyPrimitiveFieldsMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<ManyPrimitiveFieldsMessage> _parser = new pb::MessageParser<ManyPrimitiveFieldsMessage>(() => new ManyPrimitiveFieldsMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6830,11 +6835,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 9: {
DoubleField1 = input.ReadDouble();
@@ -7162,7 +7172,7 @@
}
case 802:
case 800: {
- repeatedIntField100_.AddEntriesFrom(input, _repeated_repeatedIntField100_codec);
+ repeatedIntField100_.AddEntriesFrom(ref input, _repeated_repeatedIntField100_codec);
break;
}
case 809: {
diff --git a/csharp/src/Google.Protobuf.Conformance/Conformance.cs b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
index 65ba9b1..f9bda13 100644
--- a/csharp/src/Google.Protobuf.Conformance/Conformance.cs
+++ b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
@@ -107,7 +107,7 @@
/// This will be known by message_type == "conformance.FailureSet", a conformance
/// test should return a serialized FailureSet in protobuf_payload.
/// </summary>
- public sealed partial class FailureSet : pb::IMessage<FailureSet> {
+ public sealed partial class FailureSet : pb::IMessage<FailureSet>, pb::IBufferMessage {
private static readonly pb::MessageParser<FailureSet> _parser = new pb::MessageParser<FailureSet>(() => new FailureSet());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -212,14 +212,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- failure_.AddEntriesFrom(input, _repeated_failure_codec);
+ failure_.AddEntriesFrom(ref input, _repeated_failure_codec);
break;
}
}
@@ -235,7 +240,7 @@
/// 2. parse the protobuf or JSON payload in "payload" (which may fail)
/// 3. if the parse succeeded, serialize the message in the requested format.
/// </summary>
- public sealed partial class ConformanceRequest : pb::IMessage<ConformanceRequest> {
+ public sealed partial class ConformanceRequest : pb::IMessage<ConformanceRequest>, pb::IBufferMessage {
private static readonly pb::MessageParser<ConformanceRequest> _parser = new pb::MessageParser<ConformanceRequest>(() => new ConformanceRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -370,7 +375,7 @@
private global::Conformance.TestCategory testCategory_ = global::Conformance.TestCategory.UnspecifiedTest;
/// <summary>
/// Each test is given a specific test category. Some category may need
- /// spedific support in testee programs. Refer to the defintion of TestCategory
+ /// spedific support in testee programs. Refer to the definition of TestCategory
/// for more information.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -603,11 +608,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
ProtobufPayload = input.ReadBytes();
@@ -657,7 +667,7 @@
/// <summary>
/// Represents a single test case's output.
/// </summary>
- public sealed partial class ConformanceResponse : pb::IMessage<ConformanceResponse> {
+ public sealed partial class ConformanceResponse : pb::IMessage<ConformanceResponse>, pb::IBufferMessage {
private static readonly pb::MessageParser<ConformanceResponse> _parser = new pb::MessageParser<ConformanceResponse>(() => new ConformanceResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1025,11 +1035,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
ParseError = input.ReadString();
@@ -1072,7 +1087,7 @@
/// <summary>
/// Encoding options for jspb format.
/// </summary>
- public sealed partial class JspbEncodingConfig : pb::IMessage<JspbEncodingConfig> {
+ public sealed partial class JspbEncodingConfig : pb::IMessage<JspbEncodingConfig>, pb::IBufferMessage {
private static readonly pb::MessageParser<JspbEncodingConfig> _parser = new pb::MessageParser<JspbEncodingConfig>(() => new JspbEncodingConfig());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1110,7 +1125,7 @@
public const int UseJspbArrayAnyFormatFieldNumber = 1;
private bool useJspbArrayAnyFormat_;
/// <summary>
- /// Encode the value field of Any as jspb array if ture, otherwise binary.
+ /// Encode the value field of Any as jspb array if true, otherwise binary.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool UseJspbArrayAnyFormat {
@@ -1188,11 +1203,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
UseJspbArrayAnyFormat = input.ReadBool();
diff --git a/csharp/src/Google.Protobuf.Conformance/Program.cs b/csharp/src/Google.Protobuf.Conformance/Program.cs
index 728a3b9..d1093ab 100644
--- a/csharp/src/Google.Protobuf.Conformance/Program.cs
+++ b/csharp/src/Google.Protobuf.Conformance/Program.cs
@@ -143,7 +143,7 @@
case global::Conformance.WireFormat.Protobuf:
return new ConformanceResponse { ProtobufPayload = message.ToByteString() };
default:
- throw new Exception("Unsupported request output format: " + request.PayloadCase);
+ throw new Exception("Unsupported request output format: " + request.RequestedOutputFormat);
}
}
catch (InvalidOperationException e)
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/Google.Protobuf.Test.TestProtos.csproj b/csharp/src/Google.Protobuf.Test.TestProtos/Google.Protobuf.Test.TestProtos.csproj
index 5b70580..1af85e0 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/Google.Protobuf.Test.TestProtos.csproj
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/Google.Protobuf.Test.TestProtos.csproj
@@ -6,7 +6,7 @@
and without the internal visibility from the test project (all of which have caused issues in the past).
-->
<PropertyGroup>
- <TargetFrameworks>net45;netstandard1.0;netstandard2.0</TargetFrameworks>
+ <TargetFrameworks>net45;netstandard1.1;netstandard2.0</TargetFrameworks>
<LangVersion>3.0</LangVersion>
<AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs b/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs
index 197b197..8d20605 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs
@@ -176,7 +176,7 @@
/// <summary>
/// Tests maps.
/// </summary>
- public sealed partial class TestMap : pb::IMessage<TestMap> {
+ public sealed partial class TestMap : pb::IMessage<TestMap>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMap> _parser = new pb::MessageParser<TestMap>(() => new TestMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -537,78 +537,83 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec);
+ mapInt32Int32_.AddEntriesFrom(ref input, _map_mapInt32Int32_codec);
break;
}
case 18: {
- mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec);
+ mapInt64Int64_.AddEntriesFrom(ref input, _map_mapInt64Int64_codec);
break;
}
case 26: {
- mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec);
+ mapUint32Uint32_.AddEntriesFrom(ref input, _map_mapUint32Uint32_codec);
break;
}
case 34: {
- mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec);
+ mapUint64Uint64_.AddEntriesFrom(ref input, _map_mapUint64Uint64_codec);
break;
}
case 42: {
- mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec);
+ mapSint32Sint32_.AddEntriesFrom(ref input, _map_mapSint32Sint32_codec);
break;
}
case 50: {
- mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec);
+ mapSint64Sint64_.AddEntriesFrom(ref input, _map_mapSint64Sint64_codec);
break;
}
case 58: {
- mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec);
+ mapFixed32Fixed32_.AddEntriesFrom(ref input, _map_mapFixed32Fixed32_codec);
break;
}
case 66: {
- mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec);
+ mapFixed64Fixed64_.AddEntriesFrom(ref input, _map_mapFixed64Fixed64_codec);
break;
}
case 74: {
- mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec);
+ mapSfixed32Sfixed32_.AddEntriesFrom(ref input, _map_mapSfixed32Sfixed32_codec);
break;
}
case 82: {
- mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec);
+ mapSfixed64Sfixed64_.AddEntriesFrom(ref input, _map_mapSfixed64Sfixed64_codec);
break;
}
case 90: {
- mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec);
+ mapInt32Float_.AddEntriesFrom(ref input, _map_mapInt32Float_codec);
break;
}
case 98: {
- mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec);
+ mapInt32Double_.AddEntriesFrom(ref input, _map_mapInt32Double_codec);
break;
}
case 106: {
- mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec);
+ mapBoolBool_.AddEntriesFrom(ref input, _map_mapBoolBool_codec);
break;
}
case 114: {
- mapStringString_.AddEntriesFrom(input, _map_mapStringString_codec);
+ mapStringString_.AddEntriesFrom(ref input, _map_mapStringString_codec);
break;
}
case 122: {
- mapInt32Bytes_.AddEntriesFrom(input, _map_mapInt32Bytes_codec);
+ mapInt32Bytes_.AddEntriesFrom(ref input, _map_mapInt32Bytes_codec);
break;
}
case 130: {
- mapInt32Enum_.AddEntriesFrom(input, _map_mapInt32Enum_codec);
+ mapInt32Enum_.AddEntriesFrom(ref input, _map_mapInt32Enum_codec);
break;
}
case 138: {
- mapInt32ForeignMessage_.AddEntriesFrom(input, _map_mapInt32ForeignMessage_codec);
+ mapInt32ForeignMessage_.AddEntriesFrom(ref input, _map_mapInt32ForeignMessage_codec);
break;
}
}
@@ -617,7 +622,7 @@
}
- public sealed partial class TestMapSubmessage : pb::IMessage<TestMapSubmessage> {
+ public sealed partial class TestMapSubmessage : pb::IMessage<TestMapSubmessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMapSubmessage> _parser = new pb::MessageParser<TestMapSubmessage>(() => new TestMapSubmessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -733,11 +738,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (testMap_ == null) {
@@ -752,7 +762,7 @@
}
- public sealed partial class TestMessageMap : pb::IMessage<TestMessageMap> {
+ public sealed partial class TestMessageMap : pb::IMessage<TestMessageMap>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMessageMap> _parser = new pb::MessageParser<TestMessageMap>(() => new TestMessageMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -857,14 +867,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- mapInt32Message_.AddEntriesFrom(input, _map_mapInt32Message_codec);
+ mapInt32Message_.AddEntriesFrom(ref input, _map_mapInt32Message_codec);
break;
}
}
@@ -876,7 +891,7 @@
/// <summary>
/// Two map fields share the same entry default instance.
/// </summary>
- public sealed partial class TestSameTypeMap : pb::IMessage<TestSameTypeMap> {
+ public sealed partial class TestSameTypeMap : pb::IMessage<TestSameTypeMap>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestSameTypeMap> _parser = new pb::MessageParser<TestSameTypeMap>(() => new TestSameTypeMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -997,18 +1012,23 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- map1_.AddEntriesFrom(input, _map_map1_codec);
+ map1_.AddEntriesFrom(ref input, _map_map1_codec);
break;
}
case 18: {
- map2_.AddEntriesFrom(input, _map_map2_codec);
+ map2_.AddEntriesFrom(ref input, _map_map2_codec);
break;
}
}
@@ -1017,7 +1037,7 @@
}
- public sealed partial class TestArenaMap : pb::IMessage<TestArenaMap> {
+ public sealed partial class TestArenaMap : pb::IMessage<TestArenaMap>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestArenaMap> _parser = new pb::MessageParser<TestArenaMap>(() => new TestArenaMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1346,70 +1366,75 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec);
+ mapInt32Int32_.AddEntriesFrom(ref input, _map_mapInt32Int32_codec);
break;
}
case 18: {
- mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec);
+ mapInt64Int64_.AddEntriesFrom(ref input, _map_mapInt64Int64_codec);
break;
}
case 26: {
- mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec);
+ mapUint32Uint32_.AddEntriesFrom(ref input, _map_mapUint32Uint32_codec);
break;
}
case 34: {
- mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec);
+ mapUint64Uint64_.AddEntriesFrom(ref input, _map_mapUint64Uint64_codec);
break;
}
case 42: {
- mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec);
+ mapSint32Sint32_.AddEntriesFrom(ref input, _map_mapSint32Sint32_codec);
break;
}
case 50: {
- mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec);
+ mapSint64Sint64_.AddEntriesFrom(ref input, _map_mapSint64Sint64_codec);
break;
}
case 58: {
- mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec);
+ mapFixed32Fixed32_.AddEntriesFrom(ref input, _map_mapFixed32Fixed32_codec);
break;
}
case 66: {
- mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec);
+ mapFixed64Fixed64_.AddEntriesFrom(ref input, _map_mapFixed64Fixed64_codec);
break;
}
case 74: {
- mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec);
+ mapSfixed32Sfixed32_.AddEntriesFrom(ref input, _map_mapSfixed32Sfixed32_codec);
break;
}
case 82: {
- mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec);
+ mapSfixed64Sfixed64_.AddEntriesFrom(ref input, _map_mapSfixed64Sfixed64_codec);
break;
}
case 90: {
- mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec);
+ mapInt32Float_.AddEntriesFrom(ref input, _map_mapInt32Float_codec);
break;
}
case 98: {
- mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec);
+ mapInt32Double_.AddEntriesFrom(ref input, _map_mapInt32Double_codec);
break;
}
case 106: {
- mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec);
+ mapBoolBool_.AddEntriesFrom(ref input, _map_mapBoolBool_codec);
break;
}
case 114: {
- mapInt32Enum_.AddEntriesFrom(input, _map_mapInt32Enum_codec);
+ mapInt32Enum_.AddEntriesFrom(ref input, _map_mapInt32Enum_codec);
break;
}
case 122: {
- mapInt32ForeignMessage_.AddEntriesFrom(input, _map_mapInt32ForeignMessage_codec);
+ mapInt32ForeignMessage_.AddEntriesFrom(ref input, _map_mapInt32ForeignMessage_codec);
break;
}
}
@@ -1422,7 +1447,7 @@
/// Previously, message containing enum called Type cannot be used as value of
/// map field.
/// </summary>
- public sealed partial class MessageContainingEnumCalledType : pb::IMessage<MessageContainingEnumCalledType> {
+ public sealed partial class MessageContainingEnumCalledType : pb::IMessage<MessageContainingEnumCalledType>, pb::IBufferMessage {
private static readonly pb::MessageParser<MessageContainingEnumCalledType> _parser = new pb::MessageParser<MessageContainingEnumCalledType>(() => new MessageContainingEnumCalledType());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1527,14 +1552,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- type_.AddEntriesFrom(input, _map_type_codec);
+ type_.AddEntriesFrom(ref input, _map_type_codec);
break;
}
}
@@ -1557,7 +1587,7 @@
/// <summary>
/// Previously, message cannot contain map field called "entry".
/// </summary>
- public sealed partial class MessageContainingMapCalledEntry : pb::IMessage<MessageContainingMapCalledEntry> {
+ public sealed partial class MessageContainingMapCalledEntry : pb::IMessage<MessageContainingMapCalledEntry>, pb::IBufferMessage {
private static readonly pb::MessageParser<MessageContainingMapCalledEntry> _parser = new pb::MessageParser<MessageContainingMapCalledEntry>(() => new MessageContainingMapCalledEntry());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1662,14 +1692,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- entry_.AddEntriesFrom(input, _map_entry_codec);
+ entry_.AddEntriesFrom(ref input, _map_entry_codec);
break;
}
}
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto2.cs b/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto2.cs
index 350fb7c..bef3645 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto2.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto2.cs
@@ -244,7 +244,7 @@
/// could trigger bugs that occur in any message type in this file. We verify
/// this stays true in a unit test.
/// </summary>
- public sealed partial class TestAllTypesProto2 : pb::IExtendableMessage<TestAllTypesProto2> {
+ public sealed partial class TestAllTypesProto2 : pb::IExtendableMessage<TestAllTypesProto2>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestAllTypesProto2> _parser = new pb::MessageParser<TestAllTypesProto2>(() => new TestAllTypesProto2());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestAllTypesProto2> _extensions;
@@ -290,13 +290,13 @@
optionalBool_ = other.optionalBool_;
optionalString_ = other.optionalString_;
optionalBytes_ = other.optionalBytes_;
- optionalNestedMessage_ = other.HasOptionalNestedMessage ? other.optionalNestedMessage_.Clone() : null;
- optionalForeignMessage_ = other.HasOptionalForeignMessage ? other.optionalForeignMessage_.Clone() : null;
+ optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null;
+ optionalForeignMessage_ = other.optionalForeignMessage_ != null ? other.optionalForeignMessage_.Clone() : null;
optionalNestedEnum_ = other.optionalNestedEnum_;
optionalForeignEnum_ = other.optionalForeignEnum_;
optionalStringPiece_ = other.optionalStringPiece_;
optionalCord_ = other.optionalCord_;
- recursiveMessage_ = other.HasRecursiveMessage ? other.recursiveMessage_.Clone() : null;
+ recursiveMessage_ = other.recursiveMessage_ != null ? other.recursiveMessage_.Clone() : null;
repeatedInt32_ = other.repeatedInt32_.Clone();
repeatedInt64_ = other.repeatedInt64_.Clone();
repeatedUint32_ = other.repeatedUint32_.Clone();
@@ -794,16 +794,6 @@
optionalNestedMessage_ = value;
}
}
- /// <summary>Gets whether the optional_nested_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalNestedMessage {
- get { return optionalNestedMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_nested_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalNestedMessage() {
- optionalNestedMessage_ = null;
- }
/// <summary>Field number for the "optional_foreign_message" field.</summary>
public const int OptionalForeignMessageFieldNumber = 19;
@@ -815,16 +805,6 @@
optionalForeignMessage_ = value;
}
}
- /// <summary>Gets whether the optional_foreign_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalForeignMessage {
- get { return optionalForeignMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_foreign_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalForeignMessage() {
- optionalForeignMessage_ = null;
- }
/// <summary>Field number for the "optional_nested_enum" field.</summary>
public const int OptionalNestedEnumFieldNumber = 21;
@@ -930,16 +910,6 @@
recursiveMessage_ = value;
}
}
- /// <summary>Gets whether the recursive_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasRecursiveMessage {
- get { return recursiveMessage_ != null; }
- }
- /// <summary>Clears the value of the recursive_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearRecursiveMessage() {
- recursiveMessage_ = null;
- }
/// <summary>Field number for the "repeated_int32" field.</summary>
public const int RepeatedInt32FieldNumber = 31;
@@ -1660,24 +1630,12 @@
public const int OneofNestedMessageFieldNumber = 112;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage OneofNestedMessage {
- get { return HasOneofNestedMessage ? (global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage) oneofField_ : null; }
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage ? (global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage) oneofField_ : null; }
set {
oneofField_ = value;
oneofFieldCase_ = value == null ? OneofFieldOneofCase.None : OneofFieldOneofCase.OneofNestedMessage;
}
}
- /// <summary>Gets whether the "oneof_nested_message" field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOneofNestedMessage {
- get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage; }
- }
- /// <summary> Clears the value of the oneof if it's currently set to "oneof_nested_message" </summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOneofNestedMessage() {
- if (HasOneofNestedMessage) {
- ClearOneofField();
- }
- }
/// <summary>Field number for the "oneof_string" field.</summary>
public const int OneofStringFieldNumber = 113;
@@ -1872,21 +1830,21 @@
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Fieldname1 {
- get { if ((_hasBits0 & 2097152) != 0) { return fieldname1_; } else { return Fieldname1DefaultValue; } }
+ get { if ((_hasBits0 & 32768) != 0) { return fieldname1_; } else { return Fieldname1DefaultValue; } }
set {
- _hasBits0 |= 2097152;
+ _hasBits0 |= 32768;
fieldname1_ = value;
}
}
/// <summary>Gets whether the "fieldname1" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldname1 {
- get { return (_hasBits0 & 2097152) != 0; }
+ get { return (_hasBits0 & 32768) != 0; }
}
/// <summary>Clears the value of the "fieldname1" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldname1() {
- _hasBits0 &= ~2097152;
+ _hasBits0 &= ~32768;
}
/// <summary>Field number for the "field_name2" field.</summary>
@@ -1896,21 +1854,21 @@
private int fieldName2_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName2 {
- get { if ((_hasBits0 & 4194304) != 0) { return fieldName2_; } else { return FieldName2DefaultValue; } }
+ get { if ((_hasBits0 & 65536) != 0) { return fieldName2_; } else { return FieldName2DefaultValue; } }
set {
- _hasBits0 |= 4194304;
+ _hasBits0 |= 65536;
fieldName2_ = value;
}
}
/// <summary>Gets whether the "field_name2" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName2 {
- get { return (_hasBits0 & 4194304) != 0; }
+ get { return (_hasBits0 & 65536) != 0; }
}
/// <summary>Clears the value of the "field_name2" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName2() {
- _hasBits0 &= ~4194304;
+ _hasBits0 &= ~65536;
}
/// <summary>Field number for the "_field_name3" field.</summary>
@@ -1920,21 +1878,21 @@
private int FieldName3_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName3 {
- get { if ((_hasBits0 & 8388608) != 0) { return FieldName3_; } else { return FieldName3DefaultValue; } }
+ get { if ((_hasBits0 & 131072) != 0) { return FieldName3_; } else { return FieldName3DefaultValue; } }
set {
- _hasBits0 |= 8388608;
+ _hasBits0 |= 131072;
FieldName3_ = value;
}
}
/// <summary>Gets whether the "_field_name3" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName3 {
- get { return (_hasBits0 & 8388608) != 0; }
+ get { return (_hasBits0 & 131072) != 0; }
}
/// <summary>Clears the value of the "_field_name3" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName3() {
- _hasBits0 &= ~8388608;
+ _hasBits0 &= ~131072;
}
/// <summary>Field number for the "field__name4_" field.</summary>
@@ -1944,21 +1902,21 @@
private int fieldName4_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName4 {
- get { if ((_hasBits0 & 16777216) != 0) { return fieldName4_; } else { return FieldName4DefaultValue; } }
+ get { if ((_hasBits0 & 262144) != 0) { return fieldName4_; } else { return FieldName4DefaultValue; } }
set {
- _hasBits0 |= 16777216;
+ _hasBits0 |= 262144;
fieldName4_ = value;
}
}
/// <summary>Gets whether the "field__name4_" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName4 {
- get { return (_hasBits0 & 16777216) != 0; }
+ get { return (_hasBits0 & 262144) != 0; }
}
/// <summary>Clears the value of the "field__name4_" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName4() {
- _hasBits0 &= ~16777216;
+ _hasBits0 &= ~262144;
}
/// <summary>Field number for the "field0name5" field.</summary>
@@ -1968,21 +1926,21 @@
private int field0Name5_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Field0Name5 {
- get { if ((_hasBits0 & 33554432) != 0) { return field0Name5_; } else { return Field0Name5DefaultValue; } }
+ get { if ((_hasBits0 & 524288) != 0) { return field0Name5_; } else { return Field0Name5DefaultValue; } }
set {
- _hasBits0 |= 33554432;
+ _hasBits0 |= 524288;
field0Name5_ = value;
}
}
/// <summary>Gets whether the "field0name5" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasField0Name5 {
- get { return (_hasBits0 & 33554432) != 0; }
+ get { return (_hasBits0 & 524288) != 0; }
}
/// <summary>Clears the value of the "field0name5" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearField0Name5() {
- _hasBits0 &= ~33554432;
+ _hasBits0 &= ~524288;
}
/// <summary>Field number for the "field_0_name6" field.</summary>
@@ -1992,21 +1950,21 @@
private int field0Name6_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Field0Name6 {
- get { if ((_hasBits0 & 67108864) != 0) { return field0Name6_; } else { return Field0Name6DefaultValue; } }
+ get { if ((_hasBits0 & 1048576) != 0) { return field0Name6_; } else { return Field0Name6DefaultValue; } }
set {
- _hasBits0 |= 67108864;
+ _hasBits0 |= 1048576;
field0Name6_ = value;
}
}
/// <summary>Gets whether the "field_0_name6" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasField0Name6 {
- get { return (_hasBits0 & 67108864) != 0; }
+ get { return (_hasBits0 & 1048576) != 0; }
}
/// <summary>Clears the value of the "field_0_name6" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearField0Name6() {
- _hasBits0 &= ~67108864;
+ _hasBits0 &= ~1048576;
}
/// <summary>Field number for the "fieldName7" field.</summary>
@@ -2016,21 +1974,21 @@
private int fieldName7_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName7 {
- get { if ((_hasBits0 & 134217728) != 0) { return fieldName7_; } else { return FieldName7DefaultValue; } }
+ get { if ((_hasBits0 & 2097152) != 0) { return fieldName7_; } else { return FieldName7DefaultValue; } }
set {
- _hasBits0 |= 134217728;
+ _hasBits0 |= 2097152;
fieldName7_ = value;
}
}
/// <summary>Gets whether the "fieldName7" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName7 {
- get { return (_hasBits0 & 134217728) != 0; }
+ get { return (_hasBits0 & 2097152) != 0; }
}
/// <summary>Clears the value of the "fieldName7" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName7() {
- _hasBits0 &= ~134217728;
+ _hasBits0 &= ~2097152;
}
/// <summary>Field number for the "FieldName8" field.</summary>
@@ -2040,21 +1998,21 @@
private int fieldName8_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName8 {
- get { if ((_hasBits0 & 268435456) != 0) { return fieldName8_; } else { return FieldName8DefaultValue; } }
+ get { if ((_hasBits0 & 4194304) != 0) { return fieldName8_; } else { return FieldName8DefaultValue; } }
set {
- _hasBits0 |= 268435456;
+ _hasBits0 |= 4194304;
fieldName8_ = value;
}
}
/// <summary>Gets whether the "FieldName8" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName8 {
- get { return (_hasBits0 & 268435456) != 0; }
+ get { return (_hasBits0 & 4194304) != 0; }
}
/// <summary>Clears the value of the "FieldName8" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName8() {
- _hasBits0 &= ~268435456;
+ _hasBits0 &= ~4194304;
}
/// <summary>Field number for the "field_Name9" field.</summary>
@@ -2064,21 +2022,21 @@
private int fieldName9_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName9 {
- get { if ((_hasBits0 & 536870912) != 0) { return fieldName9_; } else { return FieldName9DefaultValue; } }
+ get { if ((_hasBits0 & 8388608) != 0) { return fieldName9_; } else { return FieldName9DefaultValue; } }
set {
- _hasBits0 |= 536870912;
+ _hasBits0 |= 8388608;
fieldName9_ = value;
}
}
/// <summary>Gets whether the "field_Name9" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName9 {
- get { return (_hasBits0 & 536870912) != 0; }
+ get { return (_hasBits0 & 8388608) != 0; }
}
/// <summary>Clears the value of the "field_Name9" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName9() {
- _hasBits0 &= ~536870912;
+ _hasBits0 &= ~8388608;
}
/// <summary>Field number for the "Field_Name10" field.</summary>
@@ -2088,21 +2046,21 @@
private int fieldName10_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName10 {
- get { if ((_hasBits0 & 1073741824) != 0) { return fieldName10_; } else { return FieldName10DefaultValue; } }
+ get { if ((_hasBits0 & 16777216) != 0) { return fieldName10_; } else { return FieldName10DefaultValue; } }
set {
- _hasBits0 |= 1073741824;
+ _hasBits0 |= 16777216;
fieldName10_ = value;
}
}
/// <summary>Gets whether the "Field_Name10" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName10 {
- get { return (_hasBits0 & 1073741824) != 0; }
+ get { return (_hasBits0 & 16777216) != 0; }
}
/// <summary>Clears the value of the "Field_Name10" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName10() {
- _hasBits0 &= ~1073741824;
+ _hasBits0 &= ~16777216;
}
/// <summary>Field number for the "FIELD_NAME11" field.</summary>
@@ -2112,21 +2070,21 @@
private int fIELDNAME11_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FIELDNAME11 {
- get { if ((_hasBits0 & -2147483648) != 0) { return fIELDNAME11_; } else { return FIELDNAME11DefaultValue; } }
+ get { if ((_hasBits0 & 33554432) != 0) { return fIELDNAME11_; } else { return FIELDNAME11DefaultValue; } }
set {
- _hasBits0 |= -2147483648;
+ _hasBits0 |= 33554432;
fIELDNAME11_ = value;
}
}
/// <summary>Gets whether the "FIELD_NAME11" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFIELDNAME11 {
- get { return (_hasBits0 & -2147483648) != 0; }
+ get { return (_hasBits0 & 33554432) != 0; }
}
/// <summary>Clears the value of the "FIELD_NAME11" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFIELDNAME11() {
- _hasBits0 &= ~-2147483648;
+ _hasBits0 &= ~33554432;
}
/// <summary>Field number for the "FIELD_name12" field.</summary>
@@ -2136,21 +2094,21 @@
private int fIELDName12_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FIELDName12 {
- get { if ((_hasBits1 & 1) != 0) { return fIELDName12_; } else { return FIELDName12DefaultValue; } }
+ get { if ((_hasBits0 & 67108864) != 0) { return fIELDName12_; } else { return FIELDName12DefaultValue; } }
set {
- _hasBits1 |= 1;
+ _hasBits0 |= 67108864;
fIELDName12_ = value;
}
}
/// <summary>Gets whether the "FIELD_name12" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFIELDName12 {
- get { return (_hasBits1 & 1) != 0; }
+ get { return (_hasBits0 & 67108864) != 0; }
}
/// <summary>Clears the value of the "FIELD_name12" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFIELDName12() {
- _hasBits1 &= ~1;
+ _hasBits0 &= ~67108864;
}
/// <summary>Field number for the "__field_name13" field.</summary>
@@ -2160,21 +2118,21 @@
private int FieldName13_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName13 {
- get { if ((_hasBits1 & 2) != 0) { return FieldName13_; } else { return FieldName13DefaultValue; } }
+ get { if ((_hasBits0 & 134217728) != 0) { return FieldName13_; } else { return FieldName13DefaultValue; } }
set {
- _hasBits1 |= 2;
+ _hasBits0 |= 134217728;
FieldName13_ = value;
}
}
/// <summary>Gets whether the "__field_name13" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName13 {
- get { return (_hasBits1 & 2) != 0; }
+ get { return (_hasBits0 & 134217728) != 0; }
}
/// <summary>Clears the value of the "__field_name13" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName13() {
- _hasBits1 &= ~2;
+ _hasBits0 &= ~134217728;
}
/// <summary>Field number for the "__Field_name14" field.</summary>
@@ -2184,21 +2142,21 @@
private int FieldName14_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName14 {
- get { if ((_hasBits1 & 4) != 0) { return FieldName14_; } else { return FieldName14DefaultValue; } }
+ get { if ((_hasBits0 & 268435456) != 0) { return FieldName14_; } else { return FieldName14DefaultValue; } }
set {
- _hasBits1 |= 4;
+ _hasBits0 |= 268435456;
FieldName14_ = value;
}
}
/// <summary>Gets whether the "__Field_name14" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName14 {
- get { return (_hasBits1 & 4) != 0; }
+ get { return (_hasBits0 & 268435456) != 0; }
}
/// <summary>Clears the value of the "__Field_name14" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName14() {
- _hasBits1 &= ~4;
+ _hasBits0 &= ~268435456;
}
/// <summary>Field number for the "field__name15" field.</summary>
@@ -2208,21 +2166,21 @@
private int fieldName15_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName15 {
- get { if ((_hasBits1 & 8) != 0) { return fieldName15_; } else { return FieldName15DefaultValue; } }
+ get { if ((_hasBits0 & 536870912) != 0) { return fieldName15_; } else { return FieldName15DefaultValue; } }
set {
- _hasBits1 |= 8;
+ _hasBits0 |= 536870912;
fieldName15_ = value;
}
}
/// <summary>Gets whether the "field__name15" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName15 {
- get { return (_hasBits1 & 8) != 0; }
+ get { return (_hasBits0 & 536870912) != 0; }
}
/// <summary>Clears the value of the "field__name15" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName15() {
- _hasBits1 &= ~8;
+ _hasBits0 &= ~536870912;
}
/// <summary>Field number for the "field__Name16" field.</summary>
@@ -2232,21 +2190,21 @@
private int fieldName16_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName16 {
- get { if ((_hasBits1 & 16) != 0) { return fieldName16_; } else { return FieldName16DefaultValue; } }
+ get { if ((_hasBits0 & 1073741824) != 0) { return fieldName16_; } else { return FieldName16DefaultValue; } }
set {
- _hasBits1 |= 16;
+ _hasBits0 |= 1073741824;
fieldName16_ = value;
}
}
/// <summary>Gets whether the "field__Name16" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName16 {
- get { return (_hasBits1 & 16) != 0; }
+ get { return (_hasBits0 & 1073741824) != 0; }
}
/// <summary>Clears the value of the "field__Name16" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName16() {
- _hasBits1 &= ~16;
+ _hasBits0 &= ~1073741824;
}
/// <summary>Field number for the "field_name17__" field.</summary>
@@ -2256,21 +2214,21 @@
private int fieldName17_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName17 {
- get { if ((_hasBits1 & 32) != 0) { return fieldName17_; } else { return FieldName17DefaultValue; } }
+ get { if ((_hasBits0 & -2147483648) != 0) { return fieldName17_; } else { return FieldName17DefaultValue; } }
set {
- _hasBits1 |= 32;
+ _hasBits0 |= -2147483648;
fieldName17_ = value;
}
}
/// <summary>Gets whether the "field_name17__" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName17 {
- get { return (_hasBits1 & 32) != 0; }
+ get { return (_hasBits0 & -2147483648) != 0; }
}
/// <summary>Clears the value of the "field_name17__" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName17() {
- _hasBits1 &= ~32;
+ _hasBits0 &= ~-2147483648;
}
/// <summary>Field number for the "Field_name18__" field.</summary>
@@ -2280,21 +2238,21 @@
private int fieldName18_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FieldName18 {
- get { if ((_hasBits1 & 64) != 0) { return fieldName18_; } else { return FieldName18DefaultValue; } }
+ get { if ((_hasBits1 & 1) != 0) { return fieldName18_; } else { return FieldName18DefaultValue; } }
set {
- _hasBits1 |= 64;
+ _hasBits1 |= 1;
fieldName18_ = value;
}
}
/// <summary>Gets whether the "Field_name18__" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasFieldName18 {
- get { return (_hasBits1 & 64) != 0; }
+ get { return (_hasBits1 & 1) != 0; }
}
/// <summary>Clears the value of the "Field_name18__" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFieldName18() {
- _hasBits1 &= ~64;
+ _hasBits1 &= ~1;
}
private object oneofField_;
@@ -2479,13 +2437,13 @@
if (HasOptionalBool) hash ^= OptionalBool.GetHashCode();
if (HasOptionalString) hash ^= OptionalString.GetHashCode();
if (HasOptionalBytes) hash ^= OptionalBytes.GetHashCode();
- if (HasOptionalNestedMessage) hash ^= OptionalNestedMessage.GetHashCode();
- if (HasOptionalForeignMessage) hash ^= OptionalForeignMessage.GetHashCode();
+ if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode();
+ if (optionalForeignMessage_ != null) hash ^= OptionalForeignMessage.GetHashCode();
if (HasOptionalNestedEnum) hash ^= OptionalNestedEnum.GetHashCode();
if (HasOptionalForeignEnum) hash ^= OptionalForeignEnum.GetHashCode();
if (HasOptionalStringPiece) hash ^= OptionalStringPiece.GetHashCode();
if (HasOptionalCord) hash ^= OptionalCord.GetHashCode();
- if (HasRecursiveMessage) hash ^= RecursiveMessage.GetHashCode();
+ if (recursiveMessage_ != null) hash ^= RecursiveMessage.GetHashCode();
hash ^= repeatedInt32_.GetHashCode();
hash ^= repeatedInt64_.GetHashCode();
hash ^= repeatedUint32_.GetHashCode();
@@ -2555,7 +2513,7 @@
hash ^= MapStringNestedEnum.GetHashCode();
hash ^= MapStringForeignEnum.GetHashCode();
if (HasOneofUint32) hash ^= OneofUint32.GetHashCode();
- if (HasOneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode();
if (HasOneofString) hash ^= OneofString.GetHashCode();
if (HasOneofBytes) hash ^= OneofBytes.GetHashCode();
if (HasOneofBool) hash ^= OneofBool.GetHashCode();
@@ -2659,11 +2617,11 @@
output.WriteRawTag(122);
output.WriteBytes(OptionalBytes);
}
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
output.WriteRawTag(146, 1);
output.WriteMessage(OptionalNestedMessage);
}
- if (HasOptionalForeignMessage) {
+ if (optionalForeignMessage_ != null) {
output.WriteRawTag(154, 1);
output.WriteMessage(OptionalForeignMessage);
}
@@ -2683,7 +2641,7 @@
output.WriteRawTag(202, 1);
output.WriteString(OptionalCord);
}
- if (HasRecursiveMessage) {
+ if (recursiveMessage_ != null) {
output.WriteRawTag(218, 1);
output.WriteMessage(RecursiveMessage);
}
@@ -2759,7 +2717,7 @@
output.WriteRawTag(248, 6);
output.WriteUInt32(OneofUint32);
}
- if (HasOneofNestedMessage) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) {
output.WriteRawTag(130, 7);
output.WriteMessage(OneofNestedMessage);
}
@@ -2924,10 +2882,10 @@
if (HasOptionalBytes) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(OptionalBytes);
}
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage);
}
- if (HasOptionalForeignMessage) {
+ if (optionalForeignMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalForeignMessage);
}
if (HasOptionalNestedEnum) {
@@ -2942,7 +2900,7 @@
if (HasOptionalCord) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalCord);
}
- if (HasRecursiveMessage) {
+ if (recursiveMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(RecursiveMessage);
}
size += repeatedInt32_.CalculateSize(_repeated_repeatedInt32_codec);
@@ -3016,7 +2974,7 @@
if (HasOneofUint32) {
size += 2 + pb::CodedOutputStream.ComputeUInt32Size(OneofUint32);
}
- if (HasOneofNestedMessage) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OneofNestedMessage);
}
if (HasOneofString) {
@@ -3156,14 +3114,14 @@
if (other.HasOptionalBytes) {
OptionalBytes = other.OptionalBytes;
}
- if (other.HasOptionalNestedMessage) {
- if (!HasOptionalNestedMessage) {
+ if (other.optionalNestedMessage_ != null) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage();
}
OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage);
}
- if (other.HasOptionalForeignMessage) {
- if (!HasOptionalForeignMessage) {
+ if (other.optionalForeignMessage_ != null) {
+ if (optionalForeignMessage_ == null) {
OptionalForeignMessage = new global::ProtobufTestMessages.Proto2.ForeignMessageProto2();
}
OptionalForeignMessage.MergeFrom(other.OptionalForeignMessage);
@@ -3180,8 +3138,8 @@
if (other.HasOptionalCord) {
OptionalCord = other.OptionalCord;
}
- if (other.HasRecursiveMessage) {
- if (!HasRecursiveMessage) {
+ if (other.recursiveMessage_ != null) {
+ if (recursiveMessage_ == null) {
RecursiveMessage = new global::ProtobufTestMessages.Proto2.TestAllTypesProto2();
}
RecursiveMessage.MergeFrom(other.RecursiveMessage);
@@ -3353,12 +3311,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 8: {
@@ -3422,14 +3385,14 @@
break;
}
case 146: {
- if (!HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage();
}
input.ReadMessage(OptionalNestedMessage);
break;
}
case 154: {
- if (!HasOptionalForeignMessage) {
+ if (optionalForeignMessage_ == null) {
OptionalForeignMessage = new global::ProtobufTestMessages.Proto2.ForeignMessageProto2();
}
input.ReadMessage(OptionalForeignMessage);
@@ -3452,7 +3415,7 @@
break;
}
case 218: {
- if (!HasRecursiveMessage) {
+ if (recursiveMessage_ == null) {
RecursiveMessage = new global::ProtobufTestMessages.Proto2.TestAllTypesProto2();
}
input.ReadMessage(RecursiveMessage);
@@ -3460,317 +3423,317 @@
}
case 250:
case 248: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
case 258:
case 256: {
- repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec);
+ repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec);
break;
}
case 266:
case 264: {
- repeatedUint32_.AddEntriesFrom(input, _repeated_repeatedUint32_codec);
+ repeatedUint32_.AddEntriesFrom(ref input, _repeated_repeatedUint32_codec);
break;
}
case 274:
case 272: {
- repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec);
+ repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec);
break;
}
case 282:
case 280: {
- repeatedSint32_.AddEntriesFrom(input, _repeated_repeatedSint32_codec);
+ repeatedSint32_.AddEntriesFrom(ref input, _repeated_repeatedSint32_codec);
break;
}
case 290:
case 288: {
- repeatedSint64_.AddEntriesFrom(input, _repeated_repeatedSint64_codec);
+ repeatedSint64_.AddEntriesFrom(ref input, _repeated_repeatedSint64_codec);
break;
}
case 298:
case 301: {
- repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec);
+ repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec);
break;
}
case 306:
case 305: {
- repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec);
+ repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec);
break;
}
case 314:
case 317: {
- repeatedSfixed32_.AddEntriesFrom(input, _repeated_repeatedSfixed32_codec);
+ repeatedSfixed32_.AddEntriesFrom(ref input, _repeated_repeatedSfixed32_codec);
break;
}
case 322:
case 321: {
- repeatedSfixed64_.AddEntriesFrom(input, _repeated_repeatedSfixed64_codec);
+ repeatedSfixed64_.AddEntriesFrom(ref input, _repeated_repeatedSfixed64_codec);
break;
}
case 330:
case 333: {
- repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec);
+ repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec);
break;
}
case 338:
case 337: {
- repeatedDouble_.AddEntriesFrom(input, _repeated_repeatedDouble_codec);
+ repeatedDouble_.AddEntriesFrom(ref input, _repeated_repeatedDouble_codec);
break;
}
case 346:
case 344: {
- repeatedBool_.AddEntriesFrom(input, _repeated_repeatedBool_codec);
+ repeatedBool_.AddEntriesFrom(ref input, _repeated_repeatedBool_codec);
break;
}
case 354: {
- repeatedString_.AddEntriesFrom(input, _repeated_repeatedString_codec);
+ repeatedString_.AddEntriesFrom(ref input, _repeated_repeatedString_codec);
break;
}
case 362: {
- repeatedBytes_.AddEntriesFrom(input, _repeated_repeatedBytes_codec);
+ repeatedBytes_.AddEntriesFrom(ref input, _repeated_repeatedBytes_codec);
break;
}
case 386: {
- repeatedNestedMessage_.AddEntriesFrom(input, _repeated_repeatedNestedMessage_codec);
+ repeatedNestedMessage_.AddEntriesFrom(ref input, _repeated_repeatedNestedMessage_codec);
break;
}
case 394: {
- repeatedForeignMessage_.AddEntriesFrom(input, _repeated_repeatedForeignMessage_codec);
+ repeatedForeignMessage_.AddEntriesFrom(ref input, _repeated_repeatedForeignMessage_codec);
break;
}
case 410:
case 408: {
- repeatedNestedEnum_.AddEntriesFrom(input, _repeated_repeatedNestedEnum_codec);
+ repeatedNestedEnum_.AddEntriesFrom(ref input, _repeated_repeatedNestedEnum_codec);
break;
}
case 418:
case 416: {
- repeatedForeignEnum_.AddEntriesFrom(input, _repeated_repeatedForeignEnum_codec);
+ repeatedForeignEnum_.AddEntriesFrom(ref input, _repeated_repeatedForeignEnum_codec);
break;
}
case 434: {
- repeatedStringPiece_.AddEntriesFrom(input, _repeated_repeatedStringPiece_codec);
+ repeatedStringPiece_.AddEntriesFrom(ref input, _repeated_repeatedStringPiece_codec);
break;
}
case 442: {
- repeatedCord_.AddEntriesFrom(input, _repeated_repeatedCord_codec);
+ repeatedCord_.AddEntriesFrom(ref input, _repeated_repeatedCord_codec);
break;
}
case 450: {
- mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec);
+ mapInt32Int32_.AddEntriesFrom(ref input, _map_mapInt32Int32_codec);
break;
}
case 458: {
- mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec);
+ mapInt64Int64_.AddEntriesFrom(ref input, _map_mapInt64Int64_codec);
break;
}
case 466: {
- mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec);
+ mapUint32Uint32_.AddEntriesFrom(ref input, _map_mapUint32Uint32_codec);
break;
}
case 474: {
- mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec);
+ mapUint64Uint64_.AddEntriesFrom(ref input, _map_mapUint64Uint64_codec);
break;
}
case 482: {
- mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec);
+ mapSint32Sint32_.AddEntriesFrom(ref input, _map_mapSint32Sint32_codec);
break;
}
case 490: {
- mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec);
+ mapSint64Sint64_.AddEntriesFrom(ref input, _map_mapSint64Sint64_codec);
break;
}
case 498: {
- mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec);
+ mapFixed32Fixed32_.AddEntriesFrom(ref input, _map_mapFixed32Fixed32_codec);
break;
}
case 506: {
- mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec);
+ mapFixed64Fixed64_.AddEntriesFrom(ref input, _map_mapFixed64Fixed64_codec);
break;
}
case 514: {
- mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec);
+ mapSfixed32Sfixed32_.AddEntriesFrom(ref input, _map_mapSfixed32Sfixed32_codec);
break;
}
case 522: {
- mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec);
+ mapSfixed64Sfixed64_.AddEntriesFrom(ref input, _map_mapSfixed64Sfixed64_codec);
break;
}
case 530: {
- mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec);
+ mapInt32Float_.AddEntriesFrom(ref input, _map_mapInt32Float_codec);
break;
}
case 538: {
- mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec);
+ mapInt32Double_.AddEntriesFrom(ref input, _map_mapInt32Double_codec);
break;
}
case 546: {
- mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec);
+ mapBoolBool_.AddEntriesFrom(ref input, _map_mapBoolBool_codec);
break;
}
case 554: {
- mapStringString_.AddEntriesFrom(input, _map_mapStringString_codec);
+ mapStringString_.AddEntriesFrom(ref input, _map_mapStringString_codec);
break;
}
case 562: {
- mapStringBytes_.AddEntriesFrom(input, _map_mapStringBytes_codec);
+ mapStringBytes_.AddEntriesFrom(ref input, _map_mapStringBytes_codec);
break;
}
case 570: {
- mapStringNestedMessage_.AddEntriesFrom(input, _map_mapStringNestedMessage_codec);
+ mapStringNestedMessage_.AddEntriesFrom(ref input, _map_mapStringNestedMessage_codec);
break;
}
case 578: {
- mapStringForeignMessage_.AddEntriesFrom(input, _map_mapStringForeignMessage_codec);
+ mapStringForeignMessage_.AddEntriesFrom(ref input, _map_mapStringForeignMessage_codec);
break;
}
case 586: {
- mapStringNestedEnum_.AddEntriesFrom(input, _map_mapStringNestedEnum_codec);
+ mapStringNestedEnum_.AddEntriesFrom(ref input, _map_mapStringNestedEnum_codec);
break;
}
case 594: {
- mapStringForeignEnum_.AddEntriesFrom(input, _map_mapStringForeignEnum_codec);
+ mapStringForeignEnum_.AddEntriesFrom(ref input, _map_mapStringForeignEnum_codec);
break;
}
case 602:
case 600: {
- packedInt32_.AddEntriesFrom(input, _repeated_packedInt32_codec);
+ packedInt32_.AddEntriesFrom(ref input, _repeated_packedInt32_codec);
break;
}
case 610:
case 608: {
- packedInt64_.AddEntriesFrom(input, _repeated_packedInt64_codec);
+ packedInt64_.AddEntriesFrom(ref input, _repeated_packedInt64_codec);
break;
}
case 618:
case 616: {
- packedUint32_.AddEntriesFrom(input, _repeated_packedUint32_codec);
+ packedUint32_.AddEntriesFrom(ref input, _repeated_packedUint32_codec);
break;
}
case 626:
case 624: {
- packedUint64_.AddEntriesFrom(input, _repeated_packedUint64_codec);
+ packedUint64_.AddEntriesFrom(ref input, _repeated_packedUint64_codec);
break;
}
case 634:
case 632: {
- packedSint32_.AddEntriesFrom(input, _repeated_packedSint32_codec);
+ packedSint32_.AddEntriesFrom(ref input, _repeated_packedSint32_codec);
break;
}
case 642:
case 640: {
- packedSint64_.AddEntriesFrom(input, _repeated_packedSint64_codec);
+ packedSint64_.AddEntriesFrom(ref input, _repeated_packedSint64_codec);
break;
}
case 650:
case 653: {
- packedFixed32_.AddEntriesFrom(input, _repeated_packedFixed32_codec);
+ packedFixed32_.AddEntriesFrom(ref input, _repeated_packedFixed32_codec);
break;
}
case 658:
case 657: {
- packedFixed64_.AddEntriesFrom(input, _repeated_packedFixed64_codec);
+ packedFixed64_.AddEntriesFrom(ref input, _repeated_packedFixed64_codec);
break;
}
case 666:
case 669: {
- packedSfixed32_.AddEntriesFrom(input, _repeated_packedSfixed32_codec);
+ packedSfixed32_.AddEntriesFrom(ref input, _repeated_packedSfixed32_codec);
break;
}
case 674:
case 673: {
- packedSfixed64_.AddEntriesFrom(input, _repeated_packedSfixed64_codec);
+ packedSfixed64_.AddEntriesFrom(ref input, _repeated_packedSfixed64_codec);
break;
}
case 682:
case 685: {
- packedFloat_.AddEntriesFrom(input, _repeated_packedFloat_codec);
+ packedFloat_.AddEntriesFrom(ref input, _repeated_packedFloat_codec);
break;
}
case 690:
case 689: {
- packedDouble_.AddEntriesFrom(input, _repeated_packedDouble_codec);
+ packedDouble_.AddEntriesFrom(ref input, _repeated_packedDouble_codec);
break;
}
case 698:
case 696: {
- packedBool_.AddEntriesFrom(input, _repeated_packedBool_codec);
+ packedBool_.AddEntriesFrom(ref input, _repeated_packedBool_codec);
break;
}
case 706:
case 704: {
- packedNestedEnum_.AddEntriesFrom(input, _repeated_packedNestedEnum_codec);
+ packedNestedEnum_.AddEntriesFrom(ref input, _repeated_packedNestedEnum_codec);
break;
}
case 714:
case 712: {
- unpackedInt32_.AddEntriesFrom(input, _repeated_unpackedInt32_codec);
+ unpackedInt32_.AddEntriesFrom(ref input, _repeated_unpackedInt32_codec);
break;
}
case 722:
case 720: {
- unpackedInt64_.AddEntriesFrom(input, _repeated_unpackedInt64_codec);
+ unpackedInt64_.AddEntriesFrom(ref input, _repeated_unpackedInt64_codec);
break;
}
case 730:
case 728: {
- unpackedUint32_.AddEntriesFrom(input, _repeated_unpackedUint32_codec);
+ unpackedUint32_.AddEntriesFrom(ref input, _repeated_unpackedUint32_codec);
break;
}
case 738:
case 736: {
- unpackedUint64_.AddEntriesFrom(input, _repeated_unpackedUint64_codec);
+ unpackedUint64_.AddEntriesFrom(ref input, _repeated_unpackedUint64_codec);
break;
}
case 746:
case 744: {
- unpackedSint32_.AddEntriesFrom(input, _repeated_unpackedSint32_codec);
+ unpackedSint32_.AddEntriesFrom(ref input, _repeated_unpackedSint32_codec);
break;
}
case 754:
case 752: {
- unpackedSint64_.AddEntriesFrom(input, _repeated_unpackedSint64_codec);
+ unpackedSint64_.AddEntriesFrom(ref input, _repeated_unpackedSint64_codec);
break;
}
case 762:
case 765: {
- unpackedFixed32_.AddEntriesFrom(input, _repeated_unpackedFixed32_codec);
+ unpackedFixed32_.AddEntriesFrom(ref input, _repeated_unpackedFixed32_codec);
break;
}
case 770:
case 769: {
- unpackedFixed64_.AddEntriesFrom(input, _repeated_unpackedFixed64_codec);
+ unpackedFixed64_.AddEntriesFrom(ref input, _repeated_unpackedFixed64_codec);
break;
}
case 778:
case 781: {
- unpackedSfixed32_.AddEntriesFrom(input, _repeated_unpackedSfixed32_codec);
+ unpackedSfixed32_.AddEntriesFrom(ref input, _repeated_unpackedSfixed32_codec);
break;
}
case 786:
case 785: {
- unpackedSfixed64_.AddEntriesFrom(input, _repeated_unpackedSfixed64_codec);
+ unpackedSfixed64_.AddEntriesFrom(ref input, _repeated_unpackedSfixed64_codec);
break;
}
case 794:
case 797: {
- unpackedFloat_.AddEntriesFrom(input, _repeated_unpackedFloat_codec);
+ unpackedFloat_.AddEntriesFrom(ref input, _repeated_unpackedFloat_codec);
break;
}
case 802:
case 801: {
- unpackedDouble_.AddEntriesFrom(input, _repeated_unpackedDouble_codec);
+ unpackedDouble_.AddEntriesFrom(ref input, _repeated_unpackedDouble_codec);
break;
}
case 810:
case 808: {
- unpackedBool_.AddEntriesFrom(input, _repeated_unpackedBool_codec);
+ unpackedBool_.AddEntriesFrom(ref input, _repeated_unpackedBool_codec);
break;
}
case 818:
case 816: {
- unpackedNestedEnum_.AddEntriesFrom(input, _repeated_unpackedNestedEnum_codec);
+ unpackedNestedEnum_.AddEntriesFrom(ref input, _repeated_unpackedNestedEnum_codec);
break;
}
case 888: {
@@ -3779,7 +3742,7 @@
}
case 898: {
global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage subBuilder = new global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage();
- if (HasOneofNestedMessage) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) {
subBuilder.MergeFrom(OneofNestedMessage);
}
input.ReadMessage(subBuilder);
@@ -3934,7 +3897,7 @@
[pbr::OriginalName("NEG")] Neg = -1,
}
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -3962,7 +3925,7 @@
public NestedMessage(NestedMessage other) : this() {
_hasBits0 = other._hasBits0;
a_ = other.a_;
- corecursive_ = other.HasCorecursive ? other.corecursive_.Clone() : null;
+ corecursive_ = other.corecursive_ != null ? other.corecursive_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -4005,16 +3968,6 @@
corecursive_ = value;
}
}
- /// <summary>Gets whether the corecursive field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasCorecursive {
- get { return corecursive_ != null; }
- }
- /// <summary>Clears the value of the corecursive field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearCorecursive() {
- corecursive_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -4038,7 +3991,7 @@
public override int GetHashCode() {
int hash = 1;
if (HasA) hash ^= A.GetHashCode();
- if (HasCorecursive) hash ^= Corecursive.GetHashCode();
+ if (corecursive_ != null) hash ^= Corecursive.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -4056,7 +4009,7 @@
output.WriteRawTag(8);
output.WriteInt32(A);
}
- if (HasCorecursive) {
+ if (corecursive_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Corecursive);
}
@@ -4071,7 +4024,7 @@
if (HasA) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(A);
}
- if (HasCorecursive) {
+ if (corecursive_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Corecursive);
}
if (_unknownFields != null) {
@@ -4088,8 +4041,8 @@
if (other.HasA) {
A = other.A;
}
- if (other.HasCorecursive) {
- if (!HasCorecursive) {
+ if (other.corecursive_ != null) {
+ if (corecursive_ == null) {
Corecursive = new global::ProtobufTestMessages.Proto2.TestAllTypesProto2();
}
Corecursive.MergeFrom(other.Corecursive);
@@ -4099,18 +4052,23 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
break;
}
case 18: {
- if (!HasCorecursive) {
+ if (corecursive_ == null) {
Corecursive = new global::ProtobufTestMessages.Proto2.TestAllTypesProto2();
}
input.ReadMessage(Corecursive);
@@ -4125,7 +4083,7 @@
/// <summary>
/// groups
/// </summary>
- public sealed partial class Data : pb::IMessage<Data> {
+ public sealed partial class Data : pb::IMessage<Data>, pb::IBufferMessage {
private static readonly pb::MessageParser<Data> _parser = new pb::MessageParser<Data>(() => new Data());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4290,13 +4248,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 1612:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 1616: {
GroupInt32 = input.ReadInt32();
@@ -4315,7 +4278,7 @@
/// <summary>
/// message_set test case.
/// </summary>
- public sealed partial class MessageSetCorrect : pb::IExtendableMessage<MessageSetCorrect> {
+ public sealed partial class MessageSetCorrect : pb::IExtendableMessage<MessageSetCorrect>, pb::IBufferMessage {
private static readonly pb::MessageParser<MessageSetCorrect> _parser = new pb::MessageParser<MessageSetCorrect>(() => new MessageSetCorrect());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<MessageSetCorrect> _extensions;
@@ -4420,12 +4383,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
}
@@ -4456,7 +4424,7 @@
}
- public sealed partial class MessageSetCorrectExtension1 : pb::IMessage<MessageSetCorrectExtension1> {
+ public sealed partial class MessageSetCorrectExtension1 : pb::IMessage<MessageSetCorrectExtension1>, pb::IBufferMessage {
private static readonly pb::MessageParser<MessageSetCorrectExtension1> _parser = new pb::MessageParser<MessageSetCorrectExtension1>(() => new MessageSetCorrectExtension1());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4581,11 +4549,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 202: {
Str = input.ReadString();
@@ -4606,7 +4579,7 @@
}
- public sealed partial class MessageSetCorrectExtension2 : pb::IMessage<MessageSetCorrectExtension2> {
+ public sealed partial class MessageSetCorrectExtension2 : pb::IMessage<MessageSetCorrectExtension2>, pb::IBufferMessage {
private static readonly pb::MessageParser<MessageSetCorrectExtension2> _parser = new pb::MessageParser<MessageSetCorrectExtension2>(() => new MessageSetCorrectExtension2());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4734,11 +4707,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 72: {
I = input.ReadInt32();
@@ -4764,7 +4742,7 @@
}
- public sealed partial class ForeignMessageProto2 : pb::IMessage<ForeignMessageProto2> {
+ public sealed partial class ForeignMessageProto2 : pb::IMessage<ForeignMessageProto2>, pb::IBufferMessage {
private static readonly pb::MessageParser<ForeignMessageProto2> _parser = new pb::MessageParser<ForeignMessageProto2>(() => new ForeignMessageProto2());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4892,11 +4870,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
C = input.ReadInt32();
@@ -4908,7 +4891,7 @@
}
- public sealed partial class UnknownToTestAllTypes : pb::IMessage<UnknownToTestAllTypes> {
+ public sealed partial class UnknownToTestAllTypes : pb::IMessage<UnknownToTestAllTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<UnknownToTestAllTypes> _parser = new pb::MessageParser<UnknownToTestAllTypes>(() => new UnknownToTestAllTypes());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4937,7 +4920,7 @@
_hasBits0 = other._hasBits0;
optionalInt32_ = other.optionalInt32_;
optionalString_ = other.optionalString_;
- nestedMessage_ = other.HasNestedMessage ? other.nestedMessage_.Clone() : null;
+ nestedMessage_ = other.nestedMessage_ != null ? other.nestedMessage_.Clone() : null;
optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null;
optionalBool_ = other.optionalBool_;
repeatedInt32_ = other.repeatedInt32_.Clone();
@@ -5006,16 +4989,6 @@
nestedMessage_ = value;
}
}
- /// <summary>Gets whether the nested_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasNestedMessage {
- get { return nestedMessage_ != null; }
- }
- /// <summary>Clears the value of the nested_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearNestedMessage() {
- nestedMessage_ = null;
- }
/// <summary>Field number for the "optionalgroup" field.</summary>
public const int OptionalGroupFieldNumber = 1004;
@@ -5099,7 +5072,7 @@
int hash = 1;
if (HasOptionalInt32) hash ^= OptionalInt32.GetHashCode();
if (HasOptionalString) hash ^= OptionalString.GetHashCode();
- if (HasNestedMessage) hash ^= NestedMessage.GetHashCode();
+ if (nestedMessage_ != null) hash ^= NestedMessage.GetHashCode();
if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode();
if (HasOptionalBool) hash ^= OptionalBool.GetHashCode();
hash ^= repeatedInt32_.GetHashCode();
@@ -5124,7 +5097,7 @@
output.WriteRawTag(210, 62);
output.WriteString(OptionalString);
}
- if (HasNestedMessage) {
+ if (nestedMessage_ != null) {
output.WriteRawTag(218, 62);
output.WriteMessage(NestedMessage);
}
@@ -5152,7 +5125,7 @@
if (HasOptionalString) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalString);
}
- if (HasNestedMessage) {
+ if (nestedMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(NestedMessage);
}
if (HasOptionalGroup) {
@@ -5179,8 +5152,8 @@
if (other.HasOptionalString) {
OptionalString = other.OptionalString;
}
- if (other.HasNestedMessage) {
- if (!HasNestedMessage) {
+ if (other.nestedMessage_ != null) {
+ if (nestedMessage_ == null) {
NestedMessage = new global::ProtobufTestMessages.Proto2.ForeignMessageProto2();
}
NestedMessage.MergeFrom(other.NestedMessage);
@@ -5200,11 +5173,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8008: {
OptionalInt32 = input.ReadInt32();
@@ -5215,7 +5193,7 @@
break;
}
case 8026: {
- if (!HasNestedMessage) {
+ if (nestedMessage_ == null) {
NestedMessage = new global::ProtobufTestMessages.Proto2.ForeignMessageProto2();
}
input.ReadMessage(NestedMessage);
@@ -5234,7 +5212,7 @@
}
case 8090:
case 8088: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
}
@@ -5245,7 +5223,7 @@
/// <summary>Container for nested types declared in the UnknownToTestAllTypes message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup> {
+ public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<OptionalGroup> _parser = new pb::MessageParser<OptionalGroup>(() => new OptionalGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -5373,13 +5351,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 8036:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs b/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs
index 064d0c0..465d5e8 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs
@@ -259,7 +259,7 @@
/// could trigger bugs that occur in any message type in this file. We verify
/// this stays true in a unit test.
/// </summary>
- public sealed partial class TestAllTypesProto3 : pb::IMessage<TestAllTypesProto3> {
+ public sealed partial class TestAllTypesProto3 : pb::IMessage<TestAllTypesProto3>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestAllTypesProto3> _parser = new pb::MessageParser<TestAllTypesProto3>(() => new TestAllTypesProto3());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3383,11 +3383,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
OptionalInt32 = input.ReadInt32();
@@ -3492,317 +3497,317 @@
}
case 250:
case 248: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
case 258:
case 256: {
- repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec);
+ repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec);
break;
}
case 266:
case 264: {
- repeatedUint32_.AddEntriesFrom(input, _repeated_repeatedUint32_codec);
+ repeatedUint32_.AddEntriesFrom(ref input, _repeated_repeatedUint32_codec);
break;
}
case 274:
case 272: {
- repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec);
+ repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec);
break;
}
case 282:
case 280: {
- repeatedSint32_.AddEntriesFrom(input, _repeated_repeatedSint32_codec);
+ repeatedSint32_.AddEntriesFrom(ref input, _repeated_repeatedSint32_codec);
break;
}
case 290:
case 288: {
- repeatedSint64_.AddEntriesFrom(input, _repeated_repeatedSint64_codec);
+ repeatedSint64_.AddEntriesFrom(ref input, _repeated_repeatedSint64_codec);
break;
}
case 298:
case 301: {
- repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec);
+ repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec);
break;
}
case 306:
case 305: {
- repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec);
+ repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec);
break;
}
case 314:
case 317: {
- repeatedSfixed32_.AddEntriesFrom(input, _repeated_repeatedSfixed32_codec);
+ repeatedSfixed32_.AddEntriesFrom(ref input, _repeated_repeatedSfixed32_codec);
break;
}
case 322:
case 321: {
- repeatedSfixed64_.AddEntriesFrom(input, _repeated_repeatedSfixed64_codec);
+ repeatedSfixed64_.AddEntriesFrom(ref input, _repeated_repeatedSfixed64_codec);
break;
}
case 330:
case 333: {
- repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec);
+ repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec);
break;
}
case 338:
case 337: {
- repeatedDouble_.AddEntriesFrom(input, _repeated_repeatedDouble_codec);
+ repeatedDouble_.AddEntriesFrom(ref input, _repeated_repeatedDouble_codec);
break;
}
case 346:
case 344: {
- repeatedBool_.AddEntriesFrom(input, _repeated_repeatedBool_codec);
+ repeatedBool_.AddEntriesFrom(ref input, _repeated_repeatedBool_codec);
break;
}
case 354: {
- repeatedString_.AddEntriesFrom(input, _repeated_repeatedString_codec);
+ repeatedString_.AddEntriesFrom(ref input, _repeated_repeatedString_codec);
break;
}
case 362: {
- repeatedBytes_.AddEntriesFrom(input, _repeated_repeatedBytes_codec);
+ repeatedBytes_.AddEntriesFrom(ref input, _repeated_repeatedBytes_codec);
break;
}
case 386: {
- repeatedNestedMessage_.AddEntriesFrom(input, _repeated_repeatedNestedMessage_codec);
+ repeatedNestedMessage_.AddEntriesFrom(ref input, _repeated_repeatedNestedMessage_codec);
break;
}
case 394: {
- repeatedForeignMessage_.AddEntriesFrom(input, _repeated_repeatedForeignMessage_codec);
+ repeatedForeignMessage_.AddEntriesFrom(ref input, _repeated_repeatedForeignMessage_codec);
break;
}
case 410:
case 408: {
- repeatedNestedEnum_.AddEntriesFrom(input, _repeated_repeatedNestedEnum_codec);
+ repeatedNestedEnum_.AddEntriesFrom(ref input, _repeated_repeatedNestedEnum_codec);
break;
}
case 418:
case 416: {
- repeatedForeignEnum_.AddEntriesFrom(input, _repeated_repeatedForeignEnum_codec);
+ repeatedForeignEnum_.AddEntriesFrom(ref input, _repeated_repeatedForeignEnum_codec);
break;
}
case 434: {
- repeatedStringPiece_.AddEntriesFrom(input, _repeated_repeatedStringPiece_codec);
+ repeatedStringPiece_.AddEntriesFrom(ref input, _repeated_repeatedStringPiece_codec);
break;
}
case 442: {
- repeatedCord_.AddEntriesFrom(input, _repeated_repeatedCord_codec);
+ repeatedCord_.AddEntriesFrom(ref input, _repeated_repeatedCord_codec);
break;
}
case 450: {
- mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec);
+ mapInt32Int32_.AddEntriesFrom(ref input, _map_mapInt32Int32_codec);
break;
}
case 458: {
- mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec);
+ mapInt64Int64_.AddEntriesFrom(ref input, _map_mapInt64Int64_codec);
break;
}
case 466: {
- mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec);
+ mapUint32Uint32_.AddEntriesFrom(ref input, _map_mapUint32Uint32_codec);
break;
}
case 474: {
- mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec);
+ mapUint64Uint64_.AddEntriesFrom(ref input, _map_mapUint64Uint64_codec);
break;
}
case 482: {
- mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec);
+ mapSint32Sint32_.AddEntriesFrom(ref input, _map_mapSint32Sint32_codec);
break;
}
case 490: {
- mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec);
+ mapSint64Sint64_.AddEntriesFrom(ref input, _map_mapSint64Sint64_codec);
break;
}
case 498: {
- mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec);
+ mapFixed32Fixed32_.AddEntriesFrom(ref input, _map_mapFixed32Fixed32_codec);
break;
}
case 506: {
- mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec);
+ mapFixed64Fixed64_.AddEntriesFrom(ref input, _map_mapFixed64Fixed64_codec);
break;
}
case 514: {
- mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec);
+ mapSfixed32Sfixed32_.AddEntriesFrom(ref input, _map_mapSfixed32Sfixed32_codec);
break;
}
case 522: {
- mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec);
+ mapSfixed64Sfixed64_.AddEntriesFrom(ref input, _map_mapSfixed64Sfixed64_codec);
break;
}
case 530: {
- mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec);
+ mapInt32Float_.AddEntriesFrom(ref input, _map_mapInt32Float_codec);
break;
}
case 538: {
- mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec);
+ mapInt32Double_.AddEntriesFrom(ref input, _map_mapInt32Double_codec);
break;
}
case 546: {
- mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec);
+ mapBoolBool_.AddEntriesFrom(ref input, _map_mapBoolBool_codec);
break;
}
case 554: {
- mapStringString_.AddEntriesFrom(input, _map_mapStringString_codec);
+ mapStringString_.AddEntriesFrom(ref input, _map_mapStringString_codec);
break;
}
case 562: {
- mapStringBytes_.AddEntriesFrom(input, _map_mapStringBytes_codec);
+ mapStringBytes_.AddEntriesFrom(ref input, _map_mapStringBytes_codec);
break;
}
case 570: {
- mapStringNestedMessage_.AddEntriesFrom(input, _map_mapStringNestedMessage_codec);
+ mapStringNestedMessage_.AddEntriesFrom(ref input, _map_mapStringNestedMessage_codec);
break;
}
case 578: {
- mapStringForeignMessage_.AddEntriesFrom(input, _map_mapStringForeignMessage_codec);
+ mapStringForeignMessage_.AddEntriesFrom(ref input, _map_mapStringForeignMessage_codec);
break;
}
case 586: {
- mapStringNestedEnum_.AddEntriesFrom(input, _map_mapStringNestedEnum_codec);
+ mapStringNestedEnum_.AddEntriesFrom(ref input, _map_mapStringNestedEnum_codec);
break;
}
case 594: {
- mapStringForeignEnum_.AddEntriesFrom(input, _map_mapStringForeignEnum_codec);
+ mapStringForeignEnum_.AddEntriesFrom(ref input, _map_mapStringForeignEnum_codec);
break;
}
case 602:
case 600: {
- packedInt32_.AddEntriesFrom(input, _repeated_packedInt32_codec);
+ packedInt32_.AddEntriesFrom(ref input, _repeated_packedInt32_codec);
break;
}
case 610:
case 608: {
- packedInt64_.AddEntriesFrom(input, _repeated_packedInt64_codec);
+ packedInt64_.AddEntriesFrom(ref input, _repeated_packedInt64_codec);
break;
}
case 618:
case 616: {
- packedUint32_.AddEntriesFrom(input, _repeated_packedUint32_codec);
+ packedUint32_.AddEntriesFrom(ref input, _repeated_packedUint32_codec);
break;
}
case 626:
case 624: {
- packedUint64_.AddEntriesFrom(input, _repeated_packedUint64_codec);
+ packedUint64_.AddEntriesFrom(ref input, _repeated_packedUint64_codec);
break;
}
case 634:
case 632: {
- packedSint32_.AddEntriesFrom(input, _repeated_packedSint32_codec);
+ packedSint32_.AddEntriesFrom(ref input, _repeated_packedSint32_codec);
break;
}
case 642:
case 640: {
- packedSint64_.AddEntriesFrom(input, _repeated_packedSint64_codec);
+ packedSint64_.AddEntriesFrom(ref input, _repeated_packedSint64_codec);
break;
}
case 650:
case 653: {
- packedFixed32_.AddEntriesFrom(input, _repeated_packedFixed32_codec);
+ packedFixed32_.AddEntriesFrom(ref input, _repeated_packedFixed32_codec);
break;
}
case 658:
case 657: {
- packedFixed64_.AddEntriesFrom(input, _repeated_packedFixed64_codec);
+ packedFixed64_.AddEntriesFrom(ref input, _repeated_packedFixed64_codec);
break;
}
case 666:
case 669: {
- packedSfixed32_.AddEntriesFrom(input, _repeated_packedSfixed32_codec);
+ packedSfixed32_.AddEntriesFrom(ref input, _repeated_packedSfixed32_codec);
break;
}
case 674:
case 673: {
- packedSfixed64_.AddEntriesFrom(input, _repeated_packedSfixed64_codec);
+ packedSfixed64_.AddEntriesFrom(ref input, _repeated_packedSfixed64_codec);
break;
}
case 682:
case 685: {
- packedFloat_.AddEntriesFrom(input, _repeated_packedFloat_codec);
+ packedFloat_.AddEntriesFrom(ref input, _repeated_packedFloat_codec);
break;
}
case 690:
case 689: {
- packedDouble_.AddEntriesFrom(input, _repeated_packedDouble_codec);
+ packedDouble_.AddEntriesFrom(ref input, _repeated_packedDouble_codec);
break;
}
case 698:
case 696: {
- packedBool_.AddEntriesFrom(input, _repeated_packedBool_codec);
+ packedBool_.AddEntriesFrom(ref input, _repeated_packedBool_codec);
break;
}
case 706:
case 704: {
- packedNestedEnum_.AddEntriesFrom(input, _repeated_packedNestedEnum_codec);
+ packedNestedEnum_.AddEntriesFrom(ref input, _repeated_packedNestedEnum_codec);
break;
}
case 714:
case 712: {
- unpackedInt32_.AddEntriesFrom(input, _repeated_unpackedInt32_codec);
+ unpackedInt32_.AddEntriesFrom(ref input, _repeated_unpackedInt32_codec);
break;
}
case 722:
case 720: {
- unpackedInt64_.AddEntriesFrom(input, _repeated_unpackedInt64_codec);
+ unpackedInt64_.AddEntriesFrom(ref input, _repeated_unpackedInt64_codec);
break;
}
case 730:
case 728: {
- unpackedUint32_.AddEntriesFrom(input, _repeated_unpackedUint32_codec);
+ unpackedUint32_.AddEntriesFrom(ref input, _repeated_unpackedUint32_codec);
break;
}
case 738:
case 736: {
- unpackedUint64_.AddEntriesFrom(input, _repeated_unpackedUint64_codec);
+ unpackedUint64_.AddEntriesFrom(ref input, _repeated_unpackedUint64_codec);
break;
}
case 746:
case 744: {
- unpackedSint32_.AddEntriesFrom(input, _repeated_unpackedSint32_codec);
+ unpackedSint32_.AddEntriesFrom(ref input, _repeated_unpackedSint32_codec);
break;
}
case 754:
case 752: {
- unpackedSint64_.AddEntriesFrom(input, _repeated_unpackedSint64_codec);
+ unpackedSint64_.AddEntriesFrom(ref input, _repeated_unpackedSint64_codec);
break;
}
case 762:
case 765: {
- unpackedFixed32_.AddEntriesFrom(input, _repeated_unpackedFixed32_codec);
+ unpackedFixed32_.AddEntriesFrom(ref input, _repeated_unpackedFixed32_codec);
break;
}
case 770:
case 769: {
- unpackedFixed64_.AddEntriesFrom(input, _repeated_unpackedFixed64_codec);
+ unpackedFixed64_.AddEntriesFrom(ref input, _repeated_unpackedFixed64_codec);
break;
}
case 778:
case 781: {
- unpackedSfixed32_.AddEntriesFrom(input, _repeated_unpackedSfixed32_codec);
+ unpackedSfixed32_.AddEntriesFrom(ref input, _repeated_unpackedSfixed32_codec);
break;
}
case 786:
case 785: {
- unpackedSfixed64_.AddEntriesFrom(input, _repeated_unpackedSfixed64_codec);
+ unpackedSfixed64_.AddEntriesFrom(ref input, _repeated_unpackedSfixed64_codec);
break;
}
case 794:
case 797: {
- unpackedFloat_.AddEntriesFrom(input, _repeated_unpackedFloat_codec);
+ unpackedFloat_.AddEntriesFrom(ref input, _repeated_unpackedFloat_codec);
break;
}
case 802:
case 801: {
- unpackedDouble_.AddEntriesFrom(input, _repeated_unpackedDouble_codec);
+ unpackedDouble_.AddEntriesFrom(ref input, _repeated_unpackedDouble_codec);
break;
}
case 810:
case 808: {
- unpackedBool_.AddEntriesFrom(input, _repeated_unpackedBool_codec);
+ unpackedBool_.AddEntriesFrom(ref input, _repeated_unpackedBool_codec);
break;
}
case 818:
case 816: {
- unpackedNestedEnum_.AddEntriesFrom(input, _repeated_unpackedNestedEnum_codec);
+ unpackedNestedEnum_.AddEntriesFrom(ref input, _repeated_unpackedNestedEnum_codec);
break;
}
case 888: {
@@ -3848,102 +3853,102 @@
break;
}
case 1610: {
- bool? value = _single_optionalBoolWrapper_codec.Read(input);
+ bool? value = _single_optionalBoolWrapper_codec.Read(ref input);
if (optionalBoolWrapper_ == null || value != false) {
OptionalBoolWrapper = value;
}
break;
}
case 1618: {
- int? value = _single_optionalInt32Wrapper_codec.Read(input);
+ int? value = _single_optionalInt32Wrapper_codec.Read(ref input);
if (optionalInt32Wrapper_ == null || value != 0) {
OptionalInt32Wrapper = value;
}
break;
}
case 1626: {
- long? value = _single_optionalInt64Wrapper_codec.Read(input);
+ long? value = _single_optionalInt64Wrapper_codec.Read(ref input);
if (optionalInt64Wrapper_ == null || value != 0L) {
OptionalInt64Wrapper = value;
}
break;
}
case 1634: {
- uint? value = _single_optionalUint32Wrapper_codec.Read(input);
+ uint? value = _single_optionalUint32Wrapper_codec.Read(ref input);
if (optionalUint32Wrapper_ == null || value != 0) {
OptionalUint32Wrapper = value;
}
break;
}
case 1642: {
- ulong? value = _single_optionalUint64Wrapper_codec.Read(input);
+ ulong? value = _single_optionalUint64Wrapper_codec.Read(ref input);
if (optionalUint64Wrapper_ == null || value != 0UL) {
OptionalUint64Wrapper = value;
}
break;
}
case 1650: {
- float? value = _single_optionalFloatWrapper_codec.Read(input);
+ float? value = _single_optionalFloatWrapper_codec.Read(ref input);
if (optionalFloatWrapper_ == null || value != 0F) {
OptionalFloatWrapper = value;
}
break;
}
case 1658: {
- double? value = _single_optionalDoubleWrapper_codec.Read(input);
+ double? value = _single_optionalDoubleWrapper_codec.Read(ref input);
if (optionalDoubleWrapper_ == null || value != 0D) {
OptionalDoubleWrapper = value;
}
break;
}
case 1666: {
- string value = _single_optionalStringWrapper_codec.Read(input);
+ string value = _single_optionalStringWrapper_codec.Read(ref input);
if (optionalStringWrapper_ == null || value != "") {
OptionalStringWrapper = value;
}
break;
}
case 1674: {
- pb::ByteString value = _single_optionalBytesWrapper_codec.Read(input);
+ pb::ByteString value = _single_optionalBytesWrapper_codec.Read(ref input);
if (optionalBytesWrapper_ == null || value != pb::ByteString.Empty) {
OptionalBytesWrapper = value;
}
break;
}
case 1690: {
- repeatedBoolWrapper_.AddEntriesFrom(input, _repeated_repeatedBoolWrapper_codec);
+ repeatedBoolWrapper_.AddEntriesFrom(ref input, _repeated_repeatedBoolWrapper_codec);
break;
}
case 1698: {
- repeatedInt32Wrapper_.AddEntriesFrom(input, _repeated_repeatedInt32Wrapper_codec);
+ repeatedInt32Wrapper_.AddEntriesFrom(ref input, _repeated_repeatedInt32Wrapper_codec);
break;
}
case 1706: {
- repeatedInt64Wrapper_.AddEntriesFrom(input, _repeated_repeatedInt64Wrapper_codec);
+ repeatedInt64Wrapper_.AddEntriesFrom(ref input, _repeated_repeatedInt64Wrapper_codec);
break;
}
case 1714: {
- repeatedUint32Wrapper_.AddEntriesFrom(input, _repeated_repeatedUint32Wrapper_codec);
+ repeatedUint32Wrapper_.AddEntriesFrom(ref input, _repeated_repeatedUint32Wrapper_codec);
break;
}
case 1722: {
- repeatedUint64Wrapper_.AddEntriesFrom(input, _repeated_repeatedUint64Wrapper_codec);
+ repeatedUint64Wrapper_.AddEntriesFrom(ref input, _repeated_repeatedUint64Wrapper_codec);
break;
}
case 1730: {
- repeatedFloatWrapper_.AddEntriesFrom(input, _repeated_repeatedFloatWrapper_codec);
+ repeatedFloatWrapper_.AddEntriesFrom(ref input, _repeated_repeatedFloatWrapper_codec);
break;
}
case 1738: {
- repeatedDoubleWrapper_.AddEntriesFrom(input, _repeated_repeatedDoubleWrapper_codec);
+ repeatedDoubleWrapper_.AddEntriesFrom(ref input, _repeated_repeatedDoubleWrapper_codec);
break;
}
case 1746: {
- repeatedStringWrapper_.AddEntriesFrom(input, _repeated_repeatedStringWrapper_codec);
+ repeatedStringWrapper_.AddEntriesFrom(ref input, _repeated_repeatedStringWrapper_codec);
break;
}
case 1754: {
- repeatedBytesWrapper_.AddEntriesFrom(input, _repeated_repeatedBytesWrapper_codec);
+ repeatedBytesWrapper_.AddEntriesFrom(ref input, _repeated_repeatedBytesWrapper_codec);
break;
}
case 2410: {
@@ -3989,31 +3994,31 @@
break;
}
case 2490: {
- repeatedDuration_.AddEntriesFrom(input, _repeated_repeatedDuration_codec);
+ repeatedDuration_.AddEntriesFrom(ref input, _repeated_repeatedDuration_codec);
break;
}
case 2498: {
- repeatedTimestamp_.AddEntriesFrom(input, _repeated_repeatedTimestamp_codec);
+ repeatedTimestamp_.AddEntriesFrom(ref input, _repeated_repeatedTimestamp_codec);
break;
}
case 2506: {
- repeatedFieldmask_.AddEntriesFrom(input, _repeated_repeatedFieldmask_codec);
+ repeatedFieldmask_.AddEntriesFrom(ref input, _repeated_repeatedFieldmask_codec);
break;
}
case 2522: {
- repeatedAny_.AddEntriesFrom(input, _repeated_repeatedAny_codec);
+ repeatedAny_.AddEntriesFrom(ref input, _repeated_repeatedAny_codec);
break;
}
case 2530: {
- repeatedValue_.AddEntriesFrom(input, _repeated_repeatedValue_codec);
+ repeatedValue_.AddEntriesFrom(ref input, _repeated_repeatedValue_codec);
break;
}
case 2538: {
- repeatedListValue_.AddEntriesFrom(input, _repeated_repeatedListValue_codec);
+ repeatedListValue_.AddEntriesFrom(ref input, _repeated_repeatedListValue_codec);
break;
}
case 2594: {
- repeatedStruct_.AddEntriesFrom(input, _repeated_repeatedStruct_codec);
+ repeatedStruct_.AddEntriesFrom(ref input, _repeated_repeatedStruct_codec);
break;
}
case 3208: {
@@ -4115,7 +4120,7 @@
[pbr::OriginalName("bAz", PreferredAlias = false)] BAz = 2,
}
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4255,11 +4260,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
@@ -4283,7 +4293,7 @@
}
- public sealed partial class ForeignMessage : pb::IMessage<ForeignMessage> {
+ public sealed partial class ForeignMessage : pb::IMessage<ForeignMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<ForeignMessage> _parser = new pb::MessageParser<ForeignMessage>(() => new ForeignMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4396,11 +4406,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
C = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs b/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs
index e55df12..9b5825a 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs
@@ -1120,7 +1120,7 @@
/// This proto includes every type of field in both singular and repeated
/// forms.
/// </summary>
- public sealed partial class TestAllTypes : pb::IMessage<TestAllTypes> {
+ public sealed partial class TestAllTypes : pb::IMessage<TestAllTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestAllTypes> _parser = new pb::MessageParser<TestAllTypes>(() => new TestAllTypes());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -1165,16 +1165,16 @@
optionalString_ = other.optionalString_;
optionalBytes_ = other.optionalBytes_;
optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null;
- optionalNestedMessage_ = other.HasOptionalNestedMessage ? other.optionalNestedMessage_.Clone() : null;
- optionalForeignMessage_ = other.HasOptionalForeignMessage ? other.optionalForeignMessage_.Clone() : null;
- optionalImportMessage_ = other.HasOptionalImportMessage ? other.optionalImportMessage_.Clone() : null;
+ optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null;
+ optionalForeignMessage_ = other.optionalForeignMessage_ != null ? other.optionalForeignMessage_.Clone() : null;
+ optionalImportMessage_ = other.optionalImportMessage_ != null ? other.optionalImportMessage_.Clone() : null;
optionalNestedEnum_ = other.optionalNestedEnum_;
optionalForeignEnum_ = other.optionalForeignEnum_;
optionalImportEnum_ = other.optionalImportEnum_;
optionalStringPiece_ = other.optionalStringPiece_;
optionalCord_ = other.optionalCord_;
- optionalPublicImportMessage_ = other.HasOptionalPublicImportMessage ? other.optionalPublicImportMessage_.Clone() : null;
- optionalLazyMessage_ = other.HasOptionalLazyMessage ? other.optionalLazyMessage_.Clone() : null;
+ optionalPublicImportMessage_ = other.optionalPublicImportMessage_ != null ? other.optionalPublicImportMessage_.Clone() : null;
+ optionalLazyMessage_ = other.optionalLazyMessage_ != null ? other.optionalLazyMessage_.Clone() : null;
repeatedInt32_ = other.repeatedInt32_.Clone();
repeatedInt64_ = other.repeatedInt64_.Clone();
repeatedUint32_ = other.repeatedUint32_.Clone();
@@ -1635,16 +1635,6 @@
optionalNestedMessage_ = value;
}
}
- /// <summary>Gets whether the optional_nested_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalNestedMessage {
- get { return optionalNestedMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_nested_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalNestedMessage() {
- optionalNestedMessage_ = null;
- }
/// <summary>Field number for the "optional_foreign_message" field.</summary>
public const int OptionalForeignMessageFieldNumber = 19;
@@ -1656,16 +1646,6 @@
optionalForeignMessage_ = value;
}
}
- /// <summary>Gets whether the optional_foreign_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalForeignMessage {
- get { return optionalForeignMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_foreign_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalForeignMessage() {
- optionalForeignMessage_ = null;
- }
/// <summary>Field number for the "optional_import_message" field.</summary>
public const int OptionalImportMessageFieldNumber = 20;
@@ -1677,16 +1657,6 @@
optionalImportMessage_ = value;
}
}
- /// <summary>Gets whether the optional_import_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalImportMessage {
- get { return optionalImportMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_import_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalImportMessage() {
- optionalImportMessage_ = null;
- }
/// <summary>Field number for the "optional_nested_enum" field.</summary>
public const int OptionalNestedEnumFieldNumber = 21;
@@ -1819,16 +1789,6 @@
optionalPublicImportMessage_ = value;
}
}
- /// <summary>Gets whether the optional_public_import_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalPublicImportMessage {
- get { return optionalPublicImportMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_public_import_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalPublicImportMessage() {
- optionalPublicImportMessage_ = null;
- }
/// <summary>Field number for the "optional_lazy_message" field.</summary>
public const int OptionalLazyMessageFieldNumber = 27;
@@ -1840,16 +1800,6 @@
optionalLazyMessage_ = value;
}
}
- /// <summary>Gets whether the optional_lazy_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalLazyMessage {
- get { return optionalLazyMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_lazy_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalLazyMessage() {
- optionalLazyMessage_ = null;
- }
/// <summary>Field number for the "repeated_int32" field.</summary>
public const int RepeatedInt32FieldNumber = 31;
@@ -2610,24 +2560,12 @@
public const int OneofNestedMessageFieldNumber = 112;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage OneofNestedMessage {
- get { return HasOneofNestedMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage) oneofField_ : null; }
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage) oneofField_ : null; }
set {
oneofField_ = value;
oneofFieldCase_ = value == null ? OneofFieldOneofCase.None : OneofFieldOneofCase.OneofNestedMessage;
}
}
- /// <summary>Gets whether the "oneof_nested_message" field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOneofNestedMessage {
- get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage; }
- }
- /// <summary> Clears the value of the oneof if it's currently set to "oneof_nested_message" </summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOneofNestedMessage() {
- if (HasOneofNestedMessage) {
- ClearOneofField();
- }
- }
/// <summary>Field number for the "oneof_string" field.</summary>
public const int OneofStringFieldNumber = 113;
@@ -2807,16 +2745,16 @@
if (HasOptionalString) hash ^= OptionalString.GetHashCode();
if (HasOptionalBytes) hash ^= OptionalBytes.GetHashCode();
if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode();
- if (HasOptionalNestedMessage) hash ^= OptionalNestedMessage.GetHashCode();
- if (HasOptionalForeignMessage) hash ^= OptionalForeignMessage.GetHashCode();
- if (HasOptionalImportMessage) hash ^= OptionalImportMessage.GetHashCode();
+ if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode();
+ if (optionalForeignMessage_ != null) hash ^= OptionalForeignMessage.GetHashCode();
+ if (optionalImportMessage_ != null) hash ^= OptionalImportMessage.GetHashCode();
if (HasOptionalNestedEnum) hash ^= OptionalNestedEnum.GetHashCode();
if (HasOptionalForeignEnum) hash ^= OptionalForeignEnum.GetHashCode();
if (HasOptionalImportEnum) hash ^= OptionalImportEnum.GetHashCode();
if (HasOptionalStringPiece) hash ^= OptionalStringPiece.GetHashCode();
if (HasOptionalCord) hash ^= OptionalCord.GetHashCode();
- if (HasOptionalPublicImportMessage) hash ^= OptionalPublicImportMessage.GetHashCode();
- if (HasOptionalLazyMessage) hash ^= OptionalLazyMessage.GetHashCode();
+ if (optionalPublicImportMessage_ != null) hash ^= OptionalPublicImportMessage.GetHashCode();
+ if (optionalLazyMessage_ != null) hash ^= OptionalLazyMessage.GetHashCode();
hash ^= repeatedInt32_.GetHashCode();
hash ^= repeatedInt64_.GetHashCode();
hash ^= repeatedUint32_.GetHashCode();
@@ -2863,7 +2801,7 @@
if (HasDefaultStringPiece) hash ^= DefaultStringPiece.GetHashCode();
if (HasDefaultCord) hash ^= DefaultCord.GetHashCode();
if (HasOneofUint32) hash ^= OneofUint32.GetHashCode();
- if (HasOneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode();
if (HasOneofString) hash ^= OneofString.GetHashCode();
if (HasOneofBytes) hash ^= OneofBytes.GetHashCode();
hash ^= (int) oneofFieldCase_;
@@ -2945,15 +2883,15 @@
output.WriteGroup(OptionalGroup);
output.WriteRawTag(132, 1);
}
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
output.WriteRawTag(146, 1);
output.WriteMessage(OptionalNestedMessage);
}
- if (HasOptionalForeignMessage) {
+ if (optionalForeignMessage_ != null) {
output.WriteRawTag(154, 1);
output.WriteMessage(OptionalForeignMessage);
}
- if (HasOptionalImportMessage) {
+ if (optionalImportMessage_ != null) {
output.WriteRawTag(162, 1);
output.WriteMessage(OptionalImportMessage);
}
@@ -2977,11 +2915,11 @@
output.WriteRawTag(202, 1);
output.WriteString(OptionalCord);
}
- if (HasOptionalPublicImportMessage) {
+ if (optionalPublicImportMessage_ != null) {
output.WriteRawTag(210, 1);
output.WriteMessage(OptionalPublicImportMessage);
}
- if (HasOptionalLazyMessage) {
+ if (optionalLazyMessage_ != null) {
output.WriteRawTag(218, 1);
output.WriteMessage(OptionalLazyMessage);
}
@@ -3094,7 +3032,7 @@
output.WriteRawTag(248, 6);
output.WriteUInt32(OneofUint32);
}
- if (HasOneofNestedMessage) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) {
output.WriteRawTag(130, 7);
output.WriteMessage(OneofNestedMessage);
}
@@ -3162,13 +3100,13 @@
if (HasOptionalGroup) {
size += 4 + pb::CodedOutputStream.ComputeGroupSize(OptionalGroup);
}
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage);
}
- if (HasOptionalForeignMessage) {
+ if (optionalForeignMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalForeignMessage);
}
- if (HasOptionalImportMessage) {
+ if (optionalImportMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalImportMessage);
}
if (HasOptionalNestedEnum) {
@@ -3186,10 +3124,10 @@
if (HasOptionalCord) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalCord);
}
- if (HasOptionalPublicImportMessage) {
+ if (optionalPublicImportMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalPublicImportMessage);
}
- if (HasOptionalLazyMessage) {
+ if (optionalLazyMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalLazyMessage);
}
size += repeatedInt32_.CalculateSize(_repeated_repeatedInt32_codec);
@@ -3280,7 +3218,7 @@
if (HasOneofUint32) {
size += 2 + pb::CodedOutputStream.ComputeUInt32Size(OneofUint32);
}
- if (HasOneofNestedMessage) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OneofNestedMessage);
}
if (HasOneofString) {
@@ -3351,20 +3289,20 @@
}
OptionalGroup.MergeFrom(other.OptionalGroup);
}
- if (other.HasOptionalNestedMessage) {
- if (!HasOptionalNestedMessage) {
+ if (other.optionalNestedMessage_ != null) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage();
}
OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage);
}
- if (other.HasOptionalForeignMessage) {
- if (!HasOptionalForeignMessage) {
+ if (other.optionalForeignMessage_ != null) {
+ if (optionalForeignMessage_ == null) {
OptionalForeignMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
OptionalForeignMessage.MergeFrom(other.OptionalForeignMessage);
}
- if (other.HasOptionalImportMessage) {
- if (!HasOptionalImportMessage) {
+ if (other.optionalImportMessage_ != null) {
+ if (optionalImportMessage_ == null) {
OptionalImportMessage = new global::Google.Protobuf.TestProtos.Proto2.ImportMessage();
}
OptionalImportMessage.MergeFrom(other.OptionalImportMessage);
@@ -3384,14 +3322,14 @@
if (other.HasOptionalCord) {
OptionalCord = other.OptionalCord;
}
- if (other.HasOptionalPublicImportMessage) {
- if (!HasOptionalPublicImportMessage) {
+ if (other.optionalPublicImportMessage_ != null) {
+ if (optionalPublicImportMessage_ == null) {
OptionalPublicImportMessage = new global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage();
}
OptionalPublicImportMessage.MergeFrom(other.OptionalPublicImportMessage);
}
- if (other.HasOptionalLazyMessage) {
- if (!HasOptionalLazyMessage) {
+ if (other.optionalLazyMessage_ != null) {
+ if (optionalLazyMessage_ == null) {
OptionalLazyMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage();
}
OptionalLazyMessage.MergeFrom(other.OptionalLazyMessage);
@@ -3504,11 +3442,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
OptionalInt32 = input.ReadInt32();
@@ -3578,21 +3521,21 @@
break;
}
case 146: {
- if (!HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage();
}
input.ReadMessage(OptionalNestedMessage);
break;
}
case 154: {
- if (!HasOptionalForeignMessage) {
+ if (optionalForeignMessage_ == null) {
OptionalForeignMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
input.ReadMessage(OptionalForeignMessage);
break;
}
case 162: {
- if (!HasOptionalImportMessage) {
+ if (optionalImportMessage_ == null) {
OptionalImportMessage = new global::Google.Protobuf.TestProtos.Proto2.ImportMessage();
}
input.ReadMessage(OptionalImportMessage);
@@ -3619,14 +3562,14 @@
break;
}
case 210: {
- if (!HasOptionalPublicImportMessage) {
+ if (optionalPublicImportMessage_ == null) {
OptionalPublicImportMessage = new global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage();
}
input.ReadMessage(OptionalPublicImportMessage);
break;
}
case 218: {
- if (!HasOptionalLazyMessage) {
+ if (optionalLazyMessage_ == null) {
OptionalLazyMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage();
}
input.ReadMessage(OptionalLazyMessage);
@@ -3634,118 +3577,118 @@
}
case 250:
case 248: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
case 258:
case 256: {
- repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec);
+ repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec);
break;
}
case 266:
case 264: {
- repeatedUint32_.AddEntriesFrom(input, _repeated_repeatedUint32_codec);
+ repeatedUint32_.AddEntriesFrom(ref input, _repeated_repeatedUint32_codec);
break;
}
case 274:
case 272: {
- repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec);
+ repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec);
break;
}
case 282:
case 280: {
- repeatedSint32_.AddEntriesFrom(input, _repeated_repeatedSint32_codec);
+ repeatedSint32_.AddEntriesFrom(ref input, _repeated_repeatedSint32_codec);
break;
}
case 290:
case 288: {
- repeatedSint64_.AddEntriesFrom(input, _repeated_repeatedSint64_codec);
+ repeatedSint64_.AddEntriesFrom(ref input, _repeated_repeatedSint64_codec);
break;
}
case 298:
case 301: {
- repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec);
+ repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec);
break;
}
case 306:
case 305: {
- repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec);
+ repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec);
break;
}
case 314:
case 317: {
- repeatedSfixed32_.AddEntriesFrom(input, _repeated_repeatedSfixed32_codec);
+ repeatedSfixed32_.AddEntriesFrom(ref input, _repeated_repeatedSfixed32_codec);
break;
}
case 322:
case 321: {
- repeatedSfixed64_.AddEntriesFrom(input, _repeated_repeatedSfixed64_codec);
+ repeatedSfixed64_.AddEntriesFrom(ref input, _repeated_repeatedSfixed64_codec);
break;
}
case 330:
case 333: {
- repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec);
+ repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec);
break;
}
case 338:
case 337: {
- repeatedDouble_.AddEntriesFrom(input, _repeated_repeatedDouble_codec);
+ repeatedDouble_.AddEntriesFrom(ref input, _repeated_repeatedDouble_codec);
break;
}
case 346:
case 344: {
- repeatedBool_.AddEntriesFrom(input, _repeated_repeatedBool_codec);
+ repeatedBool_.AddEntriesFrom(ref input, _repeated_repeatedBool_codec);
break;
}
case 354: {
- repeatedString_.AddEntriesFrom(input, _repeated_repeatedString_codec);
+ repeatedString_.AddEntriesFrom(ref input, _repeated_repeatedString_codec);
break;
}
case 362: {
- repeatedBytes_.AddEntriesFrom(input, _repeated_repeatedBytes_codec);
+ repeatedBytes_.AddEntriesFrom(ref input, _repeated_repeatedBytes_codec);
break;
}
case 371: {
- repeatedGroup_.AddEntriesFrom(input, _repeated_repeatedGroup_codec);
+ repeatedGroup_.AddEntriesFrom(ref input, _repeated_repeatedGroup_codec);
break;
}
case 386: {
- repeatedNestedMessage_.AddEntriesFrom(input, _repeated_repeatedNestedMessage_codec);
+ repeatedNestedMessage_.AddEntriesFrom(ref input, _repeated_repeatedNestedMessage_codec);
break;
}
case 394: {
- repeatedForeignMessage_.AddEntriesFrom(input, _repeated_repeatedForeignMessage_codec);
+ repeatedForeignMessage_.AddEntriesFrom(ref input, _repeated_repeatedForeignMessage_codec);
break;
}
case 402: {
- repeatedImportMessage_.AddEntriesFrom(input, _repeated_repeatedImportMessage_codec);
+ repeatedImportMessage_.AddEntriesFrom(ref input, _repeated_repeatedImportMessage_codec);
break;
}
case 410:
case 408: {
- repeatedNestedEnum_.AddEntriesFrom(input, _repeated_repeatedNestedEnum_codec);
+ repeatedNestedEnum_.AddEntriesFrom(ref input, _repeated_repeatedNestedEnum_codec);
break;
}
case 418:
case 416: {
- repeatedForeignEnum_.AddEntriesFrom(input, _repeated_repeatedForeignEnum_codec);
+ repeatedForeignEnum_.AddEntriesFrom(ref input, _repeated_repeatedForeignEnum_codec);
break;
}
case 426:
case 424: {
- repeatedImportEnum_.AddEntriesFrom(input, _repeated_repeatedImportEnum_codec);
+ repeatedImportEnum_.AddEntriesFrom(ref input, _repeated_repeatedImportEnum_codec);
break;
}
case 434: {
- repeatedStringPiece_.AddEntriesFrom(input, _repeated_repeatedStringPiece_codec);
+ repeatedStringPiece_.AddEntriesFrom(ref input, _repeated_repeatedStringPiece_codec);
break;
}
case 442: {
- repeatedCord_.AddEntriesFrom(input, _repeated_repeatedCord_codec);
+ repeatedCord_.AddEntriesFrom(ref input, _repeated_repeatedCord_codec);
break;
}
case 458: {
- repeatedLazyMessage_.AddEntriesFrom(input, _repeated_repeatedLazyMessage_codec);
+ repeatedLazyMessage_.AddEntriesFrom(ref input, _repeated_repeatedLazyMessage_codec);
break;
}
case 488: {
@@ -3834,7 +3777,7 @@
}
case 898: {
global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage();
- if (HasOneofNestedMessage) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) {
subBuilder.MergeFrom(OneofNestedMessage);
}
input.ReadMessage(subBuilder);
@@ -3867,7 +3810,7 @@
[pbr::OriginalName("NEG")] Neg = -1,
}
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4000,11 +3943,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Bb = input.ReadInt32();
@@ -4016,7 +3964,7 @@
}
- public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup> {
+ public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<OptionalGroup> _parser = new pb::MessageParser<OptionalGroup>(() => new OptionalGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4144,13 +4092,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 132:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 136: {
A = input.ReadInt32();
@@ -4162,7 +4115,7 @@
}
- public sealed partial class RepeatedGroup : pb::IMessage<RepeatedGroup> {
+ public sealed partial class RepeatedGroup : pb::IMessage<RepeatedGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<RepeatedGroup> _parser = new pb::MessageParser<RepeatedGroup>(() => new RepeatedGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4290,13 +4243,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 372:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 376: {
A = input.ReadInt32();
@@ -4314,9 +4272,9 @@
}
/// <summary>
- /// This proto includes a recusively nested message.
+ /// This proto includes a recursively nested message.
/// </summary>
- public sealed partial class NestedTestAllTypes : pb::IMessage<NestedTestAllTypes> {
+ public sealed partial class NestedTestAllTypes : pb::IMessage<NestedTestAllTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedTestAllTypes> _parser = new pb::MessageParser<NestedTestAllTypes>(() => new NestedTestAllTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4341,8 +4299,8 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public NestedTestAllTypes(NestedTestAllTypes other) : this() {
- child_ = other.HasChild ? other.child_.Clone() : null;
- payload_ = other.HasPayload ? other.payload_.Clone() : null;
+ child_ = other.child_ != null ? other.child_.Clone() : null;
+ payload_ = other.payload_ != null ? other.payload_.Clone() : null;
repeatedChild_ = other.repeatedChild_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -4362,16 +4320,6 @@
child_ = value;
}
}
- /// <summary>Gets whether the child field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasChild {
- get { return child_ != null; }
- }
- /// <summary>Clears the value of the child field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearChild() {
- child_ = null;
- }
/// <summary>Field number for the "payload" field.</summary>
public const int PayloadFieldNumber = 2;
@@ -4383,16 +4331,6 @@
payload_ = value;
}
}
- /// <summary>Gets whether the payload field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasPayload {
- get { return payload_ != null; }
- }
- /// <summary>Clears the value of the payload field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearPayload() {
- payload_ = null;
- }
/// <summary>Field number for the "repeated_child" field.</summary>
public const int RepeatedChildFieldNumber = 3;
@@ -4426,8 +4364,8 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasChild) hash ^= Child.GetHashCode();
- if (HasPayload) hash ^= Payload.GetHashCode();
+ if (child_ != null) hash ^= Child.GetHashCode();
+ if (payload_ != null) hash ^= Payload.GetHashCode();
hash ^= repeatedChild_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -4442,11 +4380,11 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasChild) {
+ if (child_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Child);
}
- if (HasPayload) {
+ if (payload_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Payload);
}
@@ -4459,10 +4397,10 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasChild) {
+ if (child_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Child);
}
- if (HasPayload) {
+ if (payload_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
size += repeatedChild_.CalculateSize(_repeated_repeatedChild_codec);
@@ -4477,14 +4415,14 @@
if (other == null) {
return;
}
- if (other.HasChild) {
- if (!HasChild) {
+ if (other.child_ != null) {
+ if (child_ == null) {
Child = new global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes();
}
Child.MergeFrom(other.Child);
}
- if (other.HasPayload) {
- if (!HasPayload) {
+ if (other.payload_ != null) {
+ if (payload_ == null) {
Payload = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
Payload.MergeFrom(other.Payload);
@@ -4495,28 +4433,33 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasChild) {
+ if (child_ == null) {
Child = new global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes();
}
input.ReadMessage(Child);
break;
}
case 18: {
- if (!HasPayload) {
+ if (payload_ == null) {
Payload = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(Payload);
break;
}
case 26: {
- repeatedChild_.AddEntriesFrom(input, _repeated_repeatedChild_codec);
+ repeatedChild_.AddEntriesFrom(ref input, _repeated_repeatedChild_codec);
break;
}
}
@@ -4525,7 +4468,7 @@
}
- public sealed partial class TestDeprecatedFields : pb::IMessage<TestDeprecatedFields> {
+ public sealed partial class TestDeprecatedFields : pb::IMessage<TestDeprecatedFields>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestDeprecatedFields> _parser = new pb::MessageParser<TestDeprecatedFields>(() => new TestDeprecatedFields());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -4723,11 +4666,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
DeprecatedInt32 = input.ReadInt32();
@@ -4744,7 +4692,7 @@
}
[global::System.ObsoleteAttribute]
- public sealed partial class TestDeprecatedMessage : pb::IMessage<TestDeprecatedMessage> {
+ public sealed partial class TestDeprecatedMessage : pb::IMessage<TestDeprecatedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestDeprecatedMessage> _parser = new pb::MessageParser<TestDeprecatedMessage>(() => new TestDeprecatedMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4833,11 +4781,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -4849,7 +4802,7 @@
/// Define these after TestAllTypes to make sure the compiler can handle
/// that.
/// </summary>
- public sealed partial class ForeignMessage : pb::IMessage<ForeignMessage> {
+ public sealed partial class ForeignMessage : pb::IMessage<ForeignMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<ForeignMessage> _parser = new pb::MessageParser<ForeignMessage>(() => new ForeignMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -5014,11 +4967,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
C = input.ReadInt32();
@@ -5034,7 +4992,7 @@
}
- public sealed partial class TestReservedFields : pb::IMessage<TestReservedFields> {
+ public sealed partial class TestReservedFields : pb::IMessage<TestReservedFields>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestReservedFields> _parser = new pb::MessageParser<TestReservedFields>(() => new TestReservedFields());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5123,11 +5081,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -5135,7 +5098,7 @@
}
- public sealed partial class TestAllExtensions : pb::IExtendableMessage<TestAllExtensions> {
+ public sealed partial class TestAllExtensions : pb::IExtendableMessage<TestAllExtensions>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestAllExtensions> _parser = new pb::MessageParser<TestAllExtensions>(() => new TestAllExtensions());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestAllExtensions> _extensions;
@@ -5240,12 +5203,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
}
@@ -5276,7 +5244,7 @@
}
- public sealed partial class OptionalGroup_extension : pb::IMessage<OptionalGroup_extension> {
+ public sealed partial class OptionalGroup_extension : pb::IMessage<OptionalGroup_extension>, pb::IBufferMessage {
private static readonly pb::MessageParser<OptionalGroup_extension> _parser = new pb::MessageParser<OptionalGroup_extension>(() => new OptionalGroup_extension());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -5404,13 +5372,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 132:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 136: {
A = input.ReadInt32();
@@ -5422,7 +5395,7 @@
}
- public sealed partial class RepeatedGroup_extension : pb::IMessage<RepeatedGroup_extension> {
+ public sealed partial class RepeatedGroup_extension : pb::IMessage<RepeatedGroup_extension>, pb::IBufferMessage {
private static readonly pb::MessageParser<RepeatedGroup_extension> _parser = new pb::MessageParser<RepeatedGroup_extension>(() => new RepeatedGroup_extension());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -5550,13 +5523,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 372:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 376: {
A = input.ReadInt32();
@@ -5568,7 +5546,7 @@
}
- public sealed partial class TestGroup : pb::IMessage<TestGroup> {
+ public sealed partial class TestGroup : pb::IMessage<TestGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestGroup> _parser = new pb::MessageParser<TestGroup>(() => new TestGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -5734,11 +5712,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 131: {
if (!HasOptionalGroup) {
@@ -5759,7 +5742,7 @@
/// <summary>Container for nested types declared in the TestGroup message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup> {
+ public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<OptionalGroup> _parser = new pb::MessageParser<OptionalGroup>(() => new OptionalGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -5887,13 +5870,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 132:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 136: {
A = input.ReadInt32();
@@ -5910,7 +5898,7 @@
}
- public sealed partial class TestGroupExtension : pb::IExtendableMessage<TestGroupExtension> {
+ public sealed partial class TestGroupExtension : pb::IExtendableMessage<TestGroupExtension>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestGroupExtension> _parser = new pb::MessageParser<TestGroupExtension>(() => new TestGroupExtension());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestGroupExtension> _extensions;
@@ -6015,12 +6003,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
}
@@ -6051,7 +6044,7 @@
}
- public sealed partial class TestNestedExtension : pb::IMessage<TestNestedExtension> {
+ public sealed partial class TestNestedExtension : pb::IMessage<TestNestedExtension>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestNestedExtension> _parser = new pb::MessageParser<TestNestedExtension>(() => new TestNestedExtension());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6140,11 +6133,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -6154,7 +6152,7 @@
/// <summary>Container for nested types declared in the TestNestedExtension message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class OptionalGroup_extension : pb::IMessage<OptionalGroup_extension> {
+ public sealed partial class OptionalGroup_extension : pb::IMessage<OptionalGroup_extension>, pb::IBufferMessage {
private static readonly pb::MessageParser<OptionalGroup_extension> _parser = new pb::MessageParser<OptionalGroup_extension>(() => new OptionalGroup_extension());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -6282,13 +6280,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 132:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 136: {
A = input.ReadInt32();
@@ -6335,7 +6338,7 @@
/// required filed because the code output is basically identical to
/// optional fields for all types.
/// </summary>
- public sealed partial class TestRequired : pb::IMessage<TestRequired> {
+ public sealed partial class TestRequired : pb::IMessage<TestRequired>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRequired> _parser = new pb::MessageParser<TestRequired>(() => new TestRequired());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -7653,11 +7656,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
@@ -7808,7 +7816,7 @@
}
- public sealed partial class TestRequiredForeign : pb::IMessage<TestRequiredForeign> {
+ public sealed partial class TestRequiredForeign : pb::IMessage<TestRequiredForeign>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRequiredForeign> _parser = new pb::MessageParser<TestRequiredForeign>(() => new TestRequiredForeign());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -7835,7 +7843,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestRequiredForeign(TestRequiredForeign other) : this() {
_hasBits0 = other._hasBits0;
- optionalMessage_ = other.HasOptionalMessage ? other.optionalMessage_.Clone() : null;
+ optionalMessage_ = other.optionalMessage_ != null ? other.optionalMessage_.Clone() : null;
repeatedMessage_ = other.repeatedMessage_.Clone();
dummy_ = other.dummy_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -7856,16 +7864,6 @@
optionalMessage_ = value;
}
}
- /// <summary>Gets whether the optional_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalMessage {
- get { return optionalMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalMessage() {
- optionalMessage_ = null;
- }
/// <summary>Field number for the "repeated_message" field.</summary>
public const int RepeatedMessageFieldNumber = 2;
@@ -7923,7 +7921,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasOptionalMessage) hash ^= OptionalMessage.GetHashCode();
+ if (optionalMessage_ != null) hash ^= OptionalMessage.GetHashCode();
hash ^= repeatedMessage_.GetHashCode();
if (HasDummy) hash ^= Dummy.GetHashCode();
if (_unknownFields != null) {
@@ -7939,7 +7937,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasOptionalMessage) {
+ if (optionalMessage_ != null) {
output.WriteRawTag(10);
output.WriteMessage(OptionalMessage);
}
@@ -7956,7 +7954,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasOptionalMessage) {
+ if (optionalMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalMessage);
}
size += repeatedMessage_.CalculateSize(_repeated_repeatedMessage_codec);
@@ -7974,8 +7972,8 @@
if (other == null) {
return;
}
- if (other.HasOptionalMessage) {
- if (!HasOptionalMessage) {
+ if (other.optionalMessage_ != null) {
+ if (optionalMessage_ == null) {
OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired();
}
OptionalMessage.MergeFrom(other.OptionalMessage);
@@ -7989,21 +7987,26 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasOptionalMessage) {
+ if (optionalMessage_ == null) {
OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired();
}
input.ReadMessage(OptionalMessage);
break;
}
case 18: {
- repeatedMessage_.AddEntriesFrom(input, _repeated_repeatedMessage_codec);
+ repeatedMessage_.AddEntriesFrom(ref input, _repeated_repeatedMessage_codec);
break;
}
case 24: {
@@ -8016,7 +8019,7 @@
}
- public sealed partial class TestRequiredMessage : pb::IMessage<TestRequiredMessage> {
+ public sealed partial class TestRequiredMessage : pb::IMessage<TestRequiredMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRequiredMessage> _parser = new pb::MessageParser<TestRequiredMessage>(() => new TestRequiredMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -8041,9 +8044,9 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestRequiredMessage(TestRequiredMessage other) : this() {
- optionalMessage_ = other.HasOptionalMessage ? other.optionalMessage_.Clone() : null;
+ optionalMessage_ = other.optionalMessage_ != null ? other.optionalMessage_.Clone() : null;
repeatedMessage_ = other.repeatedMessage_.Clone();
- requiredMessage_ = other.HasRequiredMessage ? other.requiredMessage_.Clone() : null;
+ requiredMessage_ = other.requiredMessage_ != null ? other.requiredMessage_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -8062,16 +8065,6 @@
optionalMessage_ = value;
}
}
- /// <summary>Gets whether the optional_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalMessage {
- get { return optionalMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalMessage() {
- optionalMessage_ = null;
- }
/// <summary>Field number for the "repeated_message" field.</summary>
public const int RepeatedMessageFieldNumber = 2;
@@ -8093,16 +8086,6 @@
requiredMessage_ = value;
}
}
- /// <summary>Gets whether the required_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasRequiredMessage {
- get { return requiredMessage_ != null; }
- }
- /// <summary>Clears the value of the required_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearRequiredMessage() {
- requiredMessage_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -8126,9 +8109,9 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasOptionalMessage) hash ^= OptionalMessage.GetHashCode();
+ if (optionalMessage_ != null) hash ^= OptionalMessage.GetHashCode();
hash ^= repeatedMessage_.GetHashCode();
- if (HasRequiredMessage) hash ^= RequiredMessage.GetHashCode();
+ if (requiredMessage_ != null) hash ^= RequiredMessage.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -8142,12 +8125,12 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasOptionalMessage) {
+ if (optionalMessage_ != null) {
output.WriteRawTag(10);
output.WriteMessage(OptionalMessage);
}
repeatedMessage_.WriteTo(output, _repeated_repeatedMessage_codec);
- if (HasRequiredMessage) {
+ if (requiredMessage_ != null) {
output.WriteRawTag(26);
output.WriteMessage(RequiredMessage);
}
@@ -8159,11 +8142,11 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasOptionalMessage) {
+ if (optionalMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalMessage);
}
size += repeatedMessage_.CalculateSize(_repeated_repeatedMessage_codec);
- if (HasRequiredMessage) {
+ if (requiredMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RequiredMessage);
}
if (_unknownFields != null) {
@@ -8177,15 +8160,15 @@
if (other == null) {
return;
}
- if (other.HasOptionalMessage) {
- if (!HasOptionalMessage) {
+ if (other.optionalMessage_ != null) {
+ if (optionalMessage_ == null) {
OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired();
}
OptionalMessage.MergeFrom(other.OptionalMessage);
}
repeatedMessage_.Add(other.repeatedMessage_);
- if (other.HasRequiredMessage) {
- if (!HasRequiredMessage) {
+ if (other.requiredMessage_ != null) {
+ if (requiredMessage_ == null) {
RequiredMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired();
}
RequiredMessage.MergeFrom(other.RequiredMessage);
@@ -8195,25 +8178,30 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasOptionalMessage) {
+ if (optionalMessage_ == null) {
OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired();
}
input.ReadMessage(OptionalMessage);
break;
}
case 18: {
- repeatedMessage_.AddEntriesFrom(input, _repeated_repeatedMessage_codec);
+ repeatedMessage_.AddEntriesFrom(ref input, _repeated_repeatedMessage_codec);
break;
}
case 26: {
- if (!HasRequiredMessage) {
+ if (requiredMessage_ == null) {
RequiredMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired();
}
input.ReadMessage(RequiredMessage);
@@ -8228,7 +8216,7 @@
/// <summary>
/// Test that we can use NestedMessage from outside TestAllTypes.
/// </summary>
- public sealed partial class TestForeignNested : pb::IMessage<TestForeignNested> {
+ public sealed partial class TestForeignNested : pb::IMessage<TestForeignNested>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestForeignNested> _parser = new pb::MessageParser<TestForeignNested>(() => new TestForeignNested());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -8253,7 +8241,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestForeignNested(TestForeignNested other) : this() {
- foreignNested_ = other.HasForeignNested ? other.foreignNested_.Clone() : null;
+ foreignNested_ = other.foreignNested_ != null ? other.foreignNested_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -8272,16 +8260,6 @@
foreignNested_ = value;
}
}
- /// <summary>Gets whether the foreign_nested field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasForeignNested {
- get { return foreignNested_ != null; }
- }
- /// <summary>Clears the value of the foreign_nested field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearForeignNested() {
- foreignNested_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -8303,7 +8281,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasForeignNested) hash ^= ForeignNested.GetHashCode();
+ if (foreignNested_ != null) hash ^= ForeignNested.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -8317,7 +8295,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasForeignNested) {
+ if (foreignNested_ != null) {
output.WriteRawTag(10);
output.WriteMessage(ForeignNested);
}
@@ -8329,7 +8307,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasForeignNested) {
+ if (foreignNested_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ForeignNested);
}
if (_unknownFields != null) {
@@ -8343,8 +8321,8 @@
if (other == null) {
return;
}
- if (other.HasForeignNested) {
- if (!HasForeignNested) {
+ if (other.foreignNested_ != null) {
+ if (foreignNested_ == null) {
ForeignNested = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage();
}
ForeignNested.MergeFrom(other.ForeignNested);
@@ -8354,14 +8332,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasForeignNested) {
+ if (foreignNested_ == null) {
ForeignNested = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage();
}
input.ReadMessage(ForeignNested);
@@ -8376,7 +8359,7 @@
/// <summary>
/// TestEmptyMessage is used to test unknown field support.
/// </summary>
- public sealed partial class TestEmptyMessage : pb::IMessage<TestEmptyMessage> {
+ public sealed partial class TestEmptyMessage : pb::IMessage<TestEmptyMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestEmptyMessage> _parser = new pb::MessageParser<TestEmptyMessage>(() => new TestEmptyMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -8465,11 +8448,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -8481,7 +8469,7 @@
/// Like above, but declare all field numbers as potential extensions. No
/// actual extensions should ever be defined for this type.
/// </summary>
- public sealed partial class TestEmptyMessageWithExtensions : pb::IExtendableMessage<TestEmptyMessageWithExtensions> {
+ public sealed partial class TestEmptyMessageWithExtensions : pb::IExtendableMessage<TestEmptyMessageWithExtensions>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestEmptyMessageWithExtensions> _parser = new pb::MessageParser<TestEmptyMessageWithExtensions>(() => new TestEmptyMessageWithExtensions());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestEmptyMessageWithExtensions> _extensions;
@@ -8586,12 +8574,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
}
@@ -8622,7 +8615,7 @@
}
- public sealed partial class TestMultipleExtensionRanges : pb::IExtendableMessage<TestMultipleExtensionRanges> {
+ public sealed partial class TestMultipleExtensionRanges : pb::IExtendableMessage<TestMultipleExtensionRanges>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMultipleExtensionRanges> _parser = new pb::MessageParser<TestMultipleExtensionRanges>(() => new TestMultipleExtensionRanges());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestMultipleExtensionRanges> _extensions;
@@ -8727,12 +8720,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
}
@@ -8766,7 +8764,7 @@
/// <summary>
/// Test that really large tag numbers don't break anything.
/// </summary>
- public sealed partial class TestReallyLargeTagNumber : pb::IMessage<TestReallyLargeTagNumber> {
+ public sealed partial class TestReallyLargeTagNumber : pb::IMessage<TestReallyLargeTagNumber>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestReallyLargeTagNumber> _parser = new pb::MessageParser<TestReallyLargeTagNumber>(() => new TestReallyLargeTagNumber());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -8935,11 +8933,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
@@ -8955,7 +8958,7 @@
}
- public sealed partial class TestRecursiveMessage : pb::IMessage<TestRecursiveMessage> {
+ public sealed partial class TestRecursiveMessage : pb::IMessage<TestRecursiveMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRecursiveMessage> _parser = new pb::MessageParser<TestRecursiveMessage>(() => new TestRecursiveMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -8982,7 +8985,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestRecursiveMessage(TestRecursiveMessage other) : this() {
_hasBits0 = other._hasBits0;
- a_ = other.HasA ? other.a_.Clone() : null;
+ a_ = other.a_ != null ? other.a_.Clone() : null;
i_ = other.i_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -9002,16 +9005,6 @@
a_ = value;
}
}
- /// <summary>Gets whether the a field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasA {
- get { return a_ != null; }
- }
- /// <summary>Clears the value of the a field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearA() {
- a_ = null;
- }
/// <summary>Field number for the "i" field.</summary>
public const int IFieldNumber = 2;
@@ -9058,7 +9051,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasA) hash ^= A.GetHashCode();
+ if (a_ != null) hash ^= A.GetHashCode();
if (HasI) hash ^= I.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -9073,7 +9066,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasA) {
+ if (a_ != null) {
output.WriteRawTag(10);
output.WriteMessage(A);
}
@@ -9089,7 +9082,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasA) {
+ if (a_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(A);
}
if (HasI) {
@@ -9106,8 +9099,8 @@
if (other == null) {
return;
}
- if (other.HasA) {
- if (!HasA) {
+ if (other.a_ != null) {
+ if (a_ == null) {
A = new global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage();
}
A.MergeFrom(other.A);
@@ -9120,14 +9113,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasA) {
+ if (a_ == null) {
A = new global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage();
}
input.ReadMessage(A);
@@ -9146,7 +9144,7 @@
/// <summary>
/// Test that mutual recursion works.
/// </summary>
- public sealed partial class TestMutualRecursionA : pb::IMessage<TestMutualRecursionA> {
+ public sealed partial class TestMutualRecursionA : pb::IMessage<TestMutualRecursionA>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMutualRecursionA> _parser = new pb::MessageParser<TestMutualRecursionA>(() => new TestMutualRecursionA());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -9171,7 +9169,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestMutualRecursionA(TestMutualRecursionA other) : this() {
- bb_ = other.HasBb ? other.bb_.Clone() : null;
+ bb_ = other.bb_ != null ? other.bb_.Clone() : null;
subGroup_ = other.HasSubGroup ? other.subGroup_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -9191,16 +9189,6 @@
bb_ = value;
}
}
- /// <summary>Gets whether the bb field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasBb {
- get { return bb_ != null; }
- }
- /// <summary>Clears the value of the bb field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearBb() {
- bb_ = null;
- }
/// <summary>Field number for the "subgroup" field.</summary>
public const int SubGroupFieldNumber = 2;
@@ -9244,7 +9232,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasBb) hash ^= Bb.GetHashCode();
+ if (bb_ != null) hash ^= Bb.GetHashCode();
if (HasSubGroup) hash ^= SubGroup.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -9259,7 +9247,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasBb) {
+ if (bb_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Bb);
}
@@ -9276,7 +9264,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasBb) {
+ if (bb_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Bb);
}
if (HasSubGroup) {
@@ -9293,8 +9281,8 @@
if (other == null) {
return;
}
- if (other.HasBb) {
- if (!HasBb) {
+ if (other.bb_ != null) {
+ if (bb_ == null) {
Bb = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB();
}
Bb.MergeFrom(other.Bb);
@@ -9310,14 +9298,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasBb) {
+ if (bb_ == null) {
Bb = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB();
}
input.ReadMessage(Bb);
@@ -9338,7 +9331,7 @@
/// <summary>Container for nested types declared in the TestMutualRecursionA message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class SubMessage : pb::IMessage<SubMessage> {
+ public sealed partial class SubMessage : pb::IMessage<SubMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<SubMessage> _parser = new pb::MessageParser<SubMessage>(() => new SubMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -9363,7 +9356,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SubMessage(SubMessage other) : this() {
- b_ = other.HasB ? other.b_.Clone() : null;
+ b_ = other.b_ != null ? other.b_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -9382,16 +9375,6 @@
b_ = value;
}
}
- /// <summary>Gets whether the b field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasB {
- get { return b_ != null; }
- }
- /// <summary>Clears the value of the b field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearB() {
- b_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -9413,7 +9396,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasB) hash ^= B.GetHashCode();
+ if (b_ != null) hash ^= B.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -9427,7 +9410,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasB) {
+ if (b_ != null) {
output.WriteRawTag(10);
output.WriteMessage(B);
}
@@ -9439,7 +9422,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasB) {
+ if (b_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(B);
}
if (_unknownFields != null) {
@@ -9453,8 +9436,8 @@
if (other == null) {
return;
}
- if (other.HasB) {
- if (!HasB) {
+ if (other.b_ != null) {
+ if (b_ == null) {
B = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB();
}
B.MergeFrom(other.B);
@@ -9464,14 +9447,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasB) {
+ if (b_ == null) {
B = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB();
}
input.ReadMessage(B);
@@ -9483,7 +9471,7 @@
}
- public sealed partial class SubGroup : pb::IMessage<SubGroup> {
+ public sealed partial class SubGroup : pb::IMessage<SubGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<SubGroup> _parser = new pb::MessageParser<SubGroup>(() => new SubGroup());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -9508,8 +9496,8 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SubGroup(SubGroup other) : this() {
- subMessage_ = other.HasSubMessage ? other.subMessage_.Clone() : null;
- notInThisScc_ = other.HasNotInThisScc ? other.notInThisScc_.Clone() : null;
+ subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null;
+ notInThisScc_ = other.notInThisScc_ != null ? other.notInThisScc_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -9531,16 +9519,6 @@
subMessage_ = value;
}
}
- /// <summary>Gets whether the sub_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasSubMessage {
- get { return subMessage_ != null; }
- }
- /// <summary>Clears the value of the sub_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearSubMessage() {
- subMessage_ = null;
- }
/// <summary>Field number for the "not_in_this_scc" field.</summary>
public const int NotInThisSccFieldNumber = 4;
@@ -9552,16 +9530,6 @@
notInThisScc_ = value;
}
}
- /// <summary>Gets whether the not_in_this_scc field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasNotInThisScc {
- get { return notInThisScc_ != null; }
- }
- /// <summary>Clears the value of the not_in_this_scc field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearNotInThisScc() {
- notInThisScc_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -9584,8 +9552,8 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasSubMessage) hash ^= SubMessage.GetHashCode();
- if (HasNotInThisScc) hash ^= NotInThisScc.GetHashCode();
+ if (subMessage_ != null) hash ^= SubMessage.GetHashCode();
+ if (notInThisScc_ != null) hash ^= NotInThisScc.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -9599,11 +9567,11 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasSubMessage) {
+ if (subMessage_ != null) {
output.WriteRawTag(26);
output.WriteMessage(SubMessage);
}
- if (HasNotInThisScc) {
+ if (notInThisScc_ != null) {
output.WriteRawTag(34);
output.WriteMessage(NotInThisScc);
}
@@ -9615,10 +9583,10 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasSubMessage) {
+ if (subMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage);
}
- if (HasNotInThisScc) {
+ if (notInThisScc_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(NotInThisScc);
}
if (_unknownFields != null) {
@@ -9632,14 +9600,14 @@
if (other == null) {
return;
}
- if (other.HasSubMessage) {
- if (!HasSubMessage) {
+ if (other.subMessage_ != null) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage();
}
SubMessage.MergeFrom(other.SubMessage);
}
- if (other.HasNotInThisScc) {
- if (!HasNotInThisScc) {
+ if (other.notInThisScc_ != null) {
+ if (notInThisScc_ == null) {
NotInThisScc = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
NotInThisScc.MergeFrom(other.NotInThisScc);
@@ -9649,23 +9617,28 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 20:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 26: {
- if (!HasSubMessage) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage();
}
input.ReadMessage(SubMessage);
break;
}
case 34: {
- if (!HasNotInThisScc) {
+ if (notInThisScc_ == null) {
NotInThisScc = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(NotInThisScc);
@@ -9682,7 +9655,7 @@
}
- public sealed partial class TestMutualRecursionB : pb::IMessage<TestMutualRecursionB> {
+ public sealed partial class TestMutualRecursionB : pb::IMessage<TestMutualRecursionB>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMutualRecursionB> _parser = new pb::MessageParser<TestMutualRecursionB>(() => new TestMutualRecursionB());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -9709,7 +9682,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestMutualRecursionB(TestMutualRecursionB other) : this() {
_hasBits0 = other._hasBits0;
- a_ = other.HasA ? other.a_.Clone() : null;
+ a_ = other.a_ != null ? other.a_.Clone() : null;
optionalInt32_ = other.optionalInt32_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -9729,16 +9702,6 @@
a_ = value;
}
}
- /// <summary>Gets whether the a field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasA {
- get { return a_ != null; }
- }
- /// <summary>Clears the value of the a field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearA() {
- a_ = null;
- }
/// <summary>Field number for the "optional_int32" field.</summary>
public const int OptionalInt32FieldNumber = 2;
@@ -9785,7 +9748,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasA) hash ^= A.GetHashCode();
+ if (a_ != null) hash ^= A.GetHashCode();
if (HasOptionalInt32) hash ^= OptionalInt32.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -9800,7 +9763,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasA) {
+ if (a_ != null) {
output.WriteRawTag(10);
output.WriteMessage(A);
}
@@ -9816,7 +9779,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasA) {
+ if (a_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(A);
}
if (HasOptionalInt32) {
@@ -9833,8 +9796,8 @@
if (other == null) {
return;
}
- if (other.HasA) {
- if (!HasA) {
+ if (other.a_ != null) {
+ if (a_ == null) {
A = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA();
}
A.MergeFrom(other.A);
@@ -9847,14 +9810,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasA) {
+ if (a_ == null) {
A = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA();
}
input.ReadMessage(A);
@@ -9870,7 +9838,7 @@
}
- public sealed partial class TestIsInitialized : pb::IMessage<TestIsInitialized> {
+ public sealed partial class TestIsInitialized : pb::IMessage<TestIsInitialized>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestIsInitialized> _parser = new pb::MessageParser<TestIsInitialized>(() => new TestIsInitialized());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -9895,7 +9863,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestIsInitialized(TestIsInitialized other) : this() {
- subMessage_ = other.HasSubMessage ? other.subMessage_.Clone() : null;
+ subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -9914,16 +9882,6 @@
subMessage_ = value;
}
}
- /// <summary>Gets whether the sub_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasSubMessage {
- get { return subMessage_ != null; }
- }
- /// <summary>Clears the value of the sub_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearSubMessage() {
- subMessage_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -9945,7 +9903,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasSubMessage) hash ^= SubMessage.GetHashCode();
+ if (subMessage_ != null) hash ^= SubMessage.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -9959,7 +9917,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasSubMessage) {
+ if (subMessage_ != null) {
output.WriteRawTag(10);
output.WriteMessage(SubMessage);
}
@@ -9971,7 +9929,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasSubMessage) {
+ if (subMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage);
}
if (_unknownFields != null) {
@@ -9985,8 +9943,8 @@
if (other == null) {
return;
}
- if (other.HasSubMessage) {
- if (!HasSubMessage) {
+ if (other.subMessage_ != null) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage();
}
SubMessage.MergeFrom(other.SubMessage);
@@ -9996,14 +9954,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasSubMessage) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage();
}
input.ReadMessage(SubMessage);
@@ -10017,7 +9980,7 @@
/// <summary>Container for nested types declared in the TestIsInitialized message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class SubMessage : pb::IMessage<SubMessage> {
+ public sealed partial class SubMessage : pb::IMessage<SubMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<SubMessage> _parser = new pb::MessageParser<SubMessage>(() => new SubMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -10144,11 +10107,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 11: {
if (!HasSubGroup) {
@@ -10165,7 +10133,7 @@
/// <summary>Container for nested types declared in the SubMessage message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class SubGroup : pb::IMessage<SubGroup> {
+ public sealed partial class SubGroup : pb::IMessage<SubGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<SubGroup> _parser = new pb::MessageParser<SubGroup>(() => new SubGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -10293,13 +10261,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 12:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 16: {
I = input.ReadInt32();
@@ -10327,7 +10300,7 @@
/// to compile with proto1, this will emit an error; so we only include it
/// in protobuf_unittest_proto.
/// </summary>
- public sealed partial class TestDupFieldNumber : pb::IMessage<TestDupFieldNumber> {
+ public sealed partial class TestDupFieldNumber : pb::IMessage<TestDupFieldNumber>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestDupFieldNumber> _parser = new pb::MessageParser<TestDupFieldNumber>(() => new TestDupFieldNumber());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -10534,11 +10507,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
@@ -10566,7 +10544,7 @@
/// <summary>Container for nested types declared in the TestDupFieldNumber message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class Foo : pb::IMessage<Foo> {
+ public sealed partial class Foo : pb::IMessage<Foo>, pb::IBufferMessage {
private static readonly pb::MessageParser<Foo> _parser = new pb::MessageParser<Foo>(() => new Foo());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -10694,13 +10672,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 20:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
@@ -10712,7 +10695,7 @@
}
- public sealed partial class Bar : pb::IMessage<Bar> {
+ public sealed partial class Bar : pb::IMessage<Bar>, pb::IBufferMessage {
private static readonly pb::MessageParser<Bar> _parser = new pb::MessageParser<Bar>(() => new Bar());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -10840,13 +10823,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 28:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
@@ -10866,7 +10854,7 @@
/// <summary>
/// Additional messages for testing lazy fields.
/// </summary>
- public sealed partial class TestEagerMessage : pb::IMessage<TestEagerMessage> {
+ public sealed partial class TestEagerMessage : pb::IMessage<TestEagerMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestEagerMessage> _parser = new pb::MessageParser<TestEagerMessage>(() => new TestEagerMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -10891,7 +10879,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestEagerMessage(TestEagerMessage other) : this() {
- subMessage_ = other.HasSubMessage ? other.subMessage_.Clone() : null;
+ subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -10910,16 +10898,6 @@
subMessage_ = value;
}
}
- /// <summary>Gets whether the sub_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasSubMessage {
- get { return subMessage_ != null; }
- }
- /// <summary>Clears the value of the sub_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearSubMessage() {
- subMessage_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -10941,7 +10919,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasSubMessage) hash ^= SubMessage.GetHashCode();
+ if (subMessage_ != null) hash ^= SubMessage.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -10955,7 +10933,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasSubMessage) {
+ if (subMessage_ != null) {
output.WriteRawTag(10);
output.WriteMessage(SubMessage);
}
@@ -10967,7 +10945,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasSubMessage) {
+ if (subMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage);
}
if (_unknownFields != null) {
@@ -10981,8 +10959,8 @@
if (other == null) {
return;
}
- if (other.HasSubMessage) {
- if (!HasSubMessage) {
+ if (other.subMessage_ != null) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
SubMessage.MergeFrom(other.SubMessage);
@@ -10992,14 +10970,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasSubMessage) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(SubMessage);
@@ -11011,7 +10994,7 @@
}
- public sealed partial class TestLazyMessage : pb::IMessage<TestLazyMessage> {
+ public sealed partial class TestLazyMessage : pb::IMessage<TestLazyMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestLazyMessage> _parser = new pb::MessageParser<TestLazyMessage>(() => new TestLazyMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -11036,7 +11019,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestLazyMessage(TestLazyMessage other) : this() {
- subMessage_ = other.HasSubMessage ? other.subMessage_.Clone() : null;
+ subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -11055,16 +11038,6 @@
subMessage_ = value;
}
}
- /// <summary>Gets whether the sub_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasSubMessage {
- get { return subMessage_ != null; }
- }
- /// <summary>Clears the value of the sub_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearSubMessage() {
- subMessage_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -11086,7 +11059,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasSubMessage) hash ^= SubMessage.GetHashCode();
+ if (subMessage_ != null) hash ^= SubMessage.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -11100,7 +11073,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasSubMessage) {
+ if (subMessage_ != null) {
output.WriteRawTag(10);
output.WriteMessage(SubMessage);
}
@@ -11112,7 +11085,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasSubMessage) {
+ if (subMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage);
}
if (_unknownFields != null) {
@@ -11126,8 +11099,8 @@
if (other == null) {
return;
}
- if (other.HasSubMessage) {
- if (!HasSubMessage) {
+ if (other.subMessage_ != null) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
SubMessage.MergeFrom(other.SubMessage);
@@ -11137,14 +11110,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasSubMessage) {
+ if (subMessage_ == null) {
SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(SubMessage);
@@ -11159,7 +11137,7 @@
/// <summary>
/// Needed for a Python test.
/// </summary>
- public sealed partial class TestNestedMessageHasBits : pb::IMessage<TestNestedMessageHasBits> {
+ public sealed partial class TestNestedMessageHasBits : pb::IMessage<TestNestedMessageHasBits>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestNestedMessageHasBits> _parser = new pb::MessageParser<TestNestedMessageHasBits>(() => new TestNestedMessageHasBits());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -11184,7 +11162,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestNestedMessageHasBits(TestNestedMessageHasBits other) : this() {
- optionalNestedMessage_ = other.HasOptionalNestedMessage ? other.optionalNestedMessage_.Clone() : null;
+ optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -11203,16 +11181,6 @@
optionalNestedMessage_ = value;
}
}
- /// <summary>Gets whether the optional_nested_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalNestedMessage {
- get { return optionalNestedMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_nested_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalNestedMessage() {
- optionalNestedMessage_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -11234,7 +11202,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasOptionalNestedMessage) hash ^= OptionalNestedMessage.GetHashCode();
+ if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -11248,7 +11216,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
output.WriteRawTag(10);
output.WriteMessage(OptionalNestedMessage);
}
@@ -11260,7 +11228,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage);
}
if (_unknownFields != null) {
@@ -11274,8 +11242,8 @@
if (other == null) {
return;
}
- if (other.HasOptionalNestedMessage) {
- if (!HasOptionalNestedMessage) {
+ if (other.optionalNestedMessage_ != null) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage();
}
OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage);
@@ -11285,14 +11253,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- if (!HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage();
}
input.ReadMessage(OptionalNestedMessage);
@@ -11306,7 +11279,7 @@
/// <summary>Container for nested types declared in the TestNestedMessageHasBits message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -11427,19 +11400,24 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10:
case 8: {
- nestedmessageRepeatedInt32_.AddEntriesFrom(input, _repeated_nestedmessageRepeatedInt32_codec);
+ nestedmessageRepeatedInt32_.AddEntriesFrom(ref input, _repeated_nestedmessageRepeatedInt32_codec);
break;
}
case 18: {
- nestedmessageRepeatedForeignmessage_.AddEntriesFrom(input, _repeated_nestedmessageRepeatedForeignmessage_codec);
+ nestedmessageRepeatedForeignmessage_.AddEntriesFrom(ref input, _repeated_nestedmessageRepeatedForeignmessage_codec);
break;
}
}
@@ -11457,7 +11435,7 @@
/// Test message with CamelCase field names. This violates Protocol Buffer
/// standard style.
/// </summary>
- public sealed partial class TestCamelCaseFieldNames : pb::IMessage<TestCamelCaseFieldNames> {
+ public sealed partial class TestCamelCaseFieldNames : pb::IMessage<TestCamelCaseFieldNames>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestCamelCaseFieldNames> _parser = new pb::MessageParser<TestCamelCaseFieldNames>(() => new TestCamelCaseFieldNames());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -11487,7 +11465,7 @@
primitiveField_ = other.primitiveField_;
stringField_ = other.stringField_;
enumField_ = other.enumField_;
- messageField_ = other.HasMessageField ? other.messageField_.Clone() : null;
+ messageField_ = other.messageField_ != null ? other.messageField_.Clone() : null;
stringPieceField_ = other.stringPieceField_;
cordField_ = other.cordField_;
repeatedPrimitiveField_ = other.repeatedPrimitiveField_.Clone();
@@ -11585,16 +11563,6 @@
messageField_ = value;
}
}
- /// <summary>Gets whether the MessageField field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasMessageField {
- get { return messageField_ != null; }
- }
- /// <summary>Clears the value of the MessageField field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearMessageField() {
- messageField_ = null;
- }
/// <summary>Field number for the "StringPieceField" field.</summary>
public const int StringPieceFieldFieldNumber = 5;
@@ -11736,7 +11704,7 @@
if (HasPrimitiveField) hash ^= PrimitiveField.GetHashCode();
if (HasStringField) hash ^= StringField.GetHashCode();
if (HasEnumField) hash ^= EnumField.GetHashCode();
- if (HasMessageField) hash ^= MessageField.GetHashCode();
+ if (messageField_ != null) hash ^= MessageField.GetHashCode();
if (HasStringPieceField) hash ^= StringPieceField.GetHashCode();
if (HasCordField) hash ^= CordField.GetHashCode();
hash ^= repeatedPrimitiveField_.GetHashCode();
@@ -11770,7 +11738,7 @@
output.WriteRawTag(24);
output.WriteEnum((int) EnumField);
}
- if (HasMessageField) {
+ if (messageField_ != null) {
output.WriteRawTag(34);
output.WriteMessage(MessageField);
}
@@ -11805,7 +11773,7 @@
if (HasEnumField) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumField);
}
- if (HasMessageField) {
+ if (messageField_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageField);
}
if (HasStringPieceField) {
@@ -11840,8 +11808,8 @@
if (other.HasEnumField) {
EnumField = other.EnumField;
}
- if (other.HasMessageField) {
- if (!HasMessageField) {
+ if (other.messageField_ != null) {
+ if (messageField_ == null) {
MessageField = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
MessageField.MergeFrom(other.MessageField);
@@ -11863,11 +11831,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
PrimitiveField = input.ReadInt32();
@@ -11882,7 +11855,7 @@
break;
}
case 34: {
- if (!HasMessageField) {
+ if (messageField_ == null) {
MessageField = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
input.ReadMessage(MessageField);
@@ -11898,28 +11871,28 @@
}
case 58:
case 56: {
- repeatedPrimitiveField_.AddEntriesFrom(input, _repeated_repeatedPrimitiveField_codec);
+ repeatedPrimitiveField_.AddEntriesFrom(ref input, _repeated_repeatedPrimitiveField_codec);
break;
}
case 66: {
- repeatedStringField_.AddEntriesFrom(input, _repeated_repeatedStringField_codec);
+ repeatedStringField_.AddEntriesFrom(ref input, _repeated_repeatedStringField_codec);
break;
}
case 74:
case 72: {
- repeatedEnumField_.AddEntriesFrom(input, _repeated_repeatedEnumField_codec);
+ repeatedEnumField_.AddEntriesFrom(ref input, _repeated_repeatedEnumField_codec);
break;
}
case 82: {
- repeatedMessageField_.AddEntriesFrom(input, _repeated_repeatedMessageField_codec);
+ repeatedMessageField_.AddEntriesFrom(ref input, _repeated_repeatedMessageField_codec);
break;
}
case 90: {
- repeatedStringPieceField_.AddEntriesFrom(input, _repeated_repeatedStringPieceField_codec);
+ repeatedStringPieceField_.AddEntriesFrom(ref input, _repeated_repeatedStringPieceField_codec);
break;
}
case 98: {
- repeatedCordField_.AddEntriesFrom(input, _repeated_repeatedCordField_codec);
+ repeatedCordField_.AddEntriesFrom(ref input, _repeated_repeatedCordField_codec);
break;
}
}
@@ -11932,7 +11905,7 @@
/// We list fields out of order, to ensure that we're using field number and not
/// field index to determine serialization order.
/// </summary>
- public sealed partial class TestFieldOrderings : pb::IExtendableMessage<TestFieldOrderings> {
+ public sealed partial class TestFieldOrderings : pb::IExtendableMessage<TestFieldOrderings>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestFieldOrderings> _parser = new pb::MessageParser<TestFieldOrderings>(() => new TestFieldOrderings());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestFieldOrderings> _extensions;
@@ -11964,7 +11937,7 @@
myString_ = other.myString_;
myInt_ = other.myInt_;
myFloat_ = other.myFloat_;
- optionalNestedMessage_ = other.HasOptionalNestedMessage ? other.optionalNestedMessage_.Clone() : null;
+ optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
_extensions = pb::ExtensionSet.Clone(other._extensions);
}
@@ -12055,16 +12028,6 @@
optionalNestedMessage_ = value;
}
}
- /// <summary>Gets whether the optional_nested_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalNestedMessage {
- get { return optionalNestedMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_nested_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalNestedMessage() {
- optionalNestedMessage_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -12095,7 +12058,7 @@
if (HasMyString) hash ^= MyString.GetHashCode();
if (HasMyInt) hash ^= MyInt.GetHashCode();
if (HasMyFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(MyFloat);
- if (HasOptionalNestedMessage) hash ^= OptionalNestedMessage.GetHashCode();
+ if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode();
if (_extensions != null) {
hash ^= _extensions.GetHashCode();
}
@@ -12124,7 +12087,7 @@
output.WriteRawTag(173, 6);
output.WriteFloat(MyFloat);
}
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
output.WriteRawTag(194, 12);
output.WriteMessage(OptionalNestedMessage);
}
@@ -12148,7 +12111,7 @@
if (HasMyFloat) {
size += 2 + 4;
}
- if (HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage);
}
if (_extensions != null) {
@@ -12174,8 +12137,8 @@
if (other.HasMyFloat) {
MyFloat = other.MyFloat;
}
- if (other.HasOptionalNestedMessage) {
- if (!HasOptionalNestedMessage) {
+ if (other.optionalNestedMessage_ != null) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage();
}
OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage);
@@ -12186,12 +12149,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 8: {
@@ -12207,7 +12175,7 @@
break;
}
case 1602: {
- if (!HasOptionalNestedMessage) {
+ if (optionalNestedMessage_ == null) {
OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage();
}
input.ReadMessage(OptionalNestedMessage);
@@ -12243,7 +12211,7 @@
/// <summary>Container for nested types declared in the TestFieldOrderings message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -12413,11 +12381,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Bb = input.ReadInt32();
@@ -12438,7 +12411,7 @@
}
- public sealed partial class TestExtensionOrderings1 : pb::IMessage<TestExtensionOrderings1> {
+ public sealed partial class TestExtensionOrderings1 : pb::IMessage<TestExtensionOrderings1>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestExtensionOrderings1> _parser = new pb::MessageParser<TestExtensionOrderings1>(() => new TestExtensionOrderings1());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -12563,11 +12536,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
MyString = input.ReadString();
@@ -12588,7 +12566,7 @@
}
- public sealed partial class TestExtensionOrderings2 : pb::IMessage<TestExtensionOrderings2> {
+ public sealed partial class TestExtensionOrderings2 : pb::IMessage<TestExtensionOrderings2>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestExtensionOrderings2> _parser = new pb::MessageParser<TestExtensionOrderings2>(() => new TestExtensionOrderings2());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -12713,11 +12691,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
MyString = input.ReadString();
@@ -12731,7 +12714,7 @@
/// <summary>Container for nested types declared in the TestExtensionOrderings2 message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class TestExtensionOrderings3 : pb::IMessage<TestExtensionOrderings3> {
+ public sealed partial class TestExtensionOrderings3 : pb::IMessage<TestExtensionOrderings3>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestExtensionOrderings3> _parser = new pb::MessageParser<TestExtensionOrderings3>(() => new TestExtensionOrderings3());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -12856,11 +12839,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
MyString = input.ReadString();
@@ -12895,7 +12883,7 @@
}
- public sealed partial class TestExtremeDefaultValues : pb::IMessage<TestExtremeDefaultValues> {
+ public sealed partial class TestExtremeDefaultValues : pb::IMessage<TestExtremeDefaultValues>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestExtremeDefaultValues> _parser = new pb::MessageParser<TestExtremeDefaultValues>(() => new TestExtremeDefaultValues());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -14001,11 +13989,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
EscapedBytes = input.ReadBytes();
@@ -14121,7 +14114,7 @@
}
- public sealed partial class SparseEnumMessage : pb::IMessage<SparseEnumMessage> {
+ public sealed partial class SparseEnumMessage : pb::IMessage<SparseEnumMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<SparseEnumMessage> _parser = new pb::MessageParser<SparseEnumMessage>(() => new SparseEnumMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -14249,11 +14242,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
SparseEnum = (global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum) input.ReadEnum();
@@ -14268,7 +14266,7 @@
/// <summary>
/// Test String and Bytes: string is for valid UTF-8 strings
/// </summary>
- public sealed partial class OneString : pb::IMessage<OneString> {
+ public sealed partial class OneString : pb::IMessage<OneString>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneString> _parser = new pb::MessageParser<OneString>(() => new OneString());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -14393,11 +14391,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Data = input.ReadString();
@@ -14409,7 +14412,7 @@
}
- public sealed partial class MoreString : pb::IMessage<MoreString> {
+ public sealed partial class MoreString : pb::IMessage<MoreString>, pb::IBufferMessage {
private static readonly pb::MessageParser<MoreString> _parser = new pb::MessageParser<MoreString>(() => new MoreString());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -14514,14 +14517,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- data_.AddEntriesFrom(input, _repeated_data_codec);
+ data_.AddEntriesFrom(ref input, _repeated_data_codec);
break;
}
}
@@ -14530,7 +14538,7 @@
}
- public sealed partial class OneBytes : pb::IMessage<OneBytes> {
+ public sealed partial class OneBytes : pb::IMessage<OneBytes>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneBytes> _parser = new pb::MessageParser<OneBytes>(() => new OneBytes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -14655,11 +14663,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Data = input.ReadBytes();
@@ -14671,7 +14684,7 @@
}
- public sealed partial class MoreBytes : pb::IMessage<MoreBytes> {
+ public sealed partial class MoreBytes : pb::IMessage<MoreBytes>, pb::IBufferMessage {
private static readonly pb::MessageParser<MoreBytes> _parser = new pb::MessageParser<MoreBytes>(() => new MoreBytes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -14776,14 +14789,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- data_.AddEntriesFrom(input, _repeated_data_codec);
+ data_.AddEntriesFrom(ref input, _repeated_data_codec);
break;
}
}
@@ -14795,7 +14813,7 @@
/// <summary>
/// Test int32, uint32, int64, uint64, and bool are all compatible
/// </summary>
- public sealed partial class Int32Message : pb::IMessage<Int32Message> {
+ public sealed partial class Int32Message : pb::IMessage<Int32Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Int32Message> _parser = new pb::MessageParser<Int32Message>(() => new Int32Message());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -14923,11 +14941,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadInt32();
@@ -14939,7 +14962,7 @@
}
- public sealed partial class Uint32Message : pb::IMessage<Uint32Message> {
+ public sealed partial class Uint32Message : pb::IMessage<Uint32Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Uint32Message> _parser = new pb::MessageParser<Uint32Message>(() => new Uint32Message());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -15067,11 +15090,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadUInt32();
@@ -15083,7 +15111,7 @@
}
- public sealed partial class Int64Message : pb::IMessage<Int64Message> {
+ public sealed partial class Int64Message : pb::IMessage<Int64Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Int64Message> _parser = new pb::MessageParser<Int64Message>(() => new Int64Message());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -15211,11 +15239,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadInt64();
@@ -15227,7 +15260,7 @@
}
- public sealed partial class Uint64Message : pb::IMessage<Uint64Message> {
+ public sealed partial class Uint64Message : pb::IMessage<Uint64Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Uint64Message> _parser = new pb::MessageParser<Uint64Message>(() => new Uint64Message());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -15355,11 +15388,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadUInt64();
@@ -15371,7 +15409,7 @@
}
- public sealed partial class BoolMessage : pb::IMessage<BoolMessage> {
+ public sealed partial class BoolMessage : pb::IMessage<BoolMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<BoolMessage> _parser = new pb::MessageParser<BoolMessage>(() => new BoolMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -15499,11 +15537,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadBool();
@@ -15518,10 +15561,9 @@
/// <summary>
/// Test oneofs.
/// </summary>
- public sealed partial class TestOneof : pb::IMessage<TestOneof> {
+ public sealed partial class TestOneof : pb::IMessage<TestOneof>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestOneof> _parser = new pb::MessageParser<TestOneof>(() => new TestOneof());
private pb::UnknownFieldSet _unknownFields;
- private int _hasBits0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TestOneof> Parser { get { return _parser; } }
@@ -15544,7 +15586,6 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestOneof(TestOneof other) : this() {
- _hasBits0 = other._hasBits0;
switch (other.FooCase) {
case FooOneofCase.FooInt:
FooInt = other.FooInt;
@@ -15618,24 +15659,12 @@
public const int FooMessageFieldNumber = 3;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes FooMessage {
- get { return HasFooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes) foo_ : null; }
+ get { return fooCase_ == FooOneofCase.FooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes) foo_ : null; }
set {
foo_ = value;
fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooMessage;
}
}
- /// <summary>Gets whether the "foo_message" field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasFooMessage {
- get { return fooCase_ == FooOneofCase.FooMessage; }
- }
- /// <summary> Clears the value of the oneof if it's currently set to "foo_message" </summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearFooMessage() {
- if (HasFooMessage) {
- ClearFoo();
- }
- }
/// <summary>Field number for the "foogroup" field.</summary>
public const int FooGroupFieldNumber = 4;
@@ -15707,7 +15736,7 @@
int hash = 1;
if (HasFooInt) hash ^= FooInt.GetHashCode();
if (HasFooString) hash ^= FooString.GetHashCode();
- if (HasFooMessage) hash ^= FooMessage.GetHashCode();
+ if (fooCase_ == FooOneofCase.FooMessage) hash ^= FooMessage.GetHashCode();
if (HasFooGroup) hash ^= FooGroup.GetHashCode();
hash ^= (int) fooCase_;
if (_unknownFields != null) {
@@ -15731,7 +15760,7 @@
output.WriteRawTag(18);
output.WriteString(FooString);
}
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
output.WriteRawTag(26);
output.WriteMessage(FooMessage);
}
@@ -15754,7 +15783,7 @@
if (HasFooString) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString);
}
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage);
}
if (HasFooGroup) {
@@ -15797,11 +15826,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
FooInt = input.ReadInt32();
@@ -15813,7 +15847,7 @@
}
case 26: {
global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
subBuilder.MergeFrom(FooMessage);
}
input.ReadMessage(subBuilder);
@@ -15837,7 +15871,7 @@
/// <summary>Container for nested types declared in the TestOneof message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class FooGroup : pb::IMessage<FooGroup> {
+ public sealed partial class FooGroup : pb::IMessage<FooGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooGroup> _parser = new pb::MessageParser<FooGroup>(() => new FooGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -16001,13 +16035,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 36:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 40: {
A = input.ReadInt32();
@@ -16028,7 +16067,7 @@
}
- public sealed partial class TestOneofBackwardsCompatible : pb::IMessage<TestOneofBackwardsCompatible> {
+ public sealed partial class TestOneofBackwardsCompatible : pb::IMessage<TestOneofBackwardsCompatible>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestOneofBackwardsCompatible> _parser = new pb::MessageParser<TestOneofBackwardsCompatible>(() => new TestOneofBackwardsCompatible());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -16057,7 +16096,7 @@
_hasBits0 = other._hasBits0;
fooInt_ = other.fooInt_;
fooString_ = other.fooString_;
- fooMessage_ = other.HasFooMessage ? other.fooMessage_.Clone() : null;
+ fooMessage_ = other.fooMessage_ != null ? other.fooMessage_.Clone() : null;
fooGroup_ = other.HasFooGroup ? other.fooGroup_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -16124,16 +16163,6 @@
fooMessage_ = value;
}
}
- /// <summary>Gets whether the foo_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasFooMessage {
- get { return fooMessage_ != null; }
- }
- /// <summary>Clears the value of the foo_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearFooMessage() {
- fooMessage_ = null;
- }
/// <summary>Field number for the "foogroup" field.</summary>
public const int FooGroupFieldNumber = 4;
@@ -16181,7 +16210,7 @@
int hash = 1;
if (HasFooInt) hash ^= FooInt.GetHashCode();
if (HasFooString) hash ^= FooString.GetHashCode();
- if (HasFooMessage) hash ^= FooMessage.GetHashCode();
+ if (fooMessage_ != null) hash ^= FooMessage.GetHashCode();
if (HasFooGroup) hash ^= FooGroup.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -16204,7 +16233,7 @@
output.WriteRawTag(18);
output.WriteString(FooString);
}
- if (HasFooMessage) {
+ if (fooMessage_ != null) {
output.WriteRawTag(26);
output.WriteMessage(FooMessage);
}
@@ -16227,7 +16256,7 @@
if (HasFooString) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString);
}
- if (HasFooMessage) {
+ if (fooMessage_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage);
}
if (HasFooGroup) {
@@ -16250,8 +16279,8 @@
if (other.HasFooString) {
FooString = other.FooString;
}
- if (other.HasFooMessage) {
- if (!HasFooMessage) {
+ if (other.fooMessage_ != null) {
+ if (fooMessage_ == null) {
FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
FooMessage.MergeFrom(other.FooMessage);
@@ -16267,11 +16296,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
FooInt = input.ReadInt32();
@@ -16282,7 +16316,7 @@
break;
}
case 26: {
- if (!HasFooMessage) {
+ if (fooMessage_ == null) {
FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(FooMessage);
@@ -16303,7 +16337,7 @@
/// <summary>Container for nested types declared in the TestOneofBackwardsCompatible message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class FooGroup : pb::IMessage<FooGroup> {
+ public sealed partial class FooGroup : pb::IMessage<FooGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooGroup> _parser = new pb::MessageParser<FooGroup>(() => new FooGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -16467,13 +16501,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 36:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 40: {
A = input.ReadInt32();
@@ -16494,7 +16533,7 @@
}
- public sealed partial class TestOneof2 : pb::IMessage<TestOneof2> {
+ public sealed partial class TestOneof2 : pb::IMessage<TestOneof2>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestOneof2> _parser = new pb::MessageParser<TestOneof2>(() => new TestOneof2());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -16724,24 +16763,12 @@
public const int FooMessageFieldNumber = 7;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage FooMessage {
- get { return HasFooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage) foo_ : null; }
+ get { return fooCase_ == FooOneofCase.FooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage) foo_ : null; }
set {
foo_ = value;
fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooMessage;
}
}
- /// <summary>Gets whether the "foo_message" field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasFooMessage {
- get { return fooCase_ == FooOneofCase.FooMessage; }
- }
- /// <summary> Clears the value of the oneof if it's currently set to "foo_message" </summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearFooMessage() {
- if (HasFooMessage) {
- ClearFoo();
- }
- }
/// <summary>Field number for the "foogroup" field.</summary>
public const int FooGroupFieldNumber = 8;
@@ -16770,24 +16797,12 @@
public const int FooLazyMessageFieldNumber = 11;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage FooLazyMessage {
- get { return HasFooLazyMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage) foo_ : null; }
+ get { return fooCase_ == FooOneofCase.FooLazyMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage) foo_ : null; }
set {
foo_ = value;
fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooLazyMessage;
}
}
- /// <summary>Gets whether the "foo_lazy_message" field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasFooLazyMessage {
- get { return fooCase_ == FooOneofCase.FooLazyMessage; }
- }
- /// <summary> Clears the value of the oneof if it's currently set to "foo_lazy_message" </summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearFooLazyMessage() {
- if (HasFooLazyMessage) {
- ClearFoo();
- }
- }
/// <summary>Field number for the "bar_int" field.</summary>
public const int BarIntFieldNumber = 12;
@@ -16934,21 +16949,21 @@
private int bazInt_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int BazInt {
- get { if ((_hasBits0 & 16) != 0) { return bazInt_; } else { return BazIntDefaultValue; } }
+ get { if ((_hasBits0 & 1) != 0) { return bazInt_; } else { return BazIntDefaultValue; } }
set {
- _hasBits0 |= 16;
+ _hasBits0 |= 1;
bazInt_ = value;
}
}
/// <summary>Gets whether the "baz_int" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool HasBazInt {
- get { return (_hasBits0 & 16) != 0; }
+ get { return (_hasBits0 & 1) != 0; }
}
/// <summary>Clears the value of the "baz_int" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearBazInt() {
- _hasBits0 &= ~16;
+ _hasBits0 &= ~1;
}
/// <summary>Field number for the "baz_string" field.</summary>
@@ -17067,9 +17082,9 @@
if (HasFooStringPiece) hash ^= FooStringPiece.GetHashCode();
if (HasFooBytes) hash ^= FooBytes.GetHashCode();
if (HasFooEnum) hash ^= FooEnum.GetHashCode();
- if (HasFooMessage) hash ^= FooMessage.GetHashCode();
+ if (fooCase_ == FooOneofCase.FooMessage) hash ^= FooMessage.GetHashCode();
if (HasFooGroup) hash ^= FooGroup.GetHashCode();
- if (HasFooLazyMessage) hash ^= FooLazyMessage.GetHashCode();
+ if (fooCase_ == FooOneofCase.FooLazyMessage) hash ^= FooLazyMessage.GetHashCode();
if (HasBarInt) hash ^= BarInt.GetHashCode();
if (HasBarString) hash ^= BarString.GetHashCode();
if (HasBarCord) hash ^= BarCord.GetHashCode();
@@ -17117,7 +17132,7 @@
output.WriteRawTag(48);
output.WriteEnum((int) FooEnum);
}
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
output.WriteRawTag(58);
output.WriteMessage(FooMessage);
}
@@ -17126,7 +17141,7 @@
output.WriteGroup(FooGroup);
output.WriteRawTag(68);
}
- if (HasFooLazyMessage) {
+ if (fooCase_ == FooOneofCase.FooLazyMessage) {
output.WriteRawTag(90);
output.WriteMessage(FooLazyMessage);
}
@@ -17188,13 +17203,13 @@
if (HasFooEnum) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) FooEnum);
}
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage);
}
if (HasFooGroup) {
size += 2 + pb::CodedOutputStream.ComputeGroupSize(FooGroup);
}
- if (HasFooLazyMessage) {
+ if (fooCase_ == FooOneofCase.FooLazyMessage) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooLazyMessage);
}
if (HasBarInt) {
@@ -17303,11 +17318,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
FooInt = input.ReadInt32();
@@ -17336,7 +17356,7 @@
}
case 58: {
global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage();
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
subBuilder.MergeFrom(FooMessage);
}
input.ReadMessage(subBuilder);
@@ -17354,7 +17374,7 @@
}
case 90: {
global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage();
- if (HasFooLazyMessage) {
+ if (fooCase_ == FooOneofCase.FooLazyMessage) {
subBuilder.MergeFrom(FooLazyMessage);
}
input.ReadMessage(subBuilder);
@@ -17408,7 +17428,7 @@
[pbr::OriginalName("BAZ")] Baz = 3,
}
- public sealed partial class FooGroup : pb::IMessage<FooGroup> {
+ public sealed partial class FooGroup : pb::IMessage<FooGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooGroup> _parser = new pb::MessageParser<FooGroup>(() => new FooGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -17572,13 +17592,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 68:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 72: {
A = input.ReadInt32();
@@ -17594,7 +17619,7 @@
}
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -17738,11 +17763,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
QuxInt = input.ReadInt64();
@@ -17750,7 +17780,7 @@
}
case 18:
case 16: {
- corgeInt_.AddEntriesFrom(input, _repeated_corgeInt_codec);
+ corgeInt_.AddEntriesFrom(ref input, _repeated_corgeInt_codec);
break;
}
}
@@ -17764,10 +17794,9 @@
}
- public sealed partial class TestRequiredOneof : pb::IMessage<TestRequiredOneof> {
+ public sealed partial class TestRequiredOneof : pb::IMessage<TestRequiredOneof>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRequiredOneof> _parser = new pb::MessageParser<TestRequiredOneof>(() => new TestRequiredOneof());
private pb::UnknownFieldSet _unknownFields;
- private int _hasBits0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TestRequiredOneof> Parser { get { return _parser; } }
@@ -17790,7 +17819,6 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestRequiredOneof(TestRequiredOneof other) : this() {
- _hasBits0 = other._hasBits0;
switch (other.FooCase) {
case FooOneofCase.FooInt:
FooInt = other.FooInt;
@@ -17861,24 +17889,12 @@
public const int FooMessageFieldNumber = 3;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage FooMessage {
- get { return HasFooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage) foo_ : null; }
+ get { return fooCase_ == FooOneofCase.FooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage) foo_ : null; }
set {
foo_ = value;
fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooMessage;
}
}
- /// <summary>Gets whether the "foo_message" field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasFooMessage {
- get { return fooCase_ == FooOneofCase.FooMessage; }
- }
- /// <summary> Clears the value of the oneof if it's currently set to "foo_message" </summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearFooMessage() {
- if (HasFooMessage) {
- ClearFoo();
- }
- }
private object foo_;
/// <summary>Enum of possible cases for the "foo" oneof.</summary>
@@ -17925,7 +17941,7 @@
int hash = 1;
if (HasFooInt) hash ^= FooInt.GetHashCode();
if (HasFooString) hash ^= FooString.GetHashCode();
- if (HasFooMessage) hash ^= FooMessage.GetHashCode();
+ if (fooCase_ == FooOneofCase.FooMessage) hash ^= FooMessage.GetHashCode();
hash ^= (int) fooCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -17948,7 +17964,7 @@
output.WriteRawTag(18);
output.WriteString(FooString);
}
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
output.WriteRawTag(26);
output.WriteMessage(FooMessage);
}
@@ -17966,7 +17982,7 @@
if (HasFooString) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString);
}
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage);
}
if (_unknownFields != null) {
@@ -18000,11 +18016,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
FooInt = input.ReadInt32();
@@ -18016,7 +18037,7 @@
}
case 26: {
global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage();
- if (HasFooMessage) {
+ if (fooCase_ == FooOneofCase.FooMessage) {
subBuilder.MergeFrom(FooMessage);
}
input.ReadMessage(subBuilder);
@@ -18031,7 +18052,7 @@
/// <summary>Container for nested types declared in the TestRequiredOneof message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -18159,11 +18180,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 9: {
RequiredDouble = input.ReadDouble();
@@ -18180,7 +18206,7 @@
}
- public sealed partial class TestRequiredMap : pb::IMessage<TestRequiredMap> {
+ public sealed partial class TestRequiredMap : pb::IMessage<TestRequiredMap>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRequiredMap> _parser = new pb::MessageParser<TestRequiredMap>(() => new TestRequiredMap());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -18285,14 +18311,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- foo_.AddEntriesFrom(input, _map_foo_codec);
+ foo_.AddEntriesFrom(ref input, _map_foo_codec);
break;
}
}
@@ -18303,7 +18334,7 @@
/// <summary>Container for nested types declared in the TestRequiredMap message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -18431,11 +18462,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
RequiredInt32 = input.ReadInt32();
@@ -18452,7 +18488,7 @@
}
- public sealed partial class TestPackedTypes : pb::IMessage<TestPackedTypes> {
+ public sealed partial class TestPackedTypes : pb::IMessage<TestPackedTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestPackedTypes> _parser = new pb::MessageParser<TestPackedTypes>(() => new TestPackedTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -18765,80 +18801,85 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 722:
case 720: {
- packedInt32_.AddEntriesFrom(input, _repeated_packedInt32_codec);
+ packedInt32_.AddEntriesFrom(ref input, _repeated_packedInt32_codec);
break;
}
case 730:
case 728: {
- packedInt64_.AddEntriesFrom(input, _repeated_packedInt64_codec);
+ packedInt64_.AddEntriesFrom(ref input, _repeated_packedInt64_codec);
break;
}
case 738:
case 736: {
- packedUint32_.AddEntriesFrom(input, _repeated_packedUint32_codec);
+ packedUint32_.AddEntriesFrom(ref input, _repeated_packedUint32_codec);
break;
}
case 746:
case 744: {
- packedUint64_.AddEntriesFrom(input, _repeated_packedUint64_codec);
+ packedUint64_.AddEntriesFrom(ref input, _repeated_packedUint64_codec);
break;
}
case 754:
case 752: {
- packedSint32_.AddEntriesFrom(input, _repeated_packedSint32_codec);
+ packedSint32_.AddEntriesFrom(ref input, _repeated_packedSint32_codec);
break;
}
case 762:
case 760: {
- packedSint64_.AddEntriesFrom(input, _repeated_packedSint64_codec);
+ packedSint64_.AddEntriesFrom(ref input, _repeated_packedSint64_codec);
break;
}
case 770:
case 773: {
- packedFixed32_.AddEntriesFrom(input, _repeated_packedFixed32_codec);
+ packedFixed32_.AddEntriesFrom(ref input, _repeated_packedFixed32_codec);
break;
}
case 778:
case 777: {
- packedFixed64_.AddEntriesFrom(input, _repeated_packedFixed64_codec);
+ packedFixed64_.AddEntriesFrom(ref input, _repeated_packedFixed64_codec);
break;
}
case 786:
case 789: {
- packedSfixed32_.AddEntriesFrom(input, _repeated_packedSfixed32_codec);
+ packedSfixed32_.AddEntriesFrom(ref input, _repeated_packedSfixed32_codec);
break;
}
case 794:
case 793: {
- packedSfixed64_.AddEntriesFrom(input, _repeated_packedSfixed64_codec);
+ packedSfixed64_.AddEntriesFrom(ref input, _repeated_packedSfixed64_codec);
break;
}
case 802:
case 805: {
- packedFloat_.AddEntriesFrom(input, _repeated_packedFloat_codec);
+ packedFloat_.AddEntriesFrom(ref input, _repeated_packedFloat_codec);
break;
}
case 810:
case 809: {
- packedDouble_.AddEntriesFrom(input, _repeated_packedDouble_codec);
+ packedDouble_.AddEntriesFrom(ref input, _repeated_packedDouble_codec);
break;
}
case 818:
case 816: {
- packedBool_.AddEntriesFrom(input, _repeated_packedBool_codec);
+ packedBool_.AddEntriesFrom(ref input, _repeated_packedBool_codec);
break;
}
case 826:
case 824: {
- packedEnum_.AddEntriesFrom(input, _repeated_packedEnum_codec);
+ packedEnum_.AddEntriesFrom(ref input, _repeated_packedEnum_codec);
break;
}
}
@@ -18851,7 +18892,7 @@
/// A message with the same fields as TestPackedTypes, but without packing. Used
/// to test packed <-> unpacked wire compatibility.
/// </summary>
- public sealed partial class TestUnpackedTypes : pb::IMessage<TestUnpackedTypes> {
+ public sealed partial class TestUnpackedTypes : pb::IMessage<TestUnpackedTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestUnpackedTypes> _parser = new pb::MessageParser<TestUnpackedTypes>(() => new TestUnpackedTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -19164,80 +19205,85 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 722:
case 720: {
- unpackedInt32_.AddEntriesFrom(input, _repeated_unpackedInt32_codec);
+ unpackedInt32_.AddEntriesFrom(ref input, _repeated_unpackedInt32_codec);
break;
}
case 730:
case 728: {
- unpackedInt64_.AddEntriesFrom(input, _repeated_unpackedInt64_codec);
+ unpackedInt64_.AddEntriesFrom(ref input, _repeated_unpackedInt64_codec);
break;
}
case 738:
case 736: {
- unpackedUint32_.AddEntriesFrom(input, _repeated_unpackedUint32_codec);
+ unpackedUint32_.AddEntriesFrom(ref input, _repeated_unpackedUint32_codec);
break;
}
case 746:
case 744: {
- unpackedUint64_.AddEntriesFrom(input, _repeated_unpackedUint64_codec);
+ unpackedUint64_.AddEntriesFrom(ref input, _repeated_unpackedUint64_codec);
break;
}
case 754:
case 752: {
- unpackedSint32_.AddEntriesFrom(input, _repeated_unpackedSint32_codec);
+ unpackedSint32_.AddEntriesFrom(ref input, _repeated_unpackedSint32_codec);
break;
}
case 762:
case 760: {
- unpackedSint64_.AddEntriesFrom(input, _repeated_unpackedSint64_codec);
+ unpackedSint64_.AddEntriesFrom(ref input, _repeated_unpackedSint64_codec);
break;
}
case 770:
case 773: {
- unpackedFixed32_.AddEntriesFrom(input, _repeated_unpackedFixed32_codec);
+ unpackedFixed32_.AddEntriesFrom(ref input, _repeated_unpackedFixed32_codec);
break;
}
case 778:
case 777: {
- unpackedFixed64_.AddEntriesFrom(input, _repeated_unpackedFixed64_codec);
+ unpackedFixed64_.AddEntriesFrom(ref input, _repeated_unpackedFixed64_codec);
break;
}
case 786:
case 789: {
- unpackedSfixed32_.AddEntriesFrom(input, _repeated_unpackedSfixed32_codec);
+ unpackedSfixed32_.AddEntriesFrom(ref input, _repeated_unpackedSfixed32_codec);
break;
}
case 794:
case 793: {
- unpackedSfixed64_.AddEntriesFrom(input, _repeated_unpackedSfixed64_codec);
+ unpackedSfixed64_.AddEntriesFrom(ref input, _repeated_unpackedSfixed64_codec);
break;
}
case 802:
case 805: {
- unpackedFloat_.AddEntriesFrom(input, _repeated_unpackedFloat_codec);
+ unpackedFloat_.AddEntriesFrom(ref input, _repeated_unpackedFloat_codec);
break;
}
case 810:
case 809: {
- unpackedDouble_.AddEntriesFrom(input, _repeated_unpackedDouble_codec);
+ unpackedDouble_.AddEntriesFrom(ref input, _repeated_unpackedDouble_codec);
break;
}
case 818:
case 816: {
- unpackedBool_.AddEntriesFrom(input, _repeated_unpackedBool_codec);
+ unpackedBool_.AddEntriesFrom(ref input, _repeated_unpackedBool_codec);
break;
}
case 826:
case 824: {
- unpackedEnum_.AddEntriesFrom(input, _repeated_unpackedEnum_codec);
+ unpackedEnum_.AddEntriesFrom(ref input, _repeated_unpackedEnum_codec);
break;
}
}
@@ -19246,7 +19292,7 @@
}
- public sealed partial class TestPackedExtensions : pb::IExtendableMessage<TestPackedExtensions> {
+ public sealed partial class TestPackedExtensions : pb::IExtendableMessage<TestPackedExtensions>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestPackedExtensions> _parser = new pb::MessageParser<TestPackedExtensions>(() => new TestPackedExtensions());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestPackedExtensions> _extensions;
@@ -19351,12 +19397,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
}
@@ -19387,7 +19438,7 @@
}
- public sealed partial class TestUnpackedExtensions : pb::IExtendableMessage<TestUnpackedExtensions> {
+ public sealed partial class TestUnpackedExtensions : pb::IExtendableMessage<TestUnpackedExtensions>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestUnpackedExtensions> _parser = new pb::MessageParser<TestUnpackedExtensions>(() => new TestUnpackedExtensions());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestUnpackedExtensions> _extensions;
@@ -19492,12 +19543,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
}
@@ -19533,7 +19589,7 @@
/// a set of extensions to TestAllExtensions dynamically, based on the fields
/// of this message type.
/// </summary>
- public sealed partial class TestDynamicExtensions : pb::IMessage<TestDynamicExtensions> {
+ public sealed partial class TestDynamicExtensions : pb::IMessage<TestDynamicExtensions>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestDynamicExtensions> _parser = new pb::MessageParser<TestDynamicExtensions>(() => new TestDynamicExtensions());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -19563,8 +19619,8 @@
scalarExtension_ = other.scalarExtension_;
enumExtension_ = other.enumExtension_;
dynamicEnumExtension_ = other.dynamicEnumExtension_;
- messageExtension_ = other.HasMessageExtension ? other.messageExtension_.Clone() : null;
- dynamicMessageExtension_ = other.HasDynamicMessageExtension ? other.dynamicMessageExtension_.Clone() : null;
+ messageExtension_ = other.messageExtension_ != null ? other.messageExtension_.Clone() : null;
+ dynamicMessageExtension_ = other.dynamicMessageExtension_ != null ? other.dynamicMessageExtension_.Clone() : null;
repeatedExtension_ = other.repeatedExtension_.Clone();
packedExtension_ = other.packedExtension_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -19657,16 +19713,6 @@
messageExtension_ = value;
}
}
- /// <summary>Gets whether the message_extension field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasMessageExtension {
- get { return messageExtension_ != null; }
- }
- /// <summary>Clears the value of the message_extension field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearMessageExtension() {
- messageExtension_ = null;
- }
/// <summary>Field number for the "dynamic_message_extension" field.</summary>
public const int DynamicMessageExtensionFieldNumber = 2004;
@@ -19678,16 +19724,6 @@
dynamicMessageExtension_ = value;
}
}
- /// <summary>Gets whether the dynamic_message_extension field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasDynamicMessageExtension {
- get { return dynamicMessageExtension_ != null; }
- }
- /// <summary>Clears the value of the dynamic_message_extension field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearDynamicMessageExtension() {
- dynamicMessageExtension_ = null;
- }
/// <summary>Field number for the "repeated_extension" field.</summary>
public const int RepeatedExtensionFieldNumber = 2005;
@@ -19738,8 +19774,8 @@
if (HasScalarExtension) hash ^= ScalarExtension.GetHashCode();
if (HasEnumExtension) hash ^= EnumExtension.GetHashCode();
if (HasDynamicEnumExtension) hash ^= DynamicEnumExtension.GetHashCode();
- if (HasMessageExtension) hash ^= MessageExtension.GetHashCode();
- if (HasDynamicMessageExtension) hash ^= DynamicMessageExtension.GetHashCode();
+ if (messageExtension_ != null) hash ^= MessageExtension.GetHashCode();
+ if (dynamicMessageExtension_ != null) hash ^= DynamicMessageExtension.GetHashCode();
hash ^= repeatedExtension_.GetHashCode();
hash ^= packedExtension_.GetHashCode();
if (_unknownFields != null) {
@@ -19767,11 +19803,11 @@
output.WriteRawTag(144, 125);
output.WriteEnum((int) DynamicEnumExtension);
}
- if (HasMessageExtension) {
+ if (messageExtension_ != null) {
output.WriteRawTag(154, 125);
output.WriteMessage(MessageExtension);
}
- if (HasDynamicMessageExtension) {
+ if (dynamicMessageExtension_ != null) {
output.WriteRawTag(162, 125);
output.WriteMessage(DynamicMessageExtension);
}
@@ -19794,10 +19830,10 @@
if (HasDynamicEnumExtension) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) DynamicEnumExtension);
}
- if (HasMessageExtension) {
+ if (messageExtension_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(MessageExtension);
}
- if (HasDynamicMessageExtension) {
+ if (dynamicMessageExtension_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(DynamicMessageExtension);
}
size += repeatedExtension_.CalculateSize(_repeated_repeatedExtension_codec);
@@ -19822,14 +19858,14 @@
if (other.HasDynamicEnumExtension) {
DynamicEnumExtension = other.DynamicEnumExtension;
}
- if (other.HasMessageExtension) {
- if (!HasMessageExtension) {
+ if (other.messageExtension_ != null) {
+ if (messageExtension_ == null) {
MessageExtension = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
MessageExtension.MergeFrom(other.MessageExtension);
}
- if (other.HasDynamicMessageExtension) {
- if (!HasDynamicMessageExtension) {
+ if (other.dynamicMessageExtension_ != null) {
+ if (dynamicMessageExtension_ == null) {
DynamicMessageExtension = new global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType();
}
DynamicMessageExtension.MergeFrom(other.DynamicMessageExtension);
@@ -19841,11 +19877,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 16005: {
ScalarExtension = input.ReadFixed32();
@@ -19860,26 +19901,26 @@
break;
}
case 16026: {
- if (!HasMessageExtension) {
+ if (messageExtension_ == null) {
MessageExtension = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
input.ReadMessage(MessageExtension);
break;
}
case 16034: {
- if (!HasDynamicMessageExtension) {
+ if (dynamicMessageExtension_ == null) {
DynamicMessageExtension = new global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType();
}
input.ReadMessage(DynamicMessageExtension);
break;
}
case 16042: {
- repeatedExtension_.AddEntriesFrom(input, _repeated_repeatedExtension_codec);
+ repeatedExtension_.AddEntriesFrom(ref input, _repeated_repeatedExtension_codec);
break;
}
case 16050:
case 16048: {
- packedExtension_.AddEntriesFrom(input, _repeated_packedExtension_codec);
+ packedExtension_.AddEntriesFrom(ref input, _repeated_packedExtension_codec);
break;
}
}
@@ -19896,7 +19937,7 @@
[pbr::OriginalName("DYNAMIC_BAZ")] DynamicBaz = 2202,
}
- public sealed partial class DynamicMessageType : pb::IMessage<DynamicMessageType> {
+ public sealed partial class DynamicMessageType : pb::IMessage<DynamicMessageType>, pb::IBufferMessage {
private static readonly pb::MessageParser<DynamicMessageType> _parser = new pb::MessageParser<DynamicMessageType>(() => new DynamicMessageType());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -20024,11 +20065,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 16800: {
DynamicField = input.ReadInt32();
@@ -20045,7 +20091,7 @@
}
- public sealed partial class TestRepeatedScalarDifferentTagSizes : pb::IMessage<TestRepeatedScalarDifferentTagSizes> {
+ public sealed partial class TestRepeatedScalarDifferentTagSizes : pb::IMessage<TestRepeatedScalarDifferentTagSizes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRepeatedScalarDifferentTagSizes> _parser = new pb::MessageParser<TestRepeatedScalarDifferentTagSizes>(() => new TestRepeatedScalarDifferentTagSizes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -20244,40 +20290,45 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 98:
case 101: {
- repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec);
+ repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec);
break;
}
case 106:
case 104: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
case 16370:
case 16369: {
- repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec);
+ repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec);
break;
}
case 16378:
case 16376: {
- repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec);
+ repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec);
break;
}
case 2097138:
case 2097141: {
- repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec);
+ repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec);
break;
}
case 2097146:
case 2097144: {
- repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec);
+ repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec);
break;
}
}
@@ -20290,7 +20341,7 @@
/// Test that if an optional or required message/group field appears multiple
/// times in the input, they need to be merged.
/// </summary>
- public sealed partial class TestParsingMerge : pb::IExtendableMessage<TestParsingMerge> {
+ public sealed partial class TestParsingMerge : pb::IExtendableMessage<TestParsingMerge>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestParsingMerge> _parser = new pb::MessageParser<TestParsingMerge>(() => new TestParsingMerge());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestParsingMerge> _extensions;
@@ -20317,8 +20368,8 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TestParsingMerge(TestParsingMerge other) : this() {
- requiredAllTypes_ = other.HasRequiredAllTypes ? other.requiredAllTypes_.Clone() : null;
- optionalAllTypes_ = other.HasOptionalAllTypes ? other.optionalAllTypes_.Clone() : null;
+ requiredAllTypes_ = other.requiredAllTypes_ != null ? other.requiredAllTypes_.Clone() : null;
+ optionalAllTypes_ = other.optionalAllTypes_ != null ? other.optionalAllTypes_.Clone() : null;
repeatedAllTypes_ = other.repeatedAllTypes_.Clone();
optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null;
repeatedGroup_ = other.repeatedGroup_.Clone();
@@ -20341,16 +20392,6 @@
requiredAllTypes_ = value;
}
}
- /// <summary>Gets whether the required_all_types field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasRequiredAllTypes {
- get { return requiredAllTypes_ != null; }
- }
- /// <summary>Clears the value of the required_all_types field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearRequiredAllTypes() {
- requiredAllTypes_ = null;
- }
/// <summary>Field number for the "optional_all_types" field.</summary>
public const int OptionalAllTypesFieldNumber = 2;
@@ -20362,16 +20403,6 @@
optionalAllTypes_ = value;
}
}
- /// <summary>Gets whether the optional_all_types field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalAllTypes {
- get { return optionalAllTypes_ != null; }
- }
- /// <summary>Clears the value of the optional_all_types field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalAllTypes() {
- optionalAllTypes_ = null;
- }
/// <summary>Field number for the "repeated_all_types" field.</summary>
public const int RepeatedAllTypesFieldNumber = 3;
@@ -20441,8 +20472,8 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasRequiredAllTypes) hash ^= RequiredAllTypes.GetHashCode();
- if (HasOptionalAllTypes) hash ^= OptionalAllTypes.GetHashCode();
+ if (requiredAllTypes_ != null) hash ^= RequiredAllTypes.GetHashCode();
+ if (optionalAllTypes_ != null) hash ^= OptionalAllTypes.GetHashCode();
hash ^= repeatedAllTypes_.GetHashCode();
if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode();
hash ^= repeatedGroup_.GetHashCode();
@@ -20462,11 +20493,11 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasRequiredAllTypes) {
+ if (requiredAllTypes_ != null) {
output.WriteRawTag(10);
output.WriteMessage(RequiredAllTypes);
}
- if (HasOptionalAllTypes) {
+ if (optionalAllTypes_ != null) {
output.WriteRawTag(18);
output.WriteMessage(OptionalAllTypes);
}
@@ -20488,10 +20519,10 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasRequiredAllTypes) {
+ if (requiredAllTypes_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RequiredAllTypes);
}
- if (HasOptionalAllTypes) {
+ if (optionalAllTypes_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalAllTypes);
}
size += repeatedAllTypes_.CalculateSize(_repeated_repeatedAllTypes_codec);
@@ -20513,14 +20544,14 @@
if (other == null) {
return;
}
- if (other.HasRequiredAllTypes) {
- if (!HasRequiredAllTypes) {
+ if (other.requiredAllTypes_ != null) {
+ if (requiredAllTypes_ == null) {
RequiredAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
RequiredAllTypes.MergeFrom(other.RequiredAllTypes);
}
- if (other.HasOptionalAllTypes) {
- if (!HasOptionalAllTypes) {
+ if (other.optionalAllTypes_ != null) {
+ if (optionalAllTypes_ == null) {
OptionalAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
OptionalAllTypes.MergeFrom(other.OptionalAllTypes);
@@ -20539,30 +20570,35 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 10: {
- if (!HasRequiredAllTypes) {
+ if (requiredAllTypes_ == null) {
RequiredAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(RequiredAllTypes);
break;
}
case 18: {
- if (!HasOptionalAllTypes) {
+ if (optionalAllTypes_ == null) {
OptionalAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(OptionalAllTypes);
break;
}
case 26: {
- repeatedAllTypes_.AddEntriesFrom(input, _repeated_repeatedAllTypes_codec);
+ repeatedAllTypes_.AddEntriesFrom(ref input, _repeated_repeatedAllTypes_codec);
break;
}
case 83: {
@@ -20573,7 +20609,7 @@
break;
}
case 163: {
- repeatedGroup_.AddEntriesFrom(input, _repeated_repeatedGroup_codec);
+ repeatedGroup_.AddEntriesFrom(ref input, _repeated_repeatedGroup_codec);
break;
}
}
@@ -20613,7 +20649,7 @@
/// Repeated fields in RepeatedFieldsGenerator are expected to be merged into
/// the corresponding required/optional fields in TestParsingMerge.
/// </summary>
- public sealed partial class RepeatedFieldsGenerator : pb::IMessage<RepeatedFieldsGenerator> {
+ public sealed partial class RepeatedFieldsGenerator : pb::IMessage<RepeatedFieldsGenerator>, pb::IBufferMessage {
private static readonly pb::MessageParser<RepeatedFieldsGenerator> _parser = new pb::MessageParser<RepeatedFieldsGenerator>(() => new RepeatedFieldsGenerator());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -20814,38 +20850,43 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- field1_.AddEntriesFrom(input, _repeated_field1_codec);
+ field1_.AddEntriesFrom(ref input, _repeated_field1_codec);
break;
}
case 18: {
- field2_.AddEntriesFrom(input, _repeated_field2_codec);
+ field2_.AddEntriesFrom(ref input, _repeated_field2_codec);
break;
}
case 26: {
- field3_.AddEntriesFrom(input, _repeated_field3_codec);
+ field3_.AddEntriesFrom(ref input, _repeated_field3_codec);
break;
}
case 83: {
- group1_.AddEntriesFrom(input, _repeated_group1_codec);
+ group1_.AddEntriesFrom(ref input, _repeated_group1_codec);
break;
}
case 163: {
- group2_.AddEntriesFrom(input, _repeated_group2_codec);
+ group2_.AddEntriesFrom(ref input, _repeated_group2_codec);
break;
}
case 8002: {
- ext1_.AddEntriesFrom(input, _repeated_ext1_codec);
+ ext1_.AddEntriesFrom(ref input, _repeated_ext1_codec);
break;
}
case 8010: {
- ext2_.AddEntriesFrom(input, _repeated_ext2_codec);
+ ext2_.AddEntriesFrom(ref input, _repeated_ext2_codec);
break;
}
}
@@ -20856,7 +20897,7 @@
/// <summary>Container for nested types declared in the RepeatedFieldsGenerator message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class Group1 : pb::IMessage<Group1> {
+ public sealed partial class Group1 : pb::IMessage<Group1>, pb::IBufferMessage {
private static readonly pb::MessageParser<Group1> _parser = new pb::MessageParser<Group1>(() => new Group1());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -20881,7 +20922,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Group1(Group1 other) : this() {
- field1_ = other.HasField1 ? other.field1_.Clone() : null;
+ field1_ = other.field1_ != null ? other.field1_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -20900,16 +20941,6 @@
field1_ = value;
}
}
- /// <summary>Gets whether the field1 field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasField1 {
- get { return field1_ != null; }
- }
- /// <summary>Clears the value of the field1 field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearField1() {
- field1_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -20931,7 +20962,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasField1) hash ^= Field1.GetHashCode();
+ if (field1_ != null) hash ^= Field1.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -20945,7 +20976,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasField1) {
+ if (field1_ != null) {
output.WriteRawTag(90);
output.WriteMessage(Field1);
}
@@ -20957,7 +20988,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasField1) {
+ if (field1_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Field1);
}
if (_unknownFields != null) {
@@ -20971,8 +21002,8 @@
if (other == null) {
return;
}
- if (other.HasField1) {
- if (!HasField1) {
+ if (other.field1_ != null) {
+ if (field1_ == null) {
Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
Field1.MergeFrom(other.Field1);
@@ -20982,16 +21013,21 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 84:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 90: {
- if (!HasField1) {
+ if (field1_ == null) {
Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(Field1);
@@ -21003,7 +21039,7 @@
}
- public sealed partial class Group2 : pb::IMessage<Group2> {
+ public sealed partial class Group2 : pb::IMessage<Group2>, pb::IBufferMessage {
private static readonly pb::MessageParser<Group2> _parser = new pb::MessageParser<Group2>(() => new Group2());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -21028,7 +21064,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Group2(Group2 other) : this() {
- field1_ = other.HasField1 ? other.field1_.Clone() : null;
+ field1_ = other.field1_ != null ? other.field1_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -21047,16 +21083,6 @@
field1_ = value;
}
}
- /// <summary>Gets whether the field1 field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasField1 {
- get { return field1_ != null; }
- }
- /// <summary>Clears the value of the field1 field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearField1() {
- field1_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -21078,7 +21104,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasField1) hash ^= Field1.GetHashCode();
+ if (field1_ != null) hash ^= Field1.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -21092,7 +21118,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasField1) {
+ if (field1_ != null) {
output.WriteRawTag(170, 1);
output.WriteMessage(Field1);
}
@@ -21104,7 +21130,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasField1) {
+ if (field1_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(Field1);
}
if (_unknownFields != null) {
@@ -21118,8 +21144,8 @@
if (other == null) {
return;
}
- if (other.HasField1) {
- if (!HasField1) {
+ if (other.field1_ != null) {
+ if (field1_ == null) {
Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
Field1.MergeFrom(other.Field1);
@@ -21129,16 +21155,21 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 164:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 170: {
- if (!HasField1) {
+ if (field1_ == null) {
Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(Field1);
@@ -21155,7 +21186,7 @@
}
- public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup> {
+ public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<OptionalGroup> _parser = new pb::MessageParser<OptionalGroup>(() => new OptionalGroup());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -21180,7 +21211,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OptionalGroup(OptionalGroup other) : this() {
- optionalGroupAllTypes_ = other.HasOptionalGroupAllTypes ? other.optionalGroupAllTypes_.Clone() : null;
+ optionalGroupAllTypes_ = other.optionalGroupAllTypes_ != null ? other.optionalGroupAllTypes_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -21199,16 +21230,6 @@
optionalGroupAllTypes_ = value;
}
}
- /// <summary>Gets whether the optional_group_all_types field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalGroupAllTypes {
- get { return optionalGroupAllTypes_ != null; }
- }
- /// <summary>Clears the value of the optional_group_all_types field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalGroupAllTypes() {
- optionalGroupAllTypes_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -21230,7 +21251,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasOptionalGroupAllTypes) hash ^= OptionalGroupAllTypes.GetHashCode();
+ if (optionalGroupAllTypes_ != null) hash ^= OptionalGroupAllTypes.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -21244,7 +21265,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasOptionalGroupAllTypes) {
+ if (optionalGroupAllTypes_ != null) {
output.WriteRawTag(90);
output.WriteMessage(OptionalGroupAllTypes);
}
@@ -21256,7 +21277,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasOptionalGroupAllTypes) {
+ if (optionalGroupAllTypes_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalGroupAllTypes);
}
if (_unknownFields != null) {
@@ -21270,8 +21291,8 @@
if (other == null) {
return;
}
- if (other.HasOptionalGroupAllTypes) {
- if (!HasOptionalGroupAllTypes) {
+ if (other.optionalGroupAllTypes_ != null) {
+ if (optionalGroupAllTypes_ == null) {
OptionalGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
OptionalGroupAllTypes.MergeFrom(other.OptionalGroupAllTypes);
@@ -21281,16 +21302,21 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 84:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 90: {
- if (!HasOptionalGroupAllTypes) {
+ if (optionalGroupAllTypes_ == null) {
OptionalGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(OptionalGroupAllTypes);
@@ -21302,7 +21328,7 @@
}
- public sealed partial class RepeatedGroup : pb::IMessage<RepeatedGroup> {
+ public sealed partial class RepeatedGroup : pb::IMessage<RepeatedGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<RepeatedGroup> _parser = new pb::MessageParser<RepeatedGroup>(() => new RepeatedGroup());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -21327,7 +21353,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RepeatedGroup(RepeatedGroup other) : this() {
- repeatedGroupAllTypes_ = other.HasRepeatedGroupAllTypes ? other.repeatedGroupAllTypes_.Clone() : null;
+ repeatedGroupAllTypes_ = other.repeatedGroupAllTypes_ != null ? other.repeatedGroupAllTypes_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -21346,16 +21372,6 @@
repeatedGroupAllTypes_ = value;
}
}
- /// <summary>Gets whether the repeated_group_all_types field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasRepeatedGroupAllTypes {
- get { return repeatedGroupAllTypes_ != null; }
- }
- /// <summary>Clears the value of the repeated_group_all_types field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearRepeatedGroupAllTypes() {
- repeatedGroupAllTypes_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -21377,7 +21393,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
- if (HasRepeatedGroupAllTypes) hash ^= RepeatedGroupAllTypes.GetHashCode();
+ if (repeatedGroupAllTypes_ != null) hash ^= RepeatedGroupAllTypes.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -21391,7 +21407,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
- if (HasRepeatedGroupAllTypes) {
+ if (repeatedGroupAllTypes_ != null) {
output.WriteRawTag(170, 1);
output.WriteMessage(RepeatedGroupAllTypes);
}
@@ -21403,7 +21419,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
- if (HasRepeatedGroupAllTypes) {
+ if (repeatedGroupAllTypes_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(RepeatedGroupAllTypes);
}
if (_unknownFields != null) {
@@ -21417,8 +21433,8 @@
if (other == null) {
return;
}
- if (other.HasRepeatedGroupAllTypes) {
- if (!HasRepeatedGroupAllTypes) {
+ if (other.repeatedGroupAllTypes_ != null) {
+ if (repeatedGroupAllTypes_ == null) {
RepeatedGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
RepeatedGroupAllTypes.MergeFrom(other.RepeatedGroupAllTypes);
@@ -21428,16 +21444,21 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 164:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 170: {
- if (!HasRepeatedGroupAllTypes) {
+ if (repeatedGroupAllTypes_ == null) {
RepeatedGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
}
input.ReadMessage(RepeatedGroupAllTypes);
@@ -21465,7 +21486,7 @@
}
- public sealed partial class TestCommentInjectionMessage : pb::IMessage<TestCommentInjectionMessage> {
+ public sealed partial class TestCommentInjectionMessage : pb::IMessage<TestCommentInjectionMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestCommentInjectionMessage> _parser = new pb::MessageParser<TestCommentInjectionMessage>(() => new TestCommentInjectionMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -21593,11 +21614,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
A = input.ReadString();
@@ -21612,7 +21638,7 @@
/// <summary>
/// Test that RPC services work.
/// </summary>
- public sealed partial class FooRequest : pb::IMessage<FooRequest> {
+ public sealed partial class FooRequest : pb::IMessage<FooRequest>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooRequest> _parser = new pb::MessageParser<FooRequest>(() => new FooRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -21701,11 +21727,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -21713,7 +21744,7 @@
}
- public sealed partial class FooResponse : pb::IMessage<FooResponse> {
+ public sealed partial class FooResponse : pb::IMessage<FooResponse>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooResponse> _parser = new pb::MessageParser<FooResponse>(() => new FooResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -21802,11 +21833,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -21814,7 +21850,7 @@
}
- public sealed partial class FooClientMessage : pb::IMessage<FooClientMessage> {
+ public sealed partial class FooClientMessage : pb::IMessage<FooClientMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooClientMessage> _parser = new pb::MessageParser<FooClientMessage>(() => new FooClientMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -21903,11 +21939,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -21915,7 +21956,7 @@
}
- public sealed partial class FooServerMessage : pb::IMessage<FooServerMessage> {
+ public sealed partial class FooServerMessage : pb::IMessage<FooServerMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooServerMessage> _parser = new pb::MessageParser<FooServerMessage>(() => new FooServerMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -22004,11 +22045,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -22016,7 +22062,7 @@
}
- public sealed partial class BarRequest : pb::IMessage<BarRequest> {
+ public sealed partial class BarRequest : pb::IMessage<BarRequest>, pb::IBufferMessage {
private static readonly pb::MessageParser<BarRequest> _parser = new pb::MessageParser<BarRequest>(() => new BarRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -22105,11 +22151,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -22117,7 +22168,7 @@
}
- public sealed partial class BarResponse : pb::IMessage<BarResponse> {
+ public sealed partial class BarResponse : pb::IMessage<BarResponse>, pb::IBufferMessage {
private static readonly pb::MessageParser<BarResponse> _parser = new pb::MessageParser<BarResponse>(() => new BarResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -22206,11 +22257,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -22218,7 +22274,7 @@
}
- public sealed partial class TestJsonName : pb::IMessage<TestJsonName> {
+ public sealed partial class TestJsonName : pb::IMessage<TestJsonName>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestJsonName> _parser = new pb::MessageParser<TestJsonName>(() => new TestJsonName());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -22531,11 +22587,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
FieldName1 = input.ReadInt32();
@@ -22567,7 +22628,7 @@
}
- public sealed partial class TestHugeFieldNumbers : pb::IExtendableMessage<TestHugeFieldNumbers> {
+ public sealed partial class TestHugeFieldNumbers : pb::IExtendableMessage<TestHugeFieldNumbers>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestHugeFieldNumbers> _parser = new pb::MessageParser<TestHugeFieldNumbers>(() => new TestHugeFieldNumbers());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestHugeFieldNumbers> _extensions;
@@ -22603,7 +22664,7 @@
optionalEnum_ = other.optionalEnum_;
optionalString_ = other.optionalString_;
optionalBytes_ = other.optionalBytes_;
- optionalMessage_ = other.HasOptionalMessage ? other.optionalMessage_.Clone() : null;
+ optionalMessage_ = other.optionalMessage_ != null ? other.optionalMessage_.Clone() : null;
optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null;
stringStringMap_ = other.stringStringMap_.Clone();
switch (other.OneofFieldCase) {
@@ -22778,16 +22839,6 @@
optionalMessage_ = value;
}
}
- /// <summary>Gets whether the optional_message field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptionalMessage {
- get { return optionalMessage_ != null; }
- }
- /// <summary>Clears the value of the optional_message field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptionalMessage() {
- optionalMessage_ = null;
- }
/// <summary>Field number for the "optionalgroup" field.</summary>
public const int OptionalGroupFieldNumber = 536870008;
@@ -22847,24 +22898,12 @@
public const int OneofTestAllTypesFieldNumber = 536870012;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes OneofTestAllTypes {
- get { return HasOneofTestAllTypes ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes) oneofField_ : null; }
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes) oneofField_ : null; }
set {
oneofField_ = value;
oneofFieldCase_ = value == null ? OneofFieldOneofCase.None : OneofFieldOneofCase.OneofTestAllTypes;
}
}
- /// <summary>Gets whether the "oneof_test_all_types" field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOneofTestAllTypes {
- get { return oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes; }
- }
- /// <summary> Clears the value of the oneof if it's currently set to "oneof_test_all_types" </summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOneofTestAllTypes() {
- if (HasOneofTestAllTypes) {
- ClearOneofField();
- }
- }
/// <summary>Field number for the "oneof_string" field.</summary>
public const int OneofStringFieldNumber = 536870013;
@@ -22977,11 +23016,11 @@
if (HasOptionalEnum) hash ^= OptionalEnum.GetHashCode();
if (HasOptionalString) hash ^= OptionalString.GetHashCode();
if (HasOptionalBytes) hash ^= OptionalBytes.GetHashCode();
- if (HasOptionalMessage) hash ^= OptionalMessage.GetHashCode();
+ if (optionalMessage_ != null) hash ^= OptionalMessage.GetHashCode();
if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode();
hash ^= StringStringMap.GetHashCode();
if (HasOneofUint32) hash ^= OneofUint32.GetHashCode();
- if (HasOneofTestAllTypes) hash ^= OneofTestAllTypes.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) hash ^= OneofTestAllTypes.GetHashCode();
if (HasOneofString) hash ^= OneofString.GetHashCode();
if (HasOneofBytes) hash ^= OneofBytes.GetHashCode();
hash ^= (int) oneofFieldCase_;
@@ -23023,7 +23062,7 @@
output.WriteRawTag(178, 199, 255, 255, 15);
output.WriteBytes(OptionalBytes);
}
- if (HasOptionalMessage) {
+ if (optionalMessage_ != null) {
output.WriteRawTag(186, 199, 255, 255, 15);
output.WriteMessage(OptionalMessage);
}
@@ -23037,7 +23076,7 @@
output.WriteRawTag(216, 199, 255, 255, 15);
output.WriteUInt32(OneofUint32);
}
- if (HasOneofTestAllTypes) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) {
output.WriteRawTag(226, 199, 255, 255, 15);
output.WriteMessage(OneofTestAllTypes);
}
@@ -23077,7 +23116,7 @@
if (HasOptionalBytes) {
size += 5 + pb::CodedOutputStream.ComputeBytesSize(OptionalBytes);
}
- if (HasOptionalMessage) {
+ if (optionalMessage_ != null) {
size += 5 + pb::CodedOutputStream.ComputeMessageSize(OptionalMessage);
}
if (HasOptionalGroup) {
@@ -23087,7 +23126,7 @@
if (HasOneofUint32) {
size += 5 + pb::CodedOutputStream.ComputeUInt32Size(OneofUint32);
}
- if (HasOneofTestAllTypes) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) {
size += 5 + pb::CodedOutputStream.ComputeMessageSize(OneofTestAllTypes);
}
if (HasOneofString) {
@@ -23127,8 +23166,8 @@
if (other.HasOptionalBytes) {
OptionalBytes = other.OptionalBytes;
}
- if (other.HasOptionalMessage) {
- if (!HasOptionalMessage) {
+ if (other.optionalMessage_ != null) {
+ if (optionalMessage_ == null) {
OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
OptionalMessage.MergeFrom(other.OptionalMessage);
@@ -23164,12 +23203,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 4294960000: {
@@ -23182,12 +23226,12 @@
}
case 4294960018:
case 4294960016: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
case 4294960026:
case 4294960024: {
- packedInt32_.AddEntriesFrom(input, _repeated_packedInt32_codec);
+ packedInt32_.AddEntriesFrom(ref input, _repeated_packedInt32_codec);
break;
}
case 4294960032: {
@@ -23203,7 +23247,7 @@
break;
}
case 4294960058: {
- if (!HasOptionalMessage) {
+ if (optionalMessage_ == null) {
OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage();
}
input.ReadMessage(OptionalMessage);
@@ -23217,7 +23261,7 @@
break;
}
case 4294960082: {
- stringStringMap_.AddEntriesFrom(input, _map_stringStringMap_codec);
+ stringStringMap_.AddEntriesFrom(ref input, _map_stringStringMap_codec);
break;
}
case 4294960088: {
@@ -23226,7 +23270,7 @@
}
case 4294960098: {
global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes();
- if (HasOneofTestAllTypes) {
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) {
subBuilder.MergeFrom(OneofTestAllTypes);
}
input.ReadMessage(subBuilder);
@@ -23271,7 +23315,7 @@
/// <summary>Container for nested types declared in the TestHugeFieldNumbers message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup> {
+ public sealed partial class OptionalGroup : pb::IMessage<OptionalGroup>, pb::IBufferMessage {
private static readonly pb::MessageParser<OptionalGroup> _parser = new pb::MessageParser<OptionalGroup>(() => new OptionalGroup());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -23399,13 +23443,18 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
case 4294960068:
return;
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 4294960072: {
GroupA = input.ReadInt32();
@@ -23422,7 +23471,7 @@
}
- public sealed partial class TestExtensionInsideTable : pb::IExtendableMessage<TestExtensionInsideTable> {
+ public sealed partial class TestExtensionInsideTable : pb::IExtendableMessage<TestExtensionInsideTable>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestExtensionInsideTable> _parser = new pb::MessageParser<TestExtensionInsideTable>(() => new TestExtensionInsideTable());
private pb::UnknownFieldSet _unknownFields;
private pb::ExtensionSet<TestExtensionInsideTable> _extensions;
@@ -23862,12 +23911,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 8: {
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestCustomOptionsProto3.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestCustomOptionsProto3.cs
index cb5edf7..818748b 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestCustomOptionsProto3.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestCustomOptionsProto3.cs
@@ -257,7 +257,7 @@
/// A test message with custom options at all possible locations (and also some
/// regular options, to make sure they interact nicely).
/// </summary>
- public sealed partial class TestMessageWithCustomOptions : pb::IMessage<TestMessageWithCustomOptions> {
+ public sealed partial class TestMessageWithCustomOptions : pb::IMessage<TestMessageWithCustomOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMessageWithCustomOptions> _parser = new pb::MessageParser<TestMessageWithCustomOptions>(() => new TestMessageWithCustomOptions());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -422,11 +422,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Field1 = input.ReadString();
@@ -459,7 +464,7 @@
/// A test RPC service with custom options at all possible locations (and also
/// some regular options, to make sure they interact nicely).
/// </summary>
- public sealed partial class CustomOptionFooRequest : pb::IMessage<CustomOptionFooRequest> {
+ public sealed partial class CustomOptionFooRequest : pb::IMessage<CustomOptionFooRequest>, pb::IBufferMessage {
private static readonly pb::MessageParser<CustomOptionFooRequest> _parser = new pb::MessageParser<CustomOptionFooRequest>(() => new CustomOptionFooRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -548,11 +553,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -560,7 +570,7 @@
}
- public sealed partial class CustomOptionFooResponse : pb::IMessage<CustomOptionFooResponse> {
+ public sealed partial class CustomOptionFooResponse : pb::IMessage<CustomOptionFooResponse>, pb::IBufferMessage {
private static readonly pb::MessageParser<CustomOptionFooResponse> _parser = new pb::MessageParser<CustomOptionFooResponse>(() => new CustomOptionFooResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -649,11 +659,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -661,7 +676,7 @@
}
- public sealed partial class CustomOptionFooClientMessage : pb::IMessage<CustomOptionFooClientMessage> {
+ public sealed partial class CustomOptionFooClientMessage : pb::IMessage<CustomOptionFooClientMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<CustomOptionFooClientMessage> _parser = new pb::MessageParser<CustomOptionFooClientMessage>(() => new CustomOptionFooClientMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -750,11 +765,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -762,7 +782,7 @@
}
- public sealed partial class CustomOptionFooServerMessage : pb::IMessage<CustomOptionFooServerMessage> {
+ public sealed partial class CustomOptionFooServerMessage : pb::IMessage<CustomOptionFooServerMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<CustomOptionFooServerMessage> _parser = new pb::MessageParser<CustomOptionFooServerMessage>(() => new CustomOptionFooServerMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -851,11 +871,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -863,7 +888,7 @@
}
- public sealed partial class DummyMessageContainingEnum : pb::IMessage<DummyMessageContainingEnum> {
+ public sealed partial class DummyMessageContainingEnum : pb::IMessage<DummyMessageContainingEnum>, pb::IBufferMessage {
private static readonly pb::MessageParser<DummyMessageContainingEnum> _parser = new pb::MessageParser<DummyMessageContainingEnum>(() => new DummyMessageContainingEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -952,11 +977,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -977,7 +1007,7 @@
}
- public sealed partial class DummyMessageInvalidAsOptionType : pb::IMessage<DummyMessageInvalidAsOptionType> {
+ public sealed partial class DummyMessageInvalidAsOptionType : pb::IMessage<DummyMessageInvalidAsOptionType>, pb::IBufferMessage {
private static readonly pb::MessageParser<DummyMessageInvalidAsOptionType> _parser = new pb::MessageParser<DummyMessageInvalidAsOptionType>(() => new DummyMessageInvalidAsOptionType());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1066,11 +1096,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -1078,7 +1113,7 @@
}
- public sealed partial class CustomOptionMinIntegerValues : pb::IMessage<CustomOptionMinIntegerValues> {
+ public sealed partial class CustomOptionMinIntegerValues : pb::IMessage<CustomOptionMinIntegerValues>, pb::IBufferMessage {
private static readonly pb::MessageParser<CustomOptionMinIntegerValues> _parser = new pb::MessageParser<CustomOptionMinIntegerValues>(() => new CustomOptionMinIntegerValues());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1167,11 +1202,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -1179,7 +1219,7 @@
}
- public sealed partial class CustomOptionMaxIntegerValues : pb::IMessage<CustomOptionMaxIntegerValues> {
+ public sealed partial class CustomOptionMaxIntegerValues : pb::IMessage<CustomOptionMaxIntegerValues>, pb::IBufferMessage {
private static readonly pb::MessageParser<CustomOptionMaxIntegerValues> _parser = new pb::MessageParser<CustomOptionMaxIntegerValues>(() => new CustomOptionMaxIntegerValues());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1268,11 +1308,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -1280,7 +1325,7 @@
}
- public sealed partial class CustomOptionOtherValues : pb::IMessage<CustomOptionOtherValues> {
+ public sealed partial class CustomOptionOtherValues : pb::IMessage<CustomOptionOtherValues>, pb::IBufferMessage {
private static readonly pb::MessageParser<CustomOptionOtherValues> _parser = new pb::MessageParser<CustomOptionOtherValues>(() => new CustomOptionOtherValues());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1369,11 +1414,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -1381,7 +1431,7 @@
}
- public sealed partial class SettingRealsFromPositiveInts : pb::IMessage<SettingRealsFromPositiveInts> {
+ public sealed partial class SettingRealsFromPositiveInts : pb::IMessage<SettingRealsFromPositiveInts>, pb::IBufferMessage {
private static readonly pb::MessageParser<SettingRealsFromPositiveInts> _parser = new pb::MessageParser<SettingRealsFromPositiveInts>(() => new SettingRealsFromPositiveInts());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1470,11 +1520,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -1482,7 +1537,7 @@
}
- public sealed partial class SettingRealsFromNegativeInts : pb::IMessage<SettingRealsFromNegativeInts> {
+ public sealed partial class SettingRealsFromNegativeInts : pb::IMessage<SettingRealsFromNegativeInts>, pb::IBufferMessage {
private static readonly pb::MessageParser<SettingRealsFromNegativeInts> _parser = new pb::MessageParser<SettingRealsFromNegativeInts>(() => new SettingRealsFromNegativeInts());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1571,11 +1626,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -1583,7 +1643,7 @@
}
- public sealed partial class ComplexOptionType1 : pb::IMessage<ComplexOptionType1> {
+ public sealed partial class ComplexOptionType1 : pb::IMessage<ComplexOptionType1>, pb::IBufferMessage {
private static readonly pb::MessageParser<ComplexOptionType1> _parser = new pb::MessageParser<ComplexOptionType1>(() => new ComplexOptionType1());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1760,11 +1820,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Foo = input.ReadInt32();
@@ -1780,7 +1845,7 @@
}
case 34:
case 32: {
- foo4_.AddEntriesFrom(input, _repeated_foo4_codec);
+ foo4_.AddEntriesFrom(ref input, _repeated_foo4_codec);
break;
}
}
@@ -1789,7 +1854,7 @@
}
- public sealed partial class ComplexOptionType2 : pb::IMessage<ComplexOptionType2> {
+ public sealed partial class ComplexOptionType2 : pb::IMessage<ComplexOptionType2>, pb::IBufferMessage {
private static readonly pb::MessageParser<ComplexOptionType2> _parser = new pb::MessageParser<ComplexOptionType2>(() => new ComplexOptionType2());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1972,11 +2037,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (bar_ == null) {
@@ -1997,7 +2067,7 @@
break;
}
case 34: {
- barney_.AddEntriesFrom(input, _repeated_barney_codec);
+ barney_.AddEntriesFrom(ref input, _repeated_barney_codec);
break;
}
}
@@ -2008,7 +2078,7 @@
/// <summary>Container for nested types declared in the ComplexOptionType2 message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class ComplexOptionType4 : pb::IMessage<ComplexOptionType4> {
+ public sealed partial class ComplexOptionType4 : pb::IMessage<ComplexOptionType4>, pb::IBufferMessage {
private static readonly pb::MessageParser<ComplexOptionType4> _parser = new pb::MessageParser<ComplexOptionType4>(() => new ComplexOptionType4());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2121,11 +2191,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Waldo = input.ReadInt32();
@@ -2151,7 +2226,7 @@
}
- public sealed partial class ComplexOptionType3 : pb::IMessage<ComplexOptionType3> {
+ public sealed partial class ComplexOptionType3 : pb::IMessage<ComplexOptionType3>, pb::IBufferMessage {
private static readonly pb::MessageParser<ComplexOptionType3> _parser = new pb::MessageParser<ComplexOptionType3>(() => new ComplexOptionType3());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2264,11 +2339,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Qux = input.ReadInt32();
@@ -2283,7 +2363,7 @@
/// <summary>
/// Note that we try various different ways of naming the same extension.
/// </summary>
- public sealed partial class VariousComplexOptions : pb::IMessage<VariousComplexOptions> {
+ public sealed partial class VariousComplexOptions : pb::IMessage<VariousComplexOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<VariousComplexOptions> _parser = new pb::MessageParser<VariousComplexOptions>(() => new VariousComplexOptions());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2372,11 +2452,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -2387,7 +2472,7 @@
/// <summary>
/// A helper type used to test aggregate option parsing
/// </summary>
- public sealed partial class Aggregate : pb::IMessage<Aggregate> {
+ public sealed partial class Aggregate : pb::IMessage<Aggregate>, pb::IBufferMessage {
private static readonly pb::MessageParser<Aggregate> _parser = new pb::MessageParser<Aggregate>(() => new Aggregate());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2554,11 +2639,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
I = input.ReadInt32();
@@ -2581,7 +2671,7 @@
}
- public sealed partial class AggregateMessage : pb::IMessage<AggregateMessage> {
+ public sealed partial class AggregateMessage : pb::IMessage<AggregateMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<AggregateMessage> _parser = new pb::MessageParser<AggregateMessage>(() => new AggregateMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2694,11 +2784,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Fieldname = input.ReadInt32();
@@ -2713,7 +2808,7 @@
/// <summary>
/// Test custom options for nested type.
/// </summary>
- public sealed partial class NestedOptionType : pb::IMessage<NestedOptionType> {
+ public sealed partial class NestedOptionType : pb::IMessage<NestedOptionType>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedOptionType> _parser = new pb::MessageParser<NestedOptionType>(() => new NestedOptionType());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2802,11 +2897,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -2821,7 +2921,7 @@
[pbr::OriginalName("NESTED_ENUM_VALUE")] Value = 1,
}
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2934,11 +3034,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
NestedField = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImport.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImport.cs
index d5f8589..1cddcd8 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImport.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImport.cs
@@ -59,7 +59,7 @@
#endregion
#region Messages
- public sealed partial class ImportMessage : pb::IMessage<ImportMessage> {
+ public sealed partial class ImportMessage : pb::IMessage<ImportMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<ImportMessage> _parser = new pb::MessageParser<ImportMessage>(() => new ImportMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -187,11 +187,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
D = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportProto3.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportProto3.cs
index 19a1a34..bcd27bf 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportProto3.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportProto3.cs
@@ -50,7 +50,7 @@
#endregion
#region Messages
- public sealed partial class ImportMessage : pb::IMessage<ImportMessage> {
+ public sealed partial class ImportMessage : pb::IMessage<ImportMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<ImportMessage> _parser = new pb::MessageParser<ImportMessage>(() => new ImportMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -163,11 +163,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
D = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublic.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublic.cs
index 77f2121..6b35c10 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublic.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublic.cs
@@ -37,7 +37,7 @@
}
#region Messages
- public sealed partial class PublicImportMessage : pb::IMessage<PublicImportMessage> {
+ public sealed partial class PublicImportMessage : pb::IMessage<PublicImportMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<PublicImportMessage> _parser = new pb::MessageParser<PublicImportMessage>(() => new PublicImportMessage());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -165,11 +165,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
E = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublicProto3.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublicProto3.cs
index a455655..664c666 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublicProto3.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestImportPublicProto3.cs
@@ -38,7 +38,7 @@
}
#region Messages
- public sealed partial class PublicImportMessage : pb::IMessage<PublicImportMessage> {
+ public sealed partial class PublicImportMessage : pb::IMessage<PublicImportMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<PublicImportMessage> _parser = new pb::MessageParser<PublicImportMessage>(() => new PublicImportMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -151,11 +151,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
E = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs
new file mode 100644
index 0000000..56fde4f
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs
@@ -0,0 +1,46 @@
+// <auto-generated>
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: unittest_issue6936_a.proto
+// </auto-generated>
+#pragma warning disable 1591, 0612, 3021
+#region Designer generated code
+
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
+using scg = global::System.Collections.Generic;
+namespace UnitTest.Issues.TestProtos {
+
+ /// <summary>Holder for reflection information generated from unittest_issue6936_a.proto</summary>
+ public static partial class UnittestIssue6936AReflection {
+
+ #region Descriptor
+ /// <summary>File descriptor for unittest_issue6936_a.proto</summary>
+ public static pbr::FileDescriptor Descriptor {
+ get { return descriptor; }
+ }
+ private static pbr::FileDescriptor descriptor;
+
+ static UnittestIssue6936AReflection() {
+ byte[] descriptorData = global::System.Convert.FromBase64String(
+ string.Concat(
+ "Chp1bml0dGVzdF9pc3N1ZTY5MzZfYS5wcm90bxIPdW5pdHRlc3RfaXNzdWVz",
+ "GiBnb29nbGUvcHJvdG9idWYvZGVzY3JpcHRvci5wcm90bzouCgNvcHQSHy5n",
+ "b29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY0IYDIAEoCUIdqgIaVW5p",
+ "dFRlc3QuSXNzdWVzLlRlc3RQcm90b3NiBnByb3RvMw=="));
+ descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
+ new pbr::FileDescriptor[] { global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor, },
+ new pbr::GeneratedClrTypeInfo(null, new pb::Extension[] { UnittestIssue6936AExtensions.Opt }, null));
+ }
+ #endregion
+
+ }
+ /// <summary>Holder for extension identifiers generated from the top level of unittest_issue6936_a.proto</summary>
+ public static partial class UnittestIssue6936AExtensions {
+ public static readonly pb::Extension<global::Google.Protobuf.Reflection.MessageOptions, string> Opt =
+ new pb::Extension<global::Google.Protobuf.Reflection.MessageOptions, string>(50000, pb::FieldCodec.ForString(400002, ""));
+ }
+
+}
+
+#endregion Designer generated code
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936B.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936B.cs
new file mode 100644
index 0000000..bede87a
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936B.cs
@@ -0,0 +1,150 @@
+// <auto-generated>
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: unittest_issue6936_b.proto
+// </auto-generated>
+#pragma warning disable 1591, 0612, 3021
+#region Designer generated code
+
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
+using scg = global::System.Collections.Generic;
+namespace UnitTest.Issues.TestProtos {
+
+ /// <summary>Holder for reflection information generated from unittest_issue6936_b.proto</summary>
+ public static partial class UnittestIssue6936BReflection {
+
+ #region Descriptor
+ /// <summary>File descriptor for unittest_issue6936_b.proto</summary>
+ public static pbr::FileDescriptor Descriptor {
+ get { return descriptor; }
+ }
+ private static pbr::FileDescriptor descriptor;
+
+ static UnittestIssue6936BReflection() {
+ byte[] descriptorData = global::System.Convert.FromBase64String(
+ string.Concat(
+ "Chp1bml0dGVzdF9pc3N1ZTY5MzZfYi5wcm90bxIPdW5pdHRlc3RfaXNzdWVz",
+ "Ghp1bml0dGVzdF9pc3N1ZTY5MzZfYS5wcm90byIOCgNGb286B4K1GANmb29C",
+ "HaoCGlVuaXRUZXN0Lklzc3Vlcy5UZXN0UHJvdG9zYgZwcm90bzM="));
+ descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
+ new pbr::FileDescriptor[] { global::UnitTest.Issues.TestProtos.UnittestIssue6936AReflection.Descriptor, },
+ new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Foo), global::UnitTest.Issues.TestProtos.Foo.Parser, null, null, null, null, null)
+ }));
+ }
+ #endregion
+
+ }
+ #region Messages
+ public sealed partial class Foo : pb::IMessage<Foo>, pb::IBufferMessage {
+ private static readonly pb::MessageParser<Foo> _parser = new pb::MessageParser<Foo>(() => new Foo());
+ private pb::UnknownFieldSet _unknownFields;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<Foo> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestIssue6936BReflection.Descriptor.MessageTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Foo() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Foo(Foo other) : this() {
+ _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Foo Clone() {
+ return new Foo(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as Foo);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(Foo other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ return Equals(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (_unknownFields != null) {
+ hash ^= _unknownFields.GetHashCode();
+ }
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (_unknownFields != null) {
+ _unknownFields.WriteTo(output);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (_unknownFields != null) {
+ size += _unknownFields.CalculateSize();
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(Foo other) {
+ if (other == null) {
+ return;
+ }
+ _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
+ break;
+ }
+ }
+ }
+
+ }
+
+ #endregion
+
+}
+
+#endregion Designer generated code
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs
new file mode 100644
index 0000000..e86780f
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs
@@ -0,0 +1,186 @@
+// <auto-generated>
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: unittest_issue6936_c.proto
+// </auto-generated>
+#pragma warning disable 1591, 0612, 3021
+#region Designer generated code
+
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
+using scg = global::System.Collections.Generic;
+namespace UnitTest.Issues.TestProtos {
+
+ /// <summary>Holder for reflection information generated from unittest_issue6936_c.proto</summary>
+ public static partial class UnittestIssue6936CReflection {
+
+ #region Descriptor
+ /// <summary>File descriptor for unittest_issue6936_c.proto</summary>
+ public static pbr::FileDescriptor Descriptor {
+ get { return descriptor; }
+ }
+ private static pbr::FileDescriptor descriptor;
+
+ static UnittestIssue6936CReflection() {
+ byte[] descriptorData = global::System.Convert.FromBase64String(
+ string.Concat(
+ "Chp1bml0dGVzdF9pc3N1ZTY5MzZfYy5wcm90bxIPdW5pdHRlc3RfaXNzdWVz",
+ "Ghp1bml0dGVzdF9pc3N1ZTY5MzZfYS5wcm90bxoadW5pdHRlc3RfaXNzdWU2",
+ "OTM2X2IucHJvdG8iMQoDQmFyEiEKA2ZvbxgBIAEoCzIULnVuaXR0ZXN0X2lz",
+ "c3Vlcy5Gb286B4K1GANiYXJCHaoCGlVuaXRUZXN0Lklzc3Vlcy5UZXN0UHJv",
+ "dG9zYgZwcm90bzM="));
+ descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
+ new pbr::FileDescriptor[] { global::UnitTest.Issues.TestProtos.UnittestIssue6936AReflection.Descriptor, global::UnitTest.Issues.TestProtos.UnittestIssue6936BReflection.Descriptor, },
+ new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Bar), global::UnitTest.Issues.TestProtos.Bar.Parser, new[]{ "Foo" }, null, null, null, null)
+ }));
+ }
+ #endregion
+
+ }
+ #region Messages
+ public sealed partial class Bar : pb::IMessage<Bar>, pb::IBufferMessage {
+ private static readonly pb::MessageParser<Bar> _parser = new pb::MessageParser<Bar>(() => new Bar());
+ private pb::UnknownFieldSet _unknownFields;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<Bar> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.UnittestIssue6936CReflection.Descriptor.MessageTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Bar() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Bar(Bar other) : this() {
+ foo_ = other.foo_ != null ? other.foo_.Clone() : null;
+ _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public Bar Clone() {
+ return new Bar(this);
+ }
+
+ /// <summary>Field number for the "foo" field.</summary>
+ public const int FooFieldNumber = 1;
+ private global::UnitTest.Issues.TestProtos.Foo foo_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::UnitTest.Issues.TestProtos.Foo Foo {
+ get { return foo_; }
+ set {
+ foo_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as Bar);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(Bar other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (!object.Equals(Foo, other.Foo)) return false;
+ return Equals(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (foo_ != null) hash ^= Foo.GetHashCode();
+ if (_unknownFields != null) {
+ hash ^= _unknownFields.GetHashCode();
+ }
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (foo_ != null) {
+ output.WriteRawTag(10);
+ output.WriteMessage(Foo);
+ }
+ if (_unknownFields != null) {
+ _unknownFields.WriteTo(output);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (foo_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Foo);
+ }
+ if (_unknownFields != null) {
+ size += _unknownFields.CalculateSize();
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(Bar other) {
+ if (other == null) {
+ return;
+ }
+ if (other.foo_ != null) {
+ if (foo_ == null) {
+ Foo = new global::UnitTest.Issues.TestProtos.Foo();
+ }
+ Foo.MergeFrom(other.Foo);
+ }
+ _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
+ break;
+ case 10: {
+ if (foo_ == null) {
+ Foo = new global::UnitTest.Issues.TestProtos.Foo();
+ }
+ input.ReadMessage(Foo);
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ #endregion
+
+}
+
+#endregion Designer generated code
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs
index f3f40c6..68884e1 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs
@@ -88,7 +88,7 @@
/// Issue 307: when generating doubly-nested types, any references
/// should be of the form A.Types.B.Types.C.
/// </summary>
- public sealed partial class Issue307 : pb::IMessage<Issue307> {
+ public sealed partial class Issue307 : pb::IMessage<Issue307>, pb::IBufferMessage {
private static readonly pb::MessageParser<Issue307> _parser = new pb::MessageParser<Issue307>(() => new Issue307());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -177,11 +177,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -191,7 +196,7 @@
/// <summary>Container for nested types declared in the Issue307 message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class NestedOnce : pb::IMessage<NestedOnce> {
+ public sealed partial class NestedOnce : pb::IMessage<NestedOnce>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedOnce> _parser = new pb::MessageParser<NestedOnce>(() => new NestedOnce());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -280,11 +285,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -294,7 +304,7 @@
/// <summary>Container for nested types declared in the NestedOnce message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class NestedTwice : pb::IMessage<NestedTwice> {
+ public sealed partial class NestedTwice : pb::IMessage<NestedTwice>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedTwice> _parser = new pb::MessageParser<NestedTwice>(() => new NestedTwice());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -383,11 +393,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -405,7 +420,7 @@
}
- public sealed partial class NegativeEnumMessage : pb::IMessage<NegativeEnumMessage> {
+ public sealed partial class NegativeEnumMessage : pb::IMessage<NegativeEnumMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NegativeEnumMessage> _parser = new pb::MessageParser<NegativeEnumMessage>(() => new NegativeEnumMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -550,11 +565,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Value = (global::UnitTest.Issues.TestProtos.NegativeEnum) input.ReadEnum();
@@ -562,12 +582,12 @@
}
case 18:
case 16: {
- values_.AddEntriesFrom(input, _repeated_values_codec);
+ values_.AddEntriesFrom(ref input, _repeated_values_codec);
break;
}
case 26:
case 24: {
- packedValues_.AddEntriesFrom(input, _repeated_packedValues_codec);
+ packedValues_.AddEntriesFrom(ref input, _repeated_packedValues_codec);
break;
}
}
@@ -576,7 +596,7 @@
}
- public sealed partial class DeprecatedChild : pb::IMessage<DeprecatedChild> {
+ public sealed partial class DeprecatedChild : pb::IMessage<DeprecatedChild>, pb::IBufferMessage {
private static readonly pb::MessageParser<DeprecatedChild> _parser = new pb::MessageParser<DeprecatedChild>(() => new DeprecatedChild());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -665,11 +685,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -677,7 +702,7 @@
}
- public sealed partial class DeprecatedFieldsMessage : pb::IMessage<DeprecatedFieldsMessage> {
+ public sealed partial class DeprecatedFieldsMessage : pb::IMessage<DeprecatedFieldsMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<DeprecatedFieldsMessage> _parser = new pb::MessageParser<DeprecatedFieldsMessage>(() => new DeprecatedFieldsMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -895,11 +920,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
PrimitiveValue = input.ReadInt32();
@@ -907,7 +937,7 @@
}
case 18:
case 16: {
- primitiveArray_.AddEntriesFrom(input, _repeated_primitiveArray_codec);
+ primitiveArray_.AddEntriesFrom(ref input, _repeated_primitiveArray_codec);
break;
}
case 26: {
@@ -918,7 +948,7 @@
break;
}
case 34: {
- messageArray_.AddEntriesFrom(input, _repeated_messageArray_codec);
+ messageArray_.AddEntriesFrom(ref input, _repeated_messageArray_codec);
break;
}
case 40: {
@@ -927,7 +957,7 @@
}
case 50:
case 48: {
- enumArray_.AddEntriesFrom(input, _repeated_enumArray_codec);
+ enumArray_.AddEntriesFrom(ref input, _repeated_enumArray_codec);
break;
}
}
@@ -939,7 +969,7 @@
/// <summary>
/// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45
/// </summary>
- public sealed partial class ItemField : pb::IMessage<ItemField> {
+ public sealed partial class ItemField : pb::IMessage<ItemField>, pb::IBufferMessage {
private static readonly pb::MessageParser<ItemField> _parser = new pb::MessageParser<ItemField>(() => new ItemField());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1052,11 +1082,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Item = input.ReadInt32();
@@ -1068,7 +1103,7 @@
}
- public sealed partial class ReservedNames : pb::IMessage<ReservedNames> {
+ public sealed partial class ReservedNames : pb::IMessage<ReservedNames>, pb::IBufferMessage {
private static readonly pb::MessageParser<ReservedNames> _parser = new pb::MessageParser<ReservedNames>(() => new ReservedNames());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1205,11 +1240,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Types_ = input.ReadInt32();
@@ -1230,7 +1270,7 @@
/// <summary>
/// Force a nested type called Types
/// </summary>
- public sealed partial class SomeNestedType : pb::IMessage<SomeNestedType> {
+ public sealed partial class SomeNestedType : pb::IMessage<SomeNestedType>, pb::IBufferMessage {
private static readonly pb::MessageParser<SomeNestedType> _parser = new pb::MessageParser<SomeNestedType>(() => new SomeNestedType());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1319,11 +1359,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -1348,7 +1393,7 @@
/// Alternatively, consider just adding this to
/// unittest_proto3.proto if multiple platforms want it.
/// </summary>
- public sealed partial class TestJsonFieldOrdering : pb::IMessage<TestJsonFieldOrdering> {
+ public sealed partial class TestJsonFieldOrdering : pb::IMessage<TestJsonFieldOrdering>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestJsonFieldOrdering> _parser = new pb::MessageParser<TestJsonFieldOrdering>(() => new TestJsonFieldOrdering());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1643,11 +1688,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
PlainString = input.ReadString();
@@ -1679,7 +1729,7 @@
}
- public sealed partial class TestJsonName : pb::IMessage<TestJsonName> {
+ public sealed partial class TestJsonName : pb::IMessage<TestJsonName>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestJsonName> _parser = new pb::MessageParser<TestJsonName>(() => new TestJsonName());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1843,11 +1893,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -1872,7 +1927,7 @@
/// oneof case, which is itself a message type, the submessages should
/// be merged.
/// </summary>
- public sealed partial class OneofMerging : pb::IMessage<OneofMerging> {
+ public sealed partial class OneofMerging : pb::IMessage<OneofMerging>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneofMerging> _parser = new pb::MessageParser<OneofMerging>(() => new OneofMerging());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2043,11 +2098,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Text = input.ReadString();
@@ -2070,7 +2130,7 @@
/// <summary>Container for nested types declared in the OneofMerging message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class Nested : pb::IMessage<Nested> {
+ public sealed partial class Nested : pb::IMessage<Nested>, pb::IBufferMessage {
private static readonly pb::MessageParser<Nested> _parser = new pb::MessageParser<Nested>(() => new Nested());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2207,11 +2267,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
X = input.ReadInt32();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3.cs
index 2f489ad..5d0ea86 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3.cs
@@ -254,7 +254,7 @@
/// This proto includes every type of field in both singular and repeated
/// forms.
/// </summary>
- public sealed partial class TestAllTypes : pb::IMessage<TestAllTypes> {
+ public sealed partial class TestAllTypes : pb::IMessage<TestAllTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestAllTypes> _parser = new pb::MessageParser<TestAllTypes>(() => new TestAllTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1383,11 +1383,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
SingleInt32 = input.ReadInt32();
@@ -1491,106 +1496,106 @@
}
case 250:
case 248: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
case 258:
case 256: {
- repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec);
+ repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec);
break;
}
case 266:
case 264: {
- repeatedUint32_.AddEntriesFrom(input, _repeated_repeatedUint32_codec);
+ repeatedUint32_.AddEntriesFrom(ref input, _repeated_repeatedUint32_codec);
break;
}
case 274:
case 272: {
- repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec);
+ repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec);
break;
}
case 282:
case 280: {
- repeatedSint32_.AddEntriesFrom(input, _repeated_repeatedSint32_codec);
+ repeatedSint32_.AddEntriesFrom(ref input, _repeated_repeatedSint32_codec);
break;
}
case 290:
case 288: {
- repeatedSint64_.AddEntriesFrom(input, _repeated_repeatedSint64_codec);
+ repeatedSint64_.AddEntriesFrom(ref input, _repeated_repeatedSint64_codec);
break;
}
case 298:
case 301: {
- repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec);
+ repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec);
break;
}
case 306:
case 305: {
- repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec);
+ repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec);
break;
}
case 314:
case 317: {
- repeatedSfixed32_.AddEntriesFrom(input, _repeated_repeatedSfixed32_codec);
+ repeatedSfixed32_.AddEntriesFrom(ref input, _repeated_repeatedSfixed32_codec);
break;
}
case 322:
case 321: {
- repeatedSfixed64_.AddEntriesFrom(input, _repeated_repeatedSfixed64_codec);
+ repeatedSfixed64_.AddEntriesFrom(ref input, _repeated_repeatedSfixed64_codec);
break;
}
case 330:
case 333: {
- repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec);
+ repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec);
break;
}
case 338:
case 337: {
- repeatedDouble_.AddEntriesFrom(input, _repeated_repeatedDouble_codec);
+ repeatedDouble_.AddEntriesFrom(ref input, _repeated_repeatedDouble_codec);
break;
}
case 346:
case 344: {
- repeatedBool_.AddEntriesFrom(input, _repeated_repeatedBool_codec);
+ repeatedBool_.AddEntriesFrom(ref input, _repeated_repeatedBool_codec);
break;
}
case 354: {
- repeatedString_.AddEntriesFrom(input, _repeated_repeatedString_codec);
+ repeatedString_.AddEntriesFrom(ref input, _repeated_repeatedString_codec);
break;
}
case 362: {
- repeatedBytes_.AddEntriesFrom(input, _repeated_repeatedBytes_codec);
+ repeatedBytes_.AddEntriesFrom(ref input, _repeated_repeatedBytes_codec);
break;
}
case 386: {
- repeatedNestedMessage_.AddEntriesFrom(input, _repeated_repeatedNestedMessage_codec);
+ repeatedNestedMessage_.AddEntriesFrom(ref input, _repeated_repeatedNestedMessage_codec);
break;
}
case 394: {
- repeatedForeignMessage_.AddEntriesFrom(input, _repeated_repeatedForeignMessage_codec);
+ repeatedForeignMessage_.AddEntriesFrom(ref input, _repeated_repeatedForeignMessage_codec);
break;
}
case 402: {
- repeatedImportMessage_.AddEntriesFrom(input, _repeated_repeatedImportMessage_codec);
+ repeatedImportMessage_.AddEntriesFrom(ref input, _repeated_repeatedImportMessage_codec);
break;
}
case 410:
case 408: {
- repeatedNestedEnum_.AddEntriesFrom(input, _repeated_repeatedNestedEnum_codec);
+ repeatedNestedEnum_.AddEntriesFrom(ref input, _repeated_repeatedNestedEnum_codec);
break;
}
case 418:
case 416: {
- repeatedForeignEnum_.AddEntriesFrom(input, _repeated_repeatedForeignEnum_codec);
+ repeatedForeignEnum_.AddEntriesFrom(ref input, _repeated_repeatedForeignEnum_codec);
break;
}
case 426:
case 424: {
- repeatedImportEnum_.AddEntriesFrom(input, _repeated_repeatedImportEnum_codec);
+ repeatedImportEnum_.AddEntriesFrom(ref input, _repeated_repeatedImportEnum_codec);
break;
}
case 434: {
- repeatedPublicImportMessage_.AddEntriesFrom(input, _repeated_repeatedPublicImportMessage_codec);
+ repeatedPublicImportMessage_.AddEntriesFrom(ref input, _repeated_repeatedPublicImportMessage_codec);
break;
}
case 888: {
@@ -1633,7 +1638,7 @@
[pbr::OriginalName("NEG")] Neg = -1,
}
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1751,11 +1756,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Bb = input.ReadInt32();
@@ -1773,9 +1783,9 @@
}
/// <summary>
- /// This proto includes a recusively nested message.
+ /// This proto includes a recursively nested message.
/// </summary>
- public sealed partial class NestedTestAllTypes : pb::IMessage<NestedTestAllTypes> {
+ public sealed partial class NestedTestAllTypes : pb::IMessage<NestedTestAllTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedTestAllTypes> _parser = new pb::MessageParser<NestedTestAllTypes>(() => new NestedTestAllTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1934,11 +1944,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (child_ == null) {
@@ -1955,7 +1970,7 @@
break;
}
case 26: {
- repeatedChild_.AddEntriesFrom(input, _repeated_repeatedChild_codec);
+ repeatedChild_.AddEntriesFrom(ref input, _repeated_repeatedChild_codec);
break;
}
}
@@ -1964,7 +1979,7 @@
}
- public sealed partial class TestDeprecatedFields : pb::IMessage<TestDeprecatedFields> {
+ public sealed partial class TestDeprecatedFields : pb::IMessage<TestDeprecatedFields>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestDeprecatedFields> _parser = new pb::MessageParser<TestDeprecatedFields>(() => new TestDeprecatedFields());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2078,11 +2093,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
DeprecatedInt32 = input.ReadInt32();
@@ -2098,7 +2118,7 @@
/// Define these after TestAllTypes to make sure the compiler can handle
/// that.
/// </summary>
- public sealed partial class ForeignMessage : pb::IMessage<ForeignMessage> {
+ public sealed partial class ForeignMessage : pb::IMessage<ForeignMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<ForeignMessage> _parser = new pb::MessageParser<ForeignMessage>(() => new ForeignMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2211,11 +2231,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
C = input.ReadInt32();
@@ -2227,7 +2252,7 @@
}
- public sealed partial class TestReservedFields : pb::IMessage<TestReservedFields> {
+ public sealed partial class TestReservedFields : pb::IMessage<TestReservedFields>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestReservedFields> _parser = new pb::MessageParser<TestReservedFields>(() => new TestReservedFields());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2316,11 +2341,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -2331,7 +2361,7 @@
/// <summary>
/// Test that we can use NestedMessage from outside TestAllTypes.
/// </summary>
- public sealed partial class TestForeignNested : pb::IMessage<TestForeignNested> {
+ public sealed partial class TestForeignNested : pb::IMessage<TestForeignNested>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestForeignNested> _parser = new pb::MessageParser<TestForeignNested>(() => new TestForeignNested());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2447,11 +2477,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (foreignNested_ == null) {
@@ -2469,7 +2504,7 @@
/// <summary>
/// Test that really large tag numbers don't break anything.
/// </summary>
- public sealed partial class TestReallyLargeTagNumber : pb::IMessage<TestReallyLargeTagNumber> {
+ public sealed partial class TestReallyLargeTagNumber : pb::IMessage<TestReallyLargeTagNumber>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestReallyLargeTagNumber> _parser = new pb::MessageParser<TestReallyLargeTagNumber>(() => new TestReallyLargeTagNumber());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2610,11 +2645,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
A = input.ReadInt32();
@@ -2630,7 +2670,7 @@
}
- public sealed partial class TestRecursiveMessage : pb::IMessage<TestRecursiveMessage> {
+ public sealed partial class TestRecursiveMessage : pb::IMessage<TestRecursiveMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRecursiveMessage> _parser = new pb::MessageParser<TestRecursiveMessage>(() => new TestRecursiveMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2770,11 +2810,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (a_ == null) {
@@ -2796,7 +2841,7 @@
/// <summary>
/// Test that mutual recursion works.
/// </summary>
- public sealed partial class TestMutualRecursionA : pb::IMessage<TestMutualRecursionA> {
+ public sealed partial class TestMutualRecursionA : pb::IMessage<TestMutualRecursionA>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMutualRecursionA> _parser = new pb::MessageParser<TestMutualRecursionA>(() => new TestMutualRecursionA());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2912,11 +2957,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (bb_ == null) {
@@ -2931,7 +2981,7 @@
}
- public sealed partial class TestMutualRecursionB : pb::IMessage<TestMutualRecursionB> {
+ public sealed partial class TestMutualRecursionB : pb::IMessage<TestMutualRecursionB>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestMutualRecursionB> _parser = new pb::MessageParser<TestMutualRecursionB>(() => new TestMutualRecursionB());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3071,11 +3121,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (a_ == null) {
@@ -3094,7 +3149,7 @@
}
- public sealed partial class TestEnumAllowAlias : pb::IMessage<TestEnumAllowAlias> {
+ public sealed partial class TestEnumAllowAlias : pb::IMessage<TestEnumAllowAlias>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestEnumAllowAlias> _parser = new pb::MessageParser<TestEnumAllowAlias>(() => new TestEnumAllowAlias());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3207,11 +3262,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Value = (global::Google.Protobuf.TestProtos.TestEnumWithDupValue) input.ReadEnum();
@@ -3227,7 +3287,7 @@
/// Test message with CamelCase field names. This violates Protocol Buffer
/// standard style.
/// </summary>
- public sealed partial class TestCamelCaseFieldNames : pb::IMessage<TestCamelCaseFieldNames> {
+ public sealed partial class TestCamelCaseFieldNames : pb::IMessage<TestCamelCaseFieldNames>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestCamelCaseFieldNames> _parser = new pb::MessageParser<TestCamelCaseFieldNames>(() => new TestCamelCaseFieldNames());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3479,11 +3539,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
PrimitiveField = input.ReadInt32();
@@ -3506,20 +3571,20 @@
}
case 58:
case 56: {
- repeatedPrimitiveField_.AddEntriesFrom(input, _repeated_repeatedPrimitiveField_codec);
+ repeatedPrimitiveField_.AddEntriesFrom(ref input, _repeated_repeatedPrimitiveField_codec);
break;
}
case 66: {
- repeatedStringField_.AddEntriesFrom(input, _repeated_repeatedStringField_codec);
+ repeatedStringField_.AddEntriesFrom(ref input, _repeated_repeatedStringField_codec);
break;
}
case 74:
case 72: {
- repeatedEnumField_.AddEntriesFrom(input, _repeated_repeatedEnumField_codec);
+ repeatedEnumField_.AddEntriesFrom(ref input, _repeated_repeatedEnumField_codec);
break;
}
case 82: {
- repeatedMessageField_.AddEntriesFrom(input, _repeated_repeatedMessageField_codec);
+ repeatedMessageField_.AddEntriesFrom(ref input, _repeated_repeatedMessageField_codec);
break;
}
}
@@ -3532,7 +3597,7 @@
/// We list fields out of order, to ensure that we're using field number and not
/// field index to determine serialization order.
/// </summary>
- public sealed partial class TestFieldOrderings : pb::IMessage<TestFieldOrderings> {
+ public sealed partial class TestFieldOrderings : pb::IMessage<TestFieldOrderings>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestFieldOrderings> _parser = new pb::MessageParser<TestFieldOrderings>(() => new TestFieldOrderings());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3720,11 +3785,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
MyInt = input.ReadInt64();
@@ -3753,7 +3823,7 @@
/// <summary>Container for nested types declared in the TestFieldOrderings message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class NestedMessage : pb::IMessage<NestedMessage> {
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3895,11 +3965,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Bb = input.ReadInt32();
@@ -3920,7 +3995,7 @@
}
- public sealed partial class SparseEnumMessage : pb::IMessage<SparseEnumMessage> {
+ public sealed partial class SparseEnumMessage : pb::IMessage<SparseEnumMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<SparseEnumMessage> _parser = new pb::MessageParser<SparseEnumMessage>(() => new SparseEnumMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4033,11 +4108,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
SparseEnum = (global::Google.Protobuf.TestProtos.TestSparseEnum) input.ReadEnum();
@@ -4052,7 +4132,7 @@
/// <summary>
/// Test String and Bytes: string is for valid UTF-8 strings
/// </summary>
- public sealed partial class OneString : pb::IMessage<OneString> {
+ public sealed partial class OneString : pb::IMessage<OneString>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneString> _parser = new pb::MessageParser<OneString>(() => new OneString());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4165,11 +4245,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Data = input.ReadString();
@@ -4181,7 +4266,7 @@
}
- public sealed partial class MoreString : pb::IMessage<MoreString> {
+ public sealed partial class MoreString : pb::IMessage<MoreString>, pb::IBufferMessage {
private static readonly pb::MessageParser<MoreString> _parser = new pb::MessageParser<MoreString>(() => new MoreString());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4286,14 +4371,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- data_.AddEntriesFrom(input, _repeated_data_codec);
+ data_.AddEntriesFrom(ref input, _repeated_data_codec);
break;
}
}
@@ -4302,7 +4392,7 @@
}
- public sealed partial class OneBytes : pb::IMessage<OneBytes> {
+ public sealed partial class OneBytes : pb::IMessage<OneBytes>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneBytes> _parser = new pb::MessageParser<OneBytes>(() => new OneBytes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4415,11 +4505,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Data = input.ReadBytes();
@@ -4431,7 +4526,7 @@
}
- public sealed partial class MoreBytes : pb::IMessage<MoreBytes> {
+ public sealed partial class MoreBytes : pb::IMessage<MoreBytes>, pb::IBufferMessage {
private static readonly pb::MessageParser<MoreBytes> _parser = new pb::MessageParser<MoreBytes>(() => new MoreBytes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4544,11 +4639,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Data = input.ReadBytes();
@@ -4563,7 +4663,7 @@
/// <summary>
/// Test int32, uint32, int64, uint64, and bool are all compatible
/// </summary>
- public sealed partial class Int32Message : pb::IMessage<Int32Message> {
+ public sealed partial class Int32Message : pb::IMessage<Int32Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Int32Message> _parser = new pb::MessageParser<Int32Message>(() => new Int32Message());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4676,11 +4776,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadInt32();
@@ -4692,7 +4797,7 @@
}
- public sealed partial class Uint32Message : pb::IMessage<Uint32Message> {
+ public sealed partial class Uint32Message : pb::IMessage<Uint32Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Uint32Message> _parser = new pb::MessageParser<Uint32Message>(() => new Uint32Message());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4805,11 +4910,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadUInt32();
@@ -4821,7 +4931,7 @@
}
- public sealed partial class Int64Message : pb::IMessage<Int64Message> {
+ public sealed partial class Int64Message : pb::IMessage<Int64Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Int64Message> _parser = new pb::MessageParser<Int64Message>(() => new Int64Message());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -4934,11 +5044,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadInt64();
@@ -4950,7 +5065,7 @@
}
- public sealed partial class Uint64Message : pb::IMessage<Uint64Message> {
+ public sealed partial class Uint64Message : pb::IMessage<Uint64Message>, pb::IBufferMessage {
private static readonly pb::MessageParser<Uint64Message> _parser = new pb::MessageParser<Uint64Message>(() => new Uint64Message());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5063,11 +5178,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadUInt64();
@@ -5079,7 +5199,7 @@
}
- public sealed partial class BoolMessage : pb::IMessage<BoolMessage> {
+ public sealed partial class BoolMessage : pb::IMessage<BoolMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<BoolMessage> _parser = new pb::MessageParser<BoolMessage>(() => new BoolMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5192,11 +5312,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Data = input.ReadBool();
@@ -5211,7 +5336,7 @@
/// <summary>
/// Test oneofs.
/// </summary>
- public sealed partial class TestOneof : pb::IMessage<TestOneof> {
+ public sealed partial class TestOneof : pb::IMessage<TestOneof>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestOneof> _parser = new pb::MessageParser<TestOneof>(() => new TestOneof());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5409,11 +5534,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
FooInt = input.ReadInt32();
@@ -5438,7 +5568,7 @@
}
- public sealed partial class TestPackedTypes : pb::IMessage<TestPackedTypes> {
+ public sealed partial class TestPackedTypes : pb::IMessage<TestPackedTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestPackedTypes> _parser = new pb::MessageParser<TestPackedTypes>(() => new TestPackedTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -5751,80 +5881,85 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 722:
case 720: {
- packedInt32_.AddEntriesFrom(input, _repeated_packedInt32_codec);
+ packedInt32_.AddEntriesFrom(ref input, _repeated_packedInt32_codec);
break;
}
case 730:
case 728: {
- packedInt64_.AddEntriesFrom(input, _repeated_packedInt64_codec);
+ packedInt64_.AddEntriesFrom(ref input, _repeated_packedInt64_codec);
break;
}
case 738:
case 736: {
- packedUint32_.AddEntriesFrom(input, _repeated_packedUint32_codec);
+ packedUint32_.AddEntriesFrom(ref input, _repeated_packedUint32_codec);
break;
}
case 746:
case 744: {
- packedUint64_.AddEntriesFrom(input, _repeated_packedUint64_codec);
+ packedUint64_.AddEntriesFrom(ref input, _repeated_packedUint64_codec);
break;
}
case 754:
case 752: {
- packedSint32_.AddEntriesFrom(input, _repeated_packedSint32_codec);
+ packedSint32_.AddEntriesFrom(ref input, _repeated_packedSint32_codec);
break;
}
case 762:
case 760: {
- packedSint64_.AddEntriesFrom(input, _repeated_packedSint64_codec);
+ packedSint64_.AddEntriesFrom(ref input, _repeated_packedSint64_codec);
break;
}
case 770:
case 773: {
- packedFixed32_.AddEntriesFrom(input, _repeated_packedFixed32_codec);
+ packedFixed32_.AddEntriesFrom(ref input, _repeated_packedFixed32_codec);
break;
}
case 778:
case 777: {
- packedFixed64_.AddEntriesFrom(input, _repeated_packedFixed64_codec);
+ packedFixed64_.AddEntriesFrom(ref input, _repeated_packedFixed64_codec);
break;
}
case 786:
case 789: {
- packedSfixed32_.AddEntriesFrom(input, _repeated_packedSfixed32_codec);
+ packedSfixed32_.AddEntriesFrom(ref input, _repeated_packedSfixed32_codec);
break;
}
case 794:
case 793: {
- packedSfixed64_.AddEntriesFrom(input, _repeated_packedSfixed64_codec);
+ packedSfixed64_.AddEntriesFrom(ref input, _repeated_packedSfixed64_codec);
break;
}
case 802:
case 805: {
- packedFloat_.AddEntriesFrom(input, _repeated_packedFloat_codec);
+ packedFloat_.AddEntriesFrom(ref input, _repeated_packedFloat_codec);
break;
}
case 810:
case 809: {
- packedDouble_.AddEntriesFrom(input, _repeated_packedDouble_codec);
+ packedDouble_.AddEntriesFrom(ref input, _repeated_packedDouble_codec);
break;
}
case 818:
case 816: {
- packedBool_.AddEntriesFrom(input, _repeated_packedBool_codec);
+ packedBool_.AddEntriesFrom(ref input, _repeated_packedBool_codec);
break;
}
case 826:
case 824: {
- packedEnum_.AddEntriesFrom(input, _repeated_packedEnum_codec);
+ packedEnum_.AddEntriesFrom(ref input, _repeated_packedEnum_codec);
break;
}
}
@@ -5837,7 +5972,7 @@
/// A message with the same fields as TestPackedTypes, but without packing. Used
/// to test packed <-> unpacked wire compatibility.
/// </summary>
- public sealed partial class TestUnpackedTypes : pb::IMessage<TestUnpackedTypes> {
+ public sealed partial class TestUnpackedTypes : pb::IMessage<TestUnpackedTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestUnpackedTypes> _parser = new pb::MessageParser<TestUnpackedTypes>(() => new TestUnpackedTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6150,80 +6285,85 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 722:
case 720: {
- unpackedInt32_.AddEntriesFrom(input, _repeated_unpackedInt32_codec);
+ unpackedInt32_.AddEntriesFrom(ref input, _repeated_unpackedInt32_codec);
break;
}
case 730:
case 728: {
- unpackedInt64_.AddEntriesFrom(input, _repeated_unpackedInt64_codec);
+ unpackedInt64_.AddEntriesFrom(ref input, _repeated_unpackedInt64_codec);
break;
}
case 738:
case 736: {
- unpackedUint32_.AddEntriesFrom(input, _repeated_unpackedUint32_codec);
+ unpackedUint32_.AddEntriesFrom(ref input, _repeated_unpackedUint32_codec);
break;
}
case 746:
case 744: {
- unpackedUint64_.AddEntriesFrom(input, _repeated_unpackedUint64_codec);
+ unpackedUint64_.AddEntriesFrom(ref input, _repeated_unpackedUint64_codec);
break;
}
case 754:
case 752: {
- unpackedSint32_.AddEntriesFrom(input, _repeated_unpackedSint32_codec);
+ unpackedSint32_.AddEntriesFrom(ref input, _repeated_unpackedSint32_codec);
break;
}
case 762:
case 760: {
- unpackedSint64_.AddEntriesFrom(input, _repeated_unpackedSint64_codec);
+ unpackedSint64_.AddEntriesFrom(ref input, _repeated_unpackedSint64_codec);
break;
}
case 770:
case 773: {
- unpackedFixed32_.AddEntriesFrom(input, _repeated_unpackedFixed32_codec);
+ unpackedFixed32_.AddEntriesFrom(ref input, _repeated_unpackedFixed32_codec);
break;
}
case 778:
case 777: {
- unpackedFixed64_.AddEntriesFrom(input, _repeated_unpackedFixed64_codec);
+ unpackedFixed64_.AddEntriesFrom(ref input, _repeated_unpackedFixed64_codec);
break;
}
case 786:
case 789: {
- unpackedSfixed32_.AddEntriesFrom(input, _repeated_unpackedSfixed32_codec);
+ unpackedSfixed32_.AddEntriesFrom(ref input, _repeated_unpackedSfixed32_codec);
break;
}
case 794:
case 793: {
- unpackedSfixed64_.AddEntriesFrom(input, _repeated_unpackedSfixed64_codec);
+ unpackedSfixed64_.AddEntriesFrom(ref input, _repeated_unpackedSfixed64_codec);
break;
}
case 802:
case 805: {
- unpackedFloat_.AddEntriesFrom(input, _repeated_unpackedFloat_codec);
+ unpackedFloat_.AddEntriesFrom(ref input, _repeated_unpackedFloat_codec);
break;
}
case 810:
case 809: {
- unpackedDouble_.AddEntriesFrom(input, _repeated_unpackedDouble_codec);
+ unpackedDouble_.AddEntriesFrom(ref input, _repeated_unpackedDouble_codec);
break;
}
case 818:
case 816: {
- unpackedBool_.AddEntriesFrom(input, _repeated_unpackedBool_codec);
+ unpackedBool_.AddEntriesFrom(ref input, _repeated_unpackedBool_codec);
break;
}
case 826:
case 824: {
- unpackedEnum_.AddEntriesFrom(input, _repeated_unpackedEnum_codec);
+ unpackedEnum_.AddEntriesFrom(ref input, _repeated_unpackedEnum_codec);
break;
}
}
@@ -6232,7 +6372,7 @@
}
- public sealed partial class TestRepeatedScalarDifferentTagSizes : pb::IMessage<TestRepeatedScalarDifferentTagSizes> {
+ public sealed partial class TestRepeatedScalarDifferentTagSizes : pb::IMessage<TestRepeatedScalarDifferentTagSizes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestRepeatedScalarDifferentTagSizes> _parser = new pb::MessageParser<TestRepeatedScalarDifferentTagSizes>(() => new TestRepeatedScalarDifferentTagSizes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6431,40 +6571,45 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 98:
case 101: {
- repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec);
+ repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec);
break;
}
case 106:
case 104: {
- repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec);
+ repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec);
break;
}
case 16370:
case 16369: {
- repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec);
+ repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec);
break;
}
case 16378:
case 16376: {
- repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec);
+ repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec);
break;
}
case 2097138:
case 2097141: {
- repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec);
+ repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec);
break;
}
case 2097146:
case 2097144: {
- repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec);
+ repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec);
break;
}
}
@@ -6473,7 +6618,7 @@
}
- public sealed partial class TestCommentInjectionMessage : pb::IMessage<TestCommentInjectionMessage> {
+ public sealed partial class TestCommentInjectionMessage : pb::IMessage<TestCommentInjectionMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestCommentInjectionMessage> _parser = new pb::MessageParser<TestCommentInjectionMessage>(() => new TestCommentInjectionMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6589,11 +6734,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
A = input.ReadString();
@@ -6608,7 +6758,7 @@
/// <summary>
/// Test that RPC services work.
/// </summary>
- public sealed partial class FooRequest : pb::IMessage<FooRequest> {
+ public sealed partial class FooRequest : pb::IMessage<FooRequest>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooRequest> _parser = new pb::MessageParser<FooRequest>(() => new FooRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6697,11 +6847,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -6709,7 +6864,7 @@
}
- public sealed partial class FooResponse : pb::IMessage<FooResponse> {
+ public sealed partial class FooResponse : pb::IMessage<FooResponse>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooResponse> _parser = new pb::MessageParser<FooResponse>(() => new FooResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6798,11 +6953,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -6810,7 +6970,7 @@
}
- public sealed partial class FooClientMessage : pb::IMessage<FooClientMessage> {
+ public sealed partial class FooClientMessage : pb::IMessage<FooClientMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooClientMessage> _parser = new pb::MessageParser<FooClientMessage>(() => new FooClientMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -6899,11 +7059,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -6911,7 +7076,7 @@
}
- public sealed partial class FooServerMessage : pb::IMessage<FooServerMessage> {
+ public sealed partial class FooServerMessage : pb::IMessage<FooServerMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<FooServerMessage> _parser = new pb::MessageParser<FooServerMessage>(() => new FooServerMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7000,11 +7165,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -7012,7 +7182,7 @@
}
- public sealed partial class BarRequest : pb::IMessage<BarRequest> {
+ public sealed partial class BarRequest : pb::IMessage<BarRequest>, pb::IBufferMessage {
private static readonly pb::MessageParser<BarRequest> _parser = new pb::MessageParser<BarRequest>(() => new BarRequest());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7101,11 +7271,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -7113,7 +7288,7 @@
}
- public sealed partial class BarResponse : pb::IMessage<BarResponse> {
+ public sealed partial class BarResponse : pb::IMessage<BarResponse>, pb::IBufferMessage {
private static readonly pb::MessageParser<BarResponse> _parser = new pb::MessageParser<BarResponse>(() => new BarResponse());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7202,11 +7377,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -7214,7 +7394,7 @@
}
- public sealed partial class TestEmptyMessage : pb::IMessage<TestEmptyMessage> {
+ public sealed partial class TestEmptyMessage : pb::IMessage<TestEmptyMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestEmptyMessage> _parser = new pb::MessageParser<TestEmptyMessage>(() => new TestEmptyMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7303,11 +7483,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
@@ -7318,7 +7503,7 @@
/// <summary>
/// This is a leading comment
/// </summary>
- public sealed partial class CommentMessage : pb::IMessage<CommentMessage> {
+ public sealed partial class CommentMessage : pb::IMessage<CommentMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<CommentMessage> _parser = new pb::MessageParser<CommentMessage>(() => new CommentMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7434,11 +7619,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Text = input.ReadString();
@@ -7465,7 +7655,7 @@
/// <summary>
/// Leading nested message comment
/// </summary>
- public sealed partial class NestedCommentMessage : pb::IMessage<NestedCommentMessage> {
+ public sealed partial class NestedCommentMessage : pb::IMessage<NestedCommentMessage>, pb::IBufferMessage {
private static readonly pb::MessageParser<NestedCommentMessage> _parser = new pb::MessageParser<NestedCommentMessage>(() => new NestedCommentMessage());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7581,11 +7771,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
NestedText = input.ReadString();
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3Optional.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3Optional.cs
new file mode 100644
index 0000000..21e55f7
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestProto3Optional.cs
@@ -0,0 +1,1142 @@
+// <auto-generated>
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/unittest_proto3_optional.proto
+// </auto-generated>
+#pragma warning disable 1591, 0612, 3021
+#region Designer generated code
+
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
+using scg = global::System.Collections.Generic;
+namespace ProtobufUnittest {
+
+ /// <summary>Holder for reflection information generated from google/protobuf/unittest_proto3_optional.proto</summary>
+ public static partial class UnittestProto3OptionalReflection {
+
+ #region Descriptor
+ /// <summary>File descriptor for google/protobuf/unittest_proto3_optional.proto</summary>
+ public static pbr::FileDescriptor Descriptor {
+ get { return descriptor; }
+ }
+ private static pbr::FileDescriptor descriptor;
+
+ static UnittestProto3OptionalReflection() {
+ byte[] descriptorData = global::System.Convert.FromBase64String(
+ string.Concat(
+ "Ci5nb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfcHJvdG8zX29wdGlvbmFsLnBy",
+ "b3RvEhFwcm90b2J1Zl91bml0dGVzdCKxCgoSVGVzdFByb3RvM09wdGlvbmFs",
+ "EhsKDm9wdGlvbmFsX2ludDMyGAEgASgFSACIAQESGwoOb3B0aW9uYWxfaW50",
+ "NjQYAiABKANIAYgBARIcCg9vcHRpb25hbF91aW50MzIYAyABKA1IAogBARIc",
+ "Cg9vcHRpb25hbF91aW50NjQYBCABKARIA4gBARIcCg9vcHRpb25hbF9zaW50",
+ "MzIYBSABKBFIBIgBARIcCg9vcHRpb25hbF9zaW50NjQYBiABKBJIBYgBARId",
+ "ChBvcHRpb25hbF9maXhlZDMyGAcgASgHSAaIAQESHQoQb3B0aW9uYWxfZml4",
+ "ZWQ2NBgIIAEoBkgHiAEBEh4KEW9wdGlvbmFsX3NmaXhlZDMyGAkgASgPSAiI",
+ "AQESHgoRb3B0aW9uYWxfc2ZpeGVkNjQYCiABKBBICYgBARIbCg5vcHRpb25h",
+ "bF9mbG9hdBgLIAEoAkgKiAEBEhwKD29wdGlvbmFsX2RvdWJsZRgMIAEoAUgL",
+ "iAEBEhoKDW9wdGlvbmFsX2Jvb2wYDSABKAhIDIgBARIcCg9vcHRpb25hbF9z",
+ "dHJpbmcYDiABKAlIDYgBARIbCg5vcHRpb25hbF9ieXRlcxgPIAEoDEgOiAEB",
+ "Eh4KDW9wdGlvbmFsX2NvcmQYECABKAlCAggBSA+IAQESWQoXb3B0aW9uYWxf",
+ "bmVzdGVkX21lc3NhZ2UYEiABKAsyMy5wcm90b2J1Zl91bml0dGVzdC5UZXN0",
+ "UHJvdG8zT3B0aW9uYWwuTmVzdGVkTWVzc2FnZUgQiAEBElkKE2xhenlfbmVz",
+ "dGVkX21lc3NhZ2UYEyABKAsyMy5wcm90b2J1Zl91bml0dGVzdC5UZXN0UHJv",
+ "dG8zT3B0aW9uYWwuTmVzdGVkTWVzc2FnZUICKAFIEYgBARJTChRvcHRpb25h",
+ "bF9uZXN0ZWRfZW51bRgVIAEoDjIwLnByb3RvYnVmX3VuaXR0ZXN0LlRlc3RQ",
+ "cm90bzNPcHRpb25hbC5OZXN0ZWRFbnVtSBKIAQESFgoOc2luZ3VsYXJfaW50",
+ "MzIYFiABKAUSFgoOc2luZ3VsYXJfaW50NjQYFyABKAMaJwoNTmVzdGVkTWVz",
+ "c2FnZRIPCgJiYhgBIAEoBUgAiAEBQgUKA19iYiJKCgpOZXN0ZWRFbnVtEg8K",
+ "C1VOU1BFQ0lGSUVEEAASBwoDRk9PEAESBwoDQkFSEAISBwoDQkFaEAMSEAoD",
+ "TkVHEP///////////wFCEQoPX29wdGlvbmFsX2ludDMyQhEKD19vcHRpb25h",
+ "bF9pbnQ2NEISChBfb3B0aW9uYWxfdWludDMyQhIKEF9vcHRpb25hbF91aW50",
+ "NjRCEgoQX29wdGlvbmFsX3NpbnQzMkISChBfb3B0aW9uYWxfc2ludDY0QhMK",
+ "EV9vcHRpb25hbF9maXhlZDMyQhMKEV9vcHRpb25hbF9maXhlZDY0QhQKEl9v",
+ "cHRpb25hbF9zZml4ZWQzMkIUChJfb3B0aW9uYWxfc2ZpeGVkNjRCEQoPX29w",
+ "dGlvbmFsX2Zsb2F0QhIKEF9vcHRpb25hbF9kb3VibGVCEAoOX29wdGlvbmFs",
+ "X2Jvb2xCEgoQX29wdGlvbmFsX3N0cmluZ0IRCg9fb3B0aW9uYWxfYnl0ZXNC",
+ "EAoOX29wdGlvbmFsX2NvcmRCGgoYX29wdGlvbmFsX25lc3RlZF9tZXNzYWdl",
+ "QhYKFF9sYXp5X25lc3RlZF9tZXNzYWdlQhcKFV9vcHRpb25hbF9uZXN0ZWRf",
+ "ZW51bUIlCiFjb20uZ29vZ2xlLnByb3RvYnVmLnRlc3RpbmcucHJvdG9QAWIG",
+ "cHJvdG8z"));
+ descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
+ new pbr::FileDescriptor[] { },
+ new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
+ new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufUnittest.TestProto3Optional), global::ProtobufUnittest.TestProto3Optional.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalCord", "OptionalNestedMessage", "LazyNestedMessage", "OptionalNestedEnum", "SingularInt32", "SingularInt64" }, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalCord", "OptionalNestedMessage", "LazyNestedMessage", "OptionalNestedEnum" }, new[]{ typeof(global::ProtobufUnittest.TestProto3Optional.Types.NestedEnum) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage), global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage.Parser, new[]{ "Bb" }, new[]{ "Bb" }, null, null, null)})
+ }));
+ }
+ #endregion
+
+ }
+ #region Messages
+ public sealed partial class TestProto3Optional : pb::IMessage<TestProto3Optional>, pb::IBufferMessage {
+ private static readonly pb::MessageParser<TestProto3Optional> _parser = new pb::MessageParser<TestProto3Optional>(() => new TestProto3Optional());
+ private pb::UnknownFieldSet _unknownFields;
+ private int _hasBits0;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<TestProto3Optional> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::ProtobufUnittest.UnittestProto3OptionalReflection.Descriptor.MessageTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestProto3Optional() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestProto3Optional(TestProto3Optional other) : this() {
+ _hasBits0 = other._hasBits0;
+ optionalInt32_ = other.optionalInt32_;
+ optionalInt64_ = other.optionalInt64_;
+ optionalUint32_ = other.optionalUint32_;
+ optionalUint64_ = other.optionalUint64_;
+ optionalSint32_ = other.optionalSint32_;
+ optionalSint64_ = other.optionalSint64_;
+ optionalFixed32_ = other.optionalFixed32_;
+ optionalFixed64_ = other.optionalFixed64_;
+ optionalSfixed32_ = other.optionalSfixed32_;
+ optionalSfixed64_ = other.optionalSfixed64_;
+ optionalFloat_ = other.optionalFloat_;
+ optionalDouble_ = other.optionalDouble_;
+ optionalBool_ = other.optionalBool_;
+ optionalString_ = other.optionalString_;
+ optionalBytes_ = other.optionalBytes_;
+ optionalCord_ = other.optionalCord_;
+ optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null;
+ lazyNestedMessage_ = other.lazyNestedMessage_ != null ? other.lazyNestedMessage_.Clone() : null;
+ optionalNestedEnum_ = other.optionalNestedEnum_;
+ singularInt32_ = other.singularInt32_;
+ singularInt64_ = other.singularInt64_;
+ _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public TestProto3Optional Clone() {
+ return new TestProto3Optional(this);
+ }
+
+ /// <summary>Field number for the "optional_int32" field.</summary>
+ public const int OptionalInt32FieldNumber = 1;
+ private int optionalInt32_;
+ /// <summary>
+ /// Singular
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int OptionalInt32 {
+ get { if ((_hasBits0 & 1) != 0) { return optionalInt32_; } else { return 0; } }
+ set {
+ _hasBits0 |= 1;
+ optionalInt32_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_int32" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalInt32 {
+ get { return (_hasBits0 & 1) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_int32" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalInt32() {
+ _hasBits0 &= ~1;
+ }
+
+ /// <summary>Field number for the "optional_int64" field.</summary>
+ public const int OptionalInt64FieldNumber = 2;
+ private long optionalInt64_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public long OptionalInt64 {
+ get { if ((_hasBits0 & 2) != 0) { return optionalInt64_; } else { return 0L; } }
+ set {
+ _hasBits0 |= 2;
+ optionalInt64_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_int64" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalInt64 {
+ get { return (_hasBits0 & 2) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_int64" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalInt64() {
+ _hasBits0 &= ~2;
+ }
+
+ /// <summary>Field number for the "optional_uint32" field.</summary>
+ public const int OptionalUint32FieldNumber = 3;
+ private uint optionalUint32_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public uint OptionalUint32 {
+ get { if ((_hasBits0 & 4) != 0) { return optionalUint32_; } else { return 0; } }
+ set {
+ _hasBits0 |= 4;
+ optionalUint32_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_uint32" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalUint32 {
+ get { return (_hasBits0 & 4) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_uint32" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalUint32() {
+ _hasBits0 &= ~4;
+ }
+
+ /// <summary>Field number for the "optional_uint64" field.</summary>
+ public const int OptionalUint64FieldNumber = 4;
+ private ulong optionalUint64_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ulong OptionalUint64 {
+ get { if ((_hasBits0 & 8) != 0) { return optionalUint64_; } else { return 0UL; } }
+ set {
+ _hasBits0 |= 8;
+ optionalUint64_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_uint64" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalUint64 {
+ get { return (_hasBits0 & 8) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_uint64" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalUint64() {
+ _hasBits0 &= ~8;
+ }
+
+ /// <summary>Field number for the "optional_sint32" field.</summary>
+ public const int OptionalSint32FieldNumber = 5;
+ private int optionalSint32_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int OptionalSint32 {
+ get { if ((_hasBits0 & 16) != 0) { return optionalSint32_; } else { return 0; } }
+ set {
+ _hasBits0 |= 16;
+ optionalSint32_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_sint32" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalSint32 {
+ get { return (_hasBits0 & 16) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_sint32" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalSint32() {
+ _hasBits0 &= ~16;
+ }
+
+ /// <summary>Field number for the "optional_sint64" field.</summary>
+ public const int OptionalSint64FieldNumber = 6;
+ private long optionalSint64_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public long OptionalSint64 {
+ get { if ((_hasBits0 & 32) != 0) { return optionalSint64_; } else { return 0L; } }
+ set {
+ _hasBits0 |= 32;
+ optionalSint64_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_sint64" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalSint64 {
+ get { return (_hasBits0 & 32) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_sint64" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalSint64() {
+ _hasBits0 &= ~32;
+ }
+
+ /// <summary>Field number for the "optional_fixed32" field.</summary>
+ public const int OptionalFixed32FieldNumber = 7;
+ private uint optionalFixed32_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public uint OptionalFixed32 {
+ get { if ((_hasBits0 & 64) != 0) { return optionalFixed32_; } else { return 0; } }
+ set {
+ _hasBits0 |= 64;
+ optionalFixed32_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_fixed32" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalFixed32 {
+ get { return (_hasBits0 & 64) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_fixed32" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalFixed32() {
+ _hasBits0 &= ~64;
+ }
+
+ /// <summary>Field number for the "optional_fixed64" field.</summary>
+ public const int OptionalFixed64FieldNumber = 8;
+ private ulong optionalFixed64_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ulong OptionalFixed64 {
+ get { if ((_hasBits0 & 128) != 0) { return optionalFixed64_; } else { return 0UL; } }
+ set {
+ _hasBits0 |= 128;
+ optionalFixed64_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_fixed64" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalFixed64 {
+ get { return (_hasBits0 & 128) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_fixed64" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalFixed64() {
+ _hasBits0 &= ~128;
+ }
+
+ /// <summary>Field number for the "optional_sfixed32" field.</summary>
+ public const int OptionalSfixed32FieldNumber = 9;
+ private int optionalSfixed32_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int OptionalSfixed32 {
+ get { if ((_hasBits0 & 256) != 0) { return optionalSfixed32_; } else { return 0; } }
+ set {
+ _hasBits0 |= 256;
+ optionalSfixed32_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_sfixed32" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalSfixed32 {
+ get { return (_hasBits0 & 256) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_sfixed32" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalSfixed32() {
+ _hasBits0 &= ~256;
+ }
+
+ /// <summary>Field number for the "optional_sfixed64" field.</summary>
+ public const int OptionalSfixed64FieldNumber = 10;
+ private long optionalSfixed64_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public long OptionalSfixed64 {
+ get { if ((_hasBits0 & 512) != 0) { return optionalSfixed64_; } else { return 0L; } }
+ set {
+ _hasBits0 |= 512;
+ optionalSfixed64_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_sfixed64" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalSfixed64 {
+ get { return (_hasBits0 & 512) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_sfixed64" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalSfixed64() {
+ _hasBits0 &= ~512;
+ }
+
+ /// <summary>Field number for the "optional_float" field.</summary>
+ public const int OptionalFloatFieldNumber = 11;
+ private float optionalFloat_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public float OptionalFloat {
+ get { if ((_hasBits0 & 1024) != 0) { return optionalFloat_; } else { return 0F; } }
+ set {
+ _hasBits0 |= 1024;
+ optionalFloat_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_float" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalFloat {
+ get { return (_hasBits0 & 1024) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_float" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalFloat() {
+ _hasBits0 &= ~1024;
+ }
+
+ /// <summary>Field number for the "optional_double" field.</summary>
+ public const int OptionalDoubleFieldNumber = 12;
+ private double optionalDouble_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public double OptionalDouble {
+ get { if ((_hasBits0 & 2048) != 0) { return optionalDouble_; } else { return 0D; } }
+ set {
+ _hasBits0 |= 2048;
+ optionalDouble_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_double" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalDouble {
+ get { return (_hasBits0 & 2048) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_double" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalDouble() {
+ _hasBits0 &= ~2048;
+ }
+
+ /// <summary>Field number for the "optional_bool" field.</summary>
+ public const int OptionalBoolFieldNumber = 13;
+ private bool optionalBool_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool OptionalBool {
+ get { if ((_hasBits0 & 4096) != 0) { return optionalBool_; } else { return false; } }
+ set {
+ _hasBits0 |= 4096;
+ optionalBool_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_bool" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalBool {
+ get { return (_hasBits0 & 4096) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_bool" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalBool() {
+ _hasBits0 &= ~4096;
+ }
+
+ /// <summary>Field number for the "optional_string" field.</summary>
+ public const int OptionalStringFieldNumber = 14;
+ private string optionalString_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string OptionalString {
+ get { return optionalString_ ?? ""; }
+ set {
+ optionalString_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+ /// <summary>Gets whether the "optional_string" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalString {
+ get { return optionalString_ != null; }
+ }
+ /// <summary>Clears the value of the "optional_string" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalString() {
+ optionalString_ = null;
+ }
+
+ /// <summary>Field number for the "optional_bytes" field.</summary>
+ public const int OptionalBytesFieldNumber = 15;
+ private pb::ByteString optionalBytes_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public pb::ByteString OptionalBytes {
+ get { return optionalBytes_ ?? pb::ByteString.Empty; }
+ set {
+ optionalBytes_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+ /// <summary>Gets whether the "optional_bytes" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalBytes {
+ get { return optionalBytes_ != null; }
+ }
+ /// <summary>Clears the value of the "optional_bytes" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalBytes() {
+ optionalBytes_ = null;
+ }
+
+ /// <summary>Field number for the "optional_cord" field.</summary>
+ public const int OptionalCordFieldNumber = 16;
+ private string optionalCord_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public string OptionalCord {
+ get { return optionalCord_ ?? ""; }
+ set {
+ optionalCord_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
+ }
+ }
+ /// <summary>Gets whether the "optional_cord" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalCord {
+ get { return optionalCord_ != null; }
+ }
+ /// <summary>Clears the value of the "optional_cord" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalCord() {
+ optionalCord_ = null;
+ }
+
+ /// <summary>Field number for the "optional_nested_message" field.</summary>
+ public const int OptionalNestedMessageFieldNumber = 18;
+ private global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage optionalNestedMessage_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage OptionalNestedMessage {
+ get { return optionalNestedMessage_; }
+ set {
+ optionalNestedMessage_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "lazy_nested_message" field.</summary>
+ public const int LazyNestedMessageFieldNumber = 19;
+ private global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage lazyNestedMessage_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage LazyNestedMessage {
+ get { return lazyNestedMessage_; }
+ set {
+ lazyNestedMessage_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "optional_nested_enum" field.</summary>
+ public const int OptionalNestedEnumFieldNumber = 21;
+ private global::ProtobufUnittest.TestProto3Optional.Types.NestedEnum optionalNestedEnum_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::ProtobufUnittest.TestProto3Optional.Types.NestedEnum OptionalNestedEnum {
+ get { if ((_hasBits0 & 8192) != 0) { return optionalNestedEnum_; } else { return global::ProtobufUnittest.TestProto3Optional.Types.NestedEnum.Unspecified; } }
+ set {
+ _hasBits0 |= 8192;
+ optionalNestedEnum_ = value;
+ }
+ }
+ /// <summary>Gets whether the "optional_nested_enum" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasOptionalNestedEnum {
+ get { return (_hasBits0 & 8192) != 0; }
+ }
+ /// <summary>Clears the value of the "optional_nested_enum" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearOptionalNestedEnum() {
+ _hasBits0 &= ~8192;
+ }
+
+ /// <summary>Field number for the "singular_int32" field.</summary>
+ public const int SingularInt32FieldNumber = 22;
+ private int singularInt32_;
+ /// <summary>
+ /// Add some non-optional fields to verify we can mix them.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int SingularInt32 {
+ get { return singularInt32_; }
+ set {
+ singularInt32_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "singular_int64" field.</summary>
+ public const int SingularInt64FieldNumber = 23;
+ private long singularInt64_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public long SingularInt64 {
+ get { return singularInt64_; }
+ set {
+ singularInt64_ = value;
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as TestProto3Optional);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(TestProto3Optional other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (OptionalInt32 != other.OptionalInt32) return false;
+ if (OptionalInt64 != other.OptionalInt64) return false;
+ if (OptionalUint32 != other.OptionalUint32) return false;
+ if (OptionalUint64 != other.OptionalUint64) return false;
+ if (OptionalSint32 != other.OptionalSint32) return false;
+ if (OptionalSint64 != other.OptionalSint64) return false;
+ if (OptionalFixed32 != other.OptionalFixed32) return false;
+ if (OptionalFixed64 != other.OptionalFixed64) return false;
+ if (OptionalSfixed32 != other.OptionalSfixed32) return false;
+ if (OptionalSfixed64 != other.OptionalSfixed64) return false;
+ if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(OptionalFloat, other.OptionalFloat)) return false;
+ if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(OptionalDouble, other.OptionalDouble)) return false;
+ if (OptionalBool != other.OptionalBool) return false;
+ if (OptionalString != other.OptionalString) return false;
+ if (OptionalBytes != other.OptionalBytes) return false;
+ if (OptionalCord != other.OptionalCord) return false;
+ if (!object.Equals(OptionalNestedMessage, other.OptionalNestedMessage)) return false;
+ if (!object.Equals(LazyNestedMessage, other.LazyNestedMessage)) return false;
+ if (OptionalNestedEnum != other.OptionalNestedEnum) return false;
+ if (SingularInt32 != other.SingularInt32) return false;
+ if (SingularInt64 != other.SingularInt64) return false;
+ return Equals(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (HasOptionalInt32) hash ^= OptionalInt32.GetHashCode();
+ if (HasOptionalInt64) hash ^= OptionalInt64.GetHashCode();
+ if (HasOptionalUint32) hash ^= OptionalUint32.GetHashCode();
+ if (HasOptionalUint64) hash ^= OptionalUint64.GetHashCode();
+ if (HasOptionalSint32) hash ^= OptionalSint32.GetHashCode();
+ if (HasOptionalSint64) hash ^= OptionalSint64.GetHashCode();
+ if (HasOptionalFixed32) hash ^= OptionalFixed32.GetHashCode();
+ if (HasOptionalFixed64) hash ^= OptionalFixed64.GetHashCode();
+ if (HasOptionalSfixed32) hash ^= OptionalSfixed32.GetHashCode();
+ if (HasOptionalSfixed64) hash ^= OptionalSfixed64.GetHashCode();
+ if (HasOptionalFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(OptionalFloat);
+ if (HasOptionalDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(OptionalDouble);
+ if (HasOptionalBool) hash ^= OptionalBool.GetHashCode();
+ if (HasOptionalString) hash ^= OptionalString.GetHashCode();
+ if (HasOptionalBytes) hash ^= OptionalBytes.GetHashCode();
+ if (HasOptionalCord) hash ^= OptionalCord.GetHashCode();
+ if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode();
+ if (lazyNestedMessage_ != null) hash ^= LazyNestedMessage.GetHashCode();
+ if (HasOptionalNestedEnum) hash ^= OptionalNestedEnum.GetHashCode();
+ if (SingularInt32 != 0) hash ^= SingularInt32.GetHashCode();
+ if (SingularInt64 != 0L) hash ^= SingularInt64.GetHashCode();
+ if (_unknownFields != null) {
+ hash ^= _unknownFields.GetHashCode();
+ }
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (HasOptionalInt32) {
+ output.WriteRawTag(8);
+ output.WriteInt32(OptionalInt32);
+ }
+ if (HasOptionalInt64) {
+ output.WriteRawTag(16);
+ output.WriteInt64(OptionalInt64);
+ }
+ if (HasOptionalUint32) {
+ output.WriteRawTag(24);
+ output.WriteUInt32(OptionalUint32);
+ }
+ if (HasOptionalUint64) {
+ output.WriteRawTag(32);
+ output.WriteUInt64(OptionalUint64);
+ }
+ if (HasOptionalSint32) {
+ output.WriteRawTag(40);
+ output.WriteSInt32(OptionalSint32);
+ }
+ if (HasOptionalSint64) {
+ output.WriteRawTag(48);
+ output.WriteSInt64(OptionalSint64);
+ }
+ if (HasOptionalFixed32) {
+ output.WriteRawTag(61);
+ output.WriteFixed32(OptionalFixed32);
+ }
+ if (HasOptionalFixed64) {
+ output.WriteRawTag(65);
+ output.WriteFixed64(OptionalFixed64);
+ }
+ if (HasOptionalSfixed32) {
+ output.WriteRawTag(77);
+ output.WriteSFixed32(OptionalSfixed32);
+ }
+ if (HasOptionalSfixed64) {
+ output.WriteRawTag(81);
+ output.WriteSFixed64(OptionalSfixed64);
+ }
+ if (HasOptionalFloat) {
+ output.WriteRawTag(93);
+ output.WriteFloat(OptionalFloat);
+ }
+ if (HasOptionalDouble) {
+ output.WriteRawTag(97);
+ output.WriteDouble(OptionalDouble);
+ }
+ if (HasOptionalBool) {
+ output.WriteRawTag(104);
+ output.WriteBool(OptionalBool);
+ }
+ if (HasOptionalString) {
+ output.WriteRawTag(114);
+ output.WriteString(OptionalString);
+ }
+ if (HasOptionalBytes) {
+ output.WriteRawTag(122);
+ output.WriteBytes(OptionalBytes);
+ }
+ if (HasOptionalCord) {
+ output.WriteRawTag(130, 1);
+ output.WriteString(OptionalCord);
+ }
+ if (optionalNestedMessage_ != null) {
+ output.WriteRawTag(146, 1);
+ output.WriteMessage(OptionalNestedMessage);
+ }
+ if (lazyNestedMessage_ != null) {
+ output.WriteRawTag(154, 1);
+ output.WriteMessage(LazyNestedMessage);
+ }
+ if (HasOptionalNestedEnum) {
+ output.WriteRawTag(168, 1);
+ output.WriteEnum((int) OptionalNestedEnum);
+ }
+ if (SingularInt32 != 0) {
+ output.WriteRawTag(176, 1);
+ output.WriteInt32(SingularInt32);
+ }
+ if (SingularInt64 != 0L) {
+ output.WriteRawTag(184, 1);
+ output.WriteInt64(SingularInt64);
+ }
+ if (_unknownFields != null) {
+ _unknownFields.WriteTo(output);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (HasOptionalInt32) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(OptionalInt32);
+ }
+ if (HasOptionalInt64) {
+ size += 1 + pb::CodedOutputStream.ComputeInt64Size(OptionalInt64);
+ }
+ if (HasOptionalUint32) {
+ size += 1 + pb::CodedOutputStream.ComputeUInt32Size(OptionalUint32);
+ }
+ if (HasOptionalUint64) {
+ size += 1 + pb::CodedOutputStream.ComputeUInt64Size(OptionalUint64);
+ }
+ if (HasOptionalSint32) {
+ size += 1 + pb::CodedOutputStream.ComputeSInt32Size(OptionalSint32);
+ }
+ if (HasOptionalSint64) {
+ size += 1 + pb::CodedOutputStream.ComputeSInt64Size(OptionalSint64);
+ }
+ if (HasOptionalFixed32) {
+ size += 1 + 4;
+ }
+ if (HasOptionalFixed64) {
+ size += 1 + 8;
+ }
+ if (HasOptionalSfixed32) {
+ size += 1 + 4;
+ }
+ if (HasOptionalSfixed64) {
+ size += 1 + 8;
+ }
+ if (HasOptionalFloat) {
+ size += 1 + 4;
+ }
+ if (HasOptionalDouble) {
+ size += 1 + 8;
+ }
+ if (HasOptionalBool) {
+ size += 1 + 1;
+ }
+ if (HasOptionalString) {
+ size += 1 + pb::CodedOutputStream.ComputeStringSize(OptionalString);
+ }
+ if (HasOptionalBytes) {
+ size += 1 + pb::CodedOutputStream.ComputeBytesSize(OptionalBytes);
+ }
+ if (HasOptionalCord) {
+ size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalCord);
+ }
+ if (optionalNestedMessage_ != null) {
+ size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage);
+ }
+ if (lazyNestedMessage_ != null) {
+ size += 2 + pb::CodedOutputStream.ComputeMessageSize(LazyNestedMessage);
+ }
+ if (HasOptionalNestedEnum) {
+ size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalNestedEnum);
+ }
+ if (SingularInt32 != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeInt32Size(SingularInt32);
+ }
+ if (SingularInt64 != 0L) {
+ size += 2 + pb::CodedOutputStream.ComputeInt64Size(SingularInt64);
+ }
+ if (_unknownFields != null) {
+ size += _unknownFields.CalculateSize();
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(TestProto3Optional other) {
+ if (other == null) {
+ return;
+ }
+ if (other.HasOptionalInt32) {
+ OptionalInt32 = other.OptionalInt32;
+ }
+ if (other.HasOptionalInt64) {
+ OptionalInt64 = other.OptionalInt64;
+ }
+ if (other.HasOptionalUint32) {
+ OptionalUint32 = other.OptionalUint32;
+ }
+ if (other.HasOptionalUint64) {
+ OptionalUint64 = other.OptionalUint64;
+ }
+ if (other.HasOptionalSint32) {
+ OptionalSint32 = other.OptionalSint32;
+ }
+ if (other.HasOptionalSint64) {
+ OptionalSint64 = other.OptionalSint64;
+ }
+ if (other.HasOptionalFixed32) {
+ OptionalFixed32 = other.OptionalFixed32;
+ }
+ if (other.HasOptionalFixed64) {
+ OptionalFixed64 = other.OptionalFixed64;
+ }
+ if (other.HasOptionalSfixed32) {
+ OptionalSfixed32 = other.OptionalSfixed32;
+ }
+ if (other.HasOptionalSfixed64) {
+ OptionalSfixed64 = other.OptionalSfixed64;
+ }
+ if (other.HasOptionalFloat) {
+ OptionalFloat = other.OptionalFloat;
+ }
+ if (other.HasOptionalDouble) {
+ OptionalDouble = other.OptionalDouble;
+ }
+ if (other.HasOptionalBool) {
+ OptionalBool = other.OptionalBool;
+ }
+ if (other.HasOptionalString) {
+ OptionalString = other.OptionalString;
+ }
+ if (other.HasOptionalBytes) {
+ OptionalBytes = other.OptionalBytes;
+ }
+ if (other.HasOptionalCord) {
+ OptionalCord = other.OptionalCord;
+ }
+ if (other.optionalNestedMessage_ != null) {
+ if (optionalNestedMessage_ == null) {
+ OptionalNestedMessage = new global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage();
+ }
+ OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage);
+ }
+ if (other.lazyNestedMessage_ != null) {
+ if (lazyNestedMessage_ == null) {
+ LazyNestedMessage = new global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage();
+ }
+ LazyNestedMessage.MergeFrom(other.LazyNestedMessage);
+ }
+ if (other.HasOptionalNestedEnum) {
+ OptionalNestedEnum = other.OptionalNestedEnum;
+ }
+ if (other.SingularInt32 != 0) {
+ SingularInt32 = other.SingularInt32;
+ }
+ if (other.SingularInt64 != 0L) {
+ SingularInt64 = other.SingularInt64;
+ }
+ _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
+ break;
+ case 8: {
+ OptionalInt32 = input.ReadInt32();
+ break;
+ }
+ case 16: {
+ OptionalInt64 = input.ReadInt64();
+ break;
+ }
+ case 24: {
+ OptionalUint32 = input.ReadUInt32();
+ break;
+ }
+ case 32: {
+ OptionalUint64 = input.ReadUInt64();
+ break;
+ }
+ case 40: {
+ OptionalSint32 = input.ReadSInt32();
+ break;
+ }
+ case 48: {
+ OptionalSint64 = input.ReadSInt64();
+ break;
+ }
+ case 61: {
+ OptionalFixed32 = input.ReadFixed32();
+ break;
+ }
+ case 65: {
+ OptionalFixed64 = input.ReadFixed64();
+ break;
+ }
+ case 77: {
+ OptionalSfixed32 = input.ReadSFixed32();
+ break;
+ }
+ case 81: {
+ OptionalSfixed64 = input.ReadSFixed64();
+ break;
+ }
+ case 93: {
+ OptionalFloat = input.ReadFloat();
+ break;
+ }
+ case 97: {
+ OptionalDouble = input.ReadDouble();
+ break;
+ }
+ case 104: {
+ OptionalBool = input.ReadBool();
+ break;
+ }
+ case 114: {
+ OptionalString = input.ReadString();
+ break;
+ }
+ case 122: {
+ OptionalBytes = input.ReadBytes();
+ break;
+ }
+ case 130: {
+ OptionalCord = input.ReadString();
+ break;
+ }
+ case 146: {
+ if (optionalNestedMessage_ == null) {
+ OptionalNestedMessage = new global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage();
+ }
+ input.ReadMessage(OptionalNestedMessage);
+ break;
+ }
+ case 154: {
+ if (lazyNestedMessage_ == null) {
+ LazyNestedMessage = new global::ProtobufUnittest.TestProto3Optional.Types.NestedMessage();
+ }
+ input.ReadMessage(LazyNestedMessage);
+ break;
+ }
+ case 168: {
+ OptionalNestedEnum = (global::ProtobufUnittest.TestProto3Optional.Types.NestedEnum) input.ReadEnum();
+ break;
+ }
+ case 176: {
+ SingularInt32 = input.ReadInt32();
+ break;
+ }
+ case 184: {
+ SingularInt64 = input.ReadInt64();
+ break;
+ }
+ }
+ }
+ }
+
+ #region Nested types
+ /// <summary>Container for nested types declared in the TestProto3Optional message type.</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static partial class Types {
+ public enum NestedEnum {
+ [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
+ [pbr::OriginalName("FOO")] Foo = 1,
+ [pbr::OriginalName("BAR")] Bar = 2,
+ [pbr::OriginalName("BAZ")] Baz = 3,
+ /// <summary>
+ /// Intentionally negative.
+ /// </summary>
+ [pbr::OriginalName("NEG")] Neg = -1,
+ }
+
+ public sealed partial class NestedMessage : pb::IMessage<NestedMessage>, pb::IBufferMessage {
+ private static readonly pb::MessageParser<NestedMessage> _parser = new pb::MessageParser<NestedMessage>(() => new NestedMessage());
+ private pb::UnknownFieldSet _unknownFields;
+ private int _hasBits0;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<NestedMessage> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::ProtobufUnittest.TestProto3Optional.Descriptor.NestedTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedMessage() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedMessage(NestedMessage other) : this() {
+ _hasBits0 = other._hasBits0;
+ bb_ = other.bb_;
+ _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public NestedMessage Clone() {
+ return new NestedMessage(this);
+ }
+
+ /// <summary>Field number for the "bb" field.</summary>
+ public const int BbFieldNumber = 1;
+ private int bb_;
+ /// <summary>
+ /// The field name "b" fails to compile in proto1 because it conflicts with
+ /// a local variable named "b" in one of the generated methods. Doh.
+ /// This file needs to compile in proto1 to test backwards-compatibility.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Bb {
+ get { if ((_hasBits0 & 1) != 0) { return bb_; } else { return 0; } }
+ set {
+ _hasBits0 |= 1;
+ bb_ = value;
+ }
+ }
+ /// <summary>Gets whether the "bb" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasBb {
+ get { return (_hasBits0 & 1) != 0; }
+ }
+ /// <summary>Clears the value of the "bb" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearBb() {
+ _hasBits0 &= ~1;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as NestedMessage);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(NestedMessage other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (Bb != other.Bb) return false;
+ return Equals(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (HasBb) hash ^= Bb.GetHashCode();
+ if (_unknownFields != null) {
+ hash ^= _unknownFields.GetHashCode();
+ }
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (HasBb) {
+ output.WriteRawTag(8);
+ output.WriteInt32(Bb);
+ }
+ if (_unknownFields != null) {
+ _unknownFields.WriteTo(output);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (HasBb) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Bb);
+ }
+ if (_unknownFields != null) {
+ size += _unknownFields.CalculateSize();
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(NestedMessage other) {
+ if (other == null) {
+ return;
+ }
+ if (other.HasBb) {
+ Bb = other.Bb;
+ }
+ _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
+ break;
+ case 8: {
+ Bb = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ }
+ #endregion
+
+ }
+
+ #endregion
+
+}
+
+#endregion Designer generated code
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs
new file mode 100644
index 0000000..e466d54
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs
@@ -0,0 +1,306 @@
+// <auto-generated>
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: unittest_selfreferential_options.proto
+// </auto-generated>
+#pragma warning disable 1591, 0612, 3021
+#region Designer generated code
+
+using pb = global::Google.Protobuf;
+using pbc = global::Google.Protobuf.Collections;
+using pbr = global::Google.Protobuf.Reflection;
+using scg = global::System.Collections.Generic;
+namespace UnitTest.Issues.TestProtos.SelfreferentialOptions {
+
+ /// <summary>Holder for reflection information generated from unittest_selfreferential_options.proto</summary>
+ public static partial class UnittestSelfreferentialOptionsReflection {
+
+ #region Descriptor
+ /// <summary>File descriptor for unittest_selfreferential_options.proto</summary>
+ public static pbr::FileDescriptor Descriptor {
+ get { return descriptor; }
+ }
+ private static pbr::FileDescriptor descriptor;
+
+ static UnittestSelfreferentialOptionsReflection() {
+ byte[] descriptorData = global::System.Convert.FromBase64String(
+ string.Concat(
+ "CiZ1bml0dGVzdF9zZWxmcmVmZXJlbnRpYWxfb3B0aW9ucy5wcm90bxIpcHJv",
+ "dG9idWZfdW5pdHRlc3Rfc2VsZnJlZmVyZW50aWFsX29wdGlvbnMaIGdvb2ds",
+ "ZS9wcm90b2J1Zi9kZXNjcmlwdG9yLnByb3RvIkwKCkZvb09wdGlvbnMSHgoH",
+ "aW50X29wdBgBIAEoBUINyj4KCAHAPgLKPgIIAxITCgNmb28YAiABKAVCBso+",
+ "AxDSCSoJCOgHEICAgIACOjkKC2Jhcl9vcHRpb25zEh0uZ29vZ2xlLnByb3Rv",
+ "YnVmLkZpZWxkT3B0aW9ucxjoByABKAVCBMA+0gk6agoLZm9vX29wdGlvbnMS",
+ "HS5nb29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zGOkHIAEoCzI1LnByb3Rv",
+ "YnVmX3VuaXR0ZXN0X3NlbGZyZWZlcmVudGlhbF9vcHRpb25zLkZvb09wdGlv",
+ "bnM6SwoLZm9vX2ludF9vcHQSNS5wcm90b2J1Zl91bml0dGVzdF9zZWxmcmVm",
+ "ZXJlbnRpYWxfb3B0aW9ucy5Gb29PcHRpb25zGOgHIAEoBTqCAQoLZm9vX2Zv",
+ "b19vcHQSNS5wcm90b2J1Zl91bml0dGVzdF9zZWxmcmVmZXJlbnRpYWxfb3B0",
+ "aW9ucy5Gb29PcHRpb25zGOkHIAEoCzI1LnByb3RvYnVmX3VuaXR0ZXN0X3Nl",
+ "bGZyZWZlcmVudGlhbF9vcHRpb25zLkZvb09wdGlvbnNCNKoCMVVuaXRUZXN0",
+ "Lklzc3Vlcy5UZXN0UHJvdG9zLlNlbGZyZWZlcmVudGlhbE9wdGlvbnM="));
+ descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
+ new pbr::FileDescriptor[] { global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor, },
+ new pbr::GeneratedClrTypeInfo(null, new pb::Extension[] { UnittestSelfreferentialOptionsExtensions.BarOptions, UnittestSelfreferentialOptionsExtensions.FooOptions, UnittestSelfreferentialOptionsExtensions.FooIntOpt, UnittestSelfreferentialOptionsExtensions.FooFooOpt }, new pbr::GeneratedClrTypeInfo[] {
+ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions), global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Parser, new[]{ "IntOpt", "Foo" }, null, null, null, null)
+ }));
+ }
+ #endregion
+
+ }
+ /// <summary>Holder for extension identifiers generated from the top level of unittest_selfreferential_options.proto</summary>
+ public static partial class UnittestSelfreferentialOptionsExtensions {
+ /// <summary>
+ /// Custom field option used on the definition of that field option.
+ /// </summary>
+ public static readonly pb::Extension<global::Google.Protobuf.Reflection.FieldOptions, int> BarOptions =
+ new pb::Extension<global::Google.Protobuf.Reflection.FieldOptions, int>(1000, pb::FieldCodec.ForInt32(8000, 0));
+ public static readonly pb::Extension<global::Google.Protobuf.Reflection.FieldOptions, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions> FooOptions =
+ new pb::Extension<global::Google.Protobuf.Reflection.FieldOptions, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions>(1001, pb::FieldCodec.ForMessage(8010, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Parser));
+ public static readonly pb::Extension<global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions, int> FooIntOpt =
+ new pb::Extension<global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions, int>(1000, pb::FieldCodec.ForInt32(8000, 0));
+ public static readonly pb::Extension<global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions> FooFooOpt =
+ new pb::Extension<global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions>(1001, pb::FieldCodec.ForMessage(8010, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Parser));
+ }
+
+ #region Messages
+ public sealed partial class FooOptions : pb::IExtendableMessage<FooOptions>, pb::IBufferMessage {
+ private static readonly pb::MessageParser<FooOptions> _parser = new pb::MessageParser<FooOptions>(() => new FooOptions());
+ private pb::UnknownFieldSet _unknownFields;
+ private pb::ExtensionSet<FooOptions> _extensions;
+ private pb::ExtensionSet<FooOptions> _Extensions { get { return _extensions; } }
+ private int _hasBits0;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pb::MessageParser<FooOptions> Parser { get { return _parser; } }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public static pbr::MessageDescriptor Descriptor {
+ get { return global::UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsReflection.Descriptor.MessageTypes[0]; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ pbr::MessageDescriptor pb::IMessage.Descriptor {
+ get { return Descriptor; }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public FooOptions() {
+ OnConstruction();
+ }
+
+ partial void OnConstruction();
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public FooOptions(FooOptions other) : this() {
+ _hasBits0 = other._hasBits0;
+ intOpt_ = other.intOpt_;
+ foo_ = other.foo_;
+ _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
+ _extensions = pb::ExtensionSet.Clone(other._extensions);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public FooOptions Clone() {
+ return new FooOptions(this);
+ }
+
+ /// <summary>Field number for the "int_opt" field.</summary>
+ public const int IntOptFieldNumber = 1;
+ private readonly static int IntOptDefaultValue = 0;
+
+ private int intOpt_;
+ /// <summary>
+ /// Custom field option used in definition of the extension message.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int IntOpt {
+ get { if ((_hasBits0 & 1) != 0) { return intOpt_; } else { return IntOptDefaultValue; } }
+ set {
+ _hasBits0 |= 1;
+ intOpt_ = value;
+ }
+ }
+ /// <summary>Gets whether the "int_opt" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasIntOpt {
+ get { return (_hasBits0 & 1) != 0; }
+ }
+ /// <summary>Clears the value of the "int_opt" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearIntOpt() {
+ _hasBits0 &= ~1;
+ }
+
+ /// <summary>Field number for the "foo" field.</summary>
+ public const int FooFieldNumber = 2;
+ private readonly static int FooDefaultValue = 0;
+
+ private int foo_;
+ /// <summary>
+ /// Custom field option used in definition of the custom option's message.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int Foo {
+ get { if ((_hasBits0 & 2) != 0) { return foo_; } else { return FooDefaultValue; } }
+ set {
+ _hasBits0 |= 2;
+ foo_ = value;
+ }
+ }
+ /// <summary>Gets whether the "foo" field is set</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool HasFoo {
+ get { return (_hasBits0 & 2) != 0; }
+ }
+ /// <summary>Clears the value of the "foo" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearFoo() {
+ _hasBits0 &= ~2;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override bool Equals(object other) {
+ return Equals(other as FooOptions);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool Equals(FooOptions other) {
+ if (ReferenceEquals(other, null)) {
+ return false;
+ }
+ if (ReferenceEquals(other, this)) {
+ return true;
+ }
+ if (IntOpt != other.IntOpt) return false;
+ if (Foo != other.Foo) return false;
+ if (!Equals(_extensions, other._extensions)) {
+ return false;
+ }
+ return Equals(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override int GetHashCode() {
+ int hash = 1;
+ if (HasIntOpt) hash ^= IntOpt.GetHashCode();
+ if (HasFoo) hash ^= Foo.GetHashCode();
+ if (_extensions != null) {
+ hash ^= _extensions.GetHashCode();
+ }
+ if (_unknownFields != null) {
+ hash ^= _unknownFields.GetHashCode();
+ }
+ return hash;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public override string ToString() {
+ return pb::JsonFormatter.ToDiagnosticString(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (HasIntOpt) {
+ output.WriteRawTag(8);
+ output.WriteInt32(IntOpt);
+ }
+ if (HasFoo) {
+ output.WriteRawTag(16);
+ output.WriteInt32(Foo);
+ }
+ if (_extensions != null) {
+ _extensions.WriteTo(output);
+ }
+ if (_unknownFields != null) {
+ _unknownFields.WriteTo(output);
+ }
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int CalculateSize() {
+ int size = 0;
+ if (HasIntOpt) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(IntOpt);
+ }
+ if (HasFoo) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(Foo);
+ }
+ if (_extensions != null) {
+ size += _extensions.CalculateSize();
+ }
+ if (_unknownFields != null) {
+ size += _unknownFields.CalculateSize();
+ }
+ return size;
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(FooOptions other) {
+ if (other == null) {
+ return;
+ }
+ if (other.HasIntOpt) {
+ IntOpt = other.IntOpt;
+ }
+ if (other.HasFoo) {
+ Foo = other.Foo;
+ }
+ pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions);
+ _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
+ }
+ break;
+ case 8: {
+ IntOpt = input.ReadInt32();
+ break;
+ }
+ case 16: {
+ Foo = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+
+ public TValue GetExtension<TValue>(pb::Extension<FooOptions, TValue> extension) {
+ return pb::ExtensionSet.Get(ref _extensions, extension);
+ }
+ public pbc::RepeatedField<TValue> GetExtension<TValue>(pb::RepeatedExtension<FooOptions, TValue> extension) {
+ return pb::ExtensionSet.Get(ref _extensions, extension);
+ }
+ public pbc::RepeatedField<TValue> GetOrInitializeExtension<TValue>(pb::RepeatedExtension<FooOptions, TValue> extension) {
+ return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension);
+ }
+ public void SetExtension<TValue>(pb::Extension<FooOptions, TValue> extension, TValue value) {
+ pb::ExtensionSet.Set(ref _extensions, extension, value);
+ }
+ public bool HasExtension<TValue>(pb::Extension<FooOptions, TValue> extension) {
+ return pb::ExtensionSet.Has(ref _extensions, extension);
+ }
+ public void ClearExtension<TValue>(pb::Extension<FooOptions, TValue> extension) {
+ pb::ExtensionSet.Clear(ref _extensions, extension);
+ }
+ public void ClearExtension<TValue>(pb::RepeatedExtension<FooOptions, TValue> extension) {
+ pb::ExtensionSet.Clear(ref _extensions, extension);
+ }
+
+ }
+
+ #endregion
+
+}
+
+#endregion Designer generated code
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestWellKnownTypes.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestWellKnownTypes.cs
index 90b3384..c67187e 100644
--- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestWellKnownTypes.cs
+++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestWellKnownTypes.cs
@@ -179,7 +179,7 @@
/// Each wrapper type is included separately, as languages
/// map handle different wrappers in different ways.
/// </summary>
- public sealed partial class TestWellKnownTypes : pb::IMessage<TestWellKnownTypes> {
+ public sealed partial class TestWellKnownTypes : pb::IMessage<TestWellKnownTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<TestWellKnownTypes> _parser = new pb::MessageParser<TestWellKnownTypes>(() => new TestWellKnownTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -784,11 +784,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (anyField_ == null) {
@@ -854,63 +859,63 @@
break;
}
case 82: {
- double? value = _single_doubleField_codec.Read(input);
+ double? value = _single_doubleField_codec.Read(ref input);
if (doubleField_ == null || value != 0D) {
DoubleField = value;
}
break;
}
case 90: {
- float? value = _single_floatField_codec.Read(input);
+ float? value = _single_floatField_codec.Read(ref input);
if (floatField_ == null || value != 0F) {
FloatField = value;
}
break;
}
case 98: {
- long? value = _single_int64Field_codec.Read(input);
+ long? value = _single_int64Field_codec.Read(ref input);
if (int64Field_ == null || value != 0L) {
Int64Field = value;
}
break;
}
case 106: {
- ulong? value = _single_uint64Field_codec.Read(input);
+ ulong? value = _single_uint64Field_codec.Read(ref input);
if (uint64Field_ == null || value != 0UL) {
Uint64Field = value;
}
break;
}
case 114: {
- int? value = _single_int32Field_codec.Read(input);
+ int? value = _single_int32Field_codec.Read(ref input);
if (int32Field_ == null || value != 0) {
Int32Field = value;
}
break;
}
case 122: {
- uint? value = _single_uint32Field_codec.Read(input);
+ uint? value = _single_uint32Field_codec.Read(ref input);
if (uint32Field_ == null || value != 0) {
Uint32Field = value;
}
break;
}
case 130: {
- bool? value = _single_boolField_codec.Read(input);
+ bool? value = _single_boolField_codec.Read(ref input);
if (boolField_ == null || value != false) {
BoolField = value;
}
break;
}
case 138: {
- string value = _single_stringField_codec.Read(input);
+ string value = _single_stringField_codec.Read(ref input);
if (stringField_ == null || value != "") {
StringField = value;
}
break;
}
case 146: {
- pb::ByteString value = _single_bytesField_codec.Read(input);
+ pb::ByteString value = _single_bytesField_codec.Read(ref input);
if (bytesField_ == null || value != pb::ByteString.Empty) {
BytesField = value;
}
@@ -932,7 +937,7 @@
/// <summary>
/// A repeated field for each well-known type.
/// </summary>
- public sealed partial class RepeatedWellKnownTypes : pb::IMessage<RepeatedWellKnownTypes> {
+ public sealed partial class RepeatedWellKnownTypes : pb::IMessage<RepeatedWellKnownTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<RepeatedWellKnownTypes> _parser = new pb::MessageParser<RepeatedWellKnownTypes>(() => new RepeatedWellKnownTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1312,82 +1317,87 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- anyField_.AddEntriesFrom(input, _repeated_anyField_codec);
+ anyField_.AddEntriesFrom(ref input, _repeated_anyField_codec);
break;
}
case 18: {
- apiField_.AddEntriesFrom(input, _repeated_apiField_codec);
+ apiField_.AddEntriesFrom(ref input, _repeated_apiField_codec);
break;
}
case 26: {
- durationField_.AddEntriesFrom(input, _repeated_durationField_codec);
+ durationField_.AddEntriesFrom(ref input, _repeated_durationField_codec);
break;
}
case 34: {
- emptyField_.AddEntriesFrom(input, _repeated_emptyField_codec);
+ emptyField_.AddEntriesFrom(ref input, _repeated_emptyField_codec);
break;
}
case 42: {
- fieldMaskField_.AddEntriesFrom(input, _repeated_fieldMaskField_codec);
+ fieldMaskField_.AddEntriesFrom(ref input, _repeated_fieldMaskField_codec);
break;
}
case 50: {
- sourceContextField_.AddEntriesFrom(input, _repeated_sourceContextField_codec);
+ sourceContextField_.AddEntriesFrom(ref input, _repeated_sourceContextField_codec);
break;
}
case 58: {
- structField_.AddEntriesFrom(input, _repeated_structField_codec);
+ structField_.AddEntriesFrom(ref input, _repeated_structField_codec);
break;
}
case 66: {
- timestampField_.AddEntriesFrom(input, _repeated_timestampField_codec);
+ timestampField_.AddEntriesFrom(ref input, _repeated_timestampField_codec);
break;
}
case 74: {
- typeField_.AddEntriesFrom(input, _repeated_typeField_codec);
+ typeField_.AddEntriesFrom(ref input, _repeated_typeField_codec);
break;
}
case 82: {
- doubleField_.AddEntriesFrom(input, _repeated_doubleField_codec);
+ doubleField_.AddEntriesFrom(ref input, _repeated_doubleField_codec);
break;
}
case 90: {
- floatField_.AddEntriesFrom(input, _repeated_floatField_codec);
+ floatField_.AddEntriesFrom(ref input, _repeated_floatField_codec);
break;
}
case 98: {
- int64Field_.AddEntriesFrom(input, _repeated_int64Field_codec);
+ int64Field_.AddEntriesFrom(ref input, _repeated_int64Field_codec);
break;
}
case 106: {
- uint64Field_.AddEntriesFrom(input, _repeated_uint64Field_codec);
+ uint64Field_.AddEntriesFrom(ref input, _repeated_uint64Field_codec);
break;
}
case 114: {
- int32Field_.AddEntriesFrom(input, _repeated_int32Field_codec);
+ int32Field_.AddEntriesFrom(ref input, _repeated_int32Field_codec);
break;
}
case 122: {
- uint32Field_.AddEntriesFrom(input, _repeated_uint32Field_codec);
+ uint32Field_.AddEntriesFrom(ref input, _repeated_uint32Field_codec);
break;
}
case 130: {
- boolField_.AddEntriesFrom(input, _repeated_boolField_codec);
+ boolField_.AddEntriesFrom(ref input, _repeated_boolField_codec);
break;
}
case 138: {
- stringField_.AddEntriesFrom(input, _repeated_stringField_codec);
+ stringField_.AddEntriesFrom(ref input, _repeated_stringField_codec);
break;
}
case 146: {
- bytesField_.AddEntriesFrom(input, _repeated_bytesField_codec);
+ bytesField_.AddEntriesFrom(ref input, _repeated_bytesField_codec);
break;
}
}
@@ -1396,7 +1406,7 @@
}
- public sealed partial class OneofWellKnownTypes : pb::IMessage<OneofWellKnownTypes> {
+ public sealed partial class OneofWellKnownTypes : pb::IMessage<OneofWellKnownTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneofWellKnownTypes> _parser = new pb::MessageParser<OneofWellKnownTypes>(() => new OneofWellKnownTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2023,11 +2033,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
global::Google.Protobuf.WellKnownTypes.Any subBuilder = new global::Google.Protobuf.WellKnownTypes.Any();
@@ -2111,39 +2126,39 @@
break;
}
case 82: {
- DoubleField = _oneof_doubleField_codec.Read(input);
+ DoubleField = _oneof_doubleField_codec.Read(ref input);
break;
}
case 90: {
- FloatField = _oneof_floatField_codec.Read(input);
+ FloatField = _oneof_floatField_codec.Read(ref input);
break;
}
case 98: {
- Int64Field = _oneof_int64Field_codec.Read(input);
+ Int64Field = _oneof_int64Field_codec.Read(ref input);
break;
}
case 106: {
- Uint64Field = _oneof_uint64Field_codec.Read(input);
+ Uint64Field = _oneof_uint64Field_codec.Read(ref input);
break;
}
case 114: {
- Int32Field = _oneof_int32Field_codec.Read(input);
+ Int32Field = _oneof_int32Field_codec.Read(ref input);
break;
}
case 122: {
- Uint32Field = _oneof_uint32Field_codec.Read(input);
+ Uint32Field = _oneof_uint32Field_codec.Read(ref input);
break;
}
case 130: {
- BoolField = _oneof_boolField_codec.Read(input);
+ BoolField = _oneof_boolField_codec.Read(ref input);
break;
}
case 138: {
- StringField = _oneof_stringField_codec.Read(input);
+ StringField = _oneof_stringField_codec.Read(ref input);
break;
}
case 146: {
- BytesField = _oneof_bytesField_codec.Read(input);
+ BytesField = _oneof_bytesField_codec.Read(ref input);
break;
}
}
@@ -2157,7 +2172,7 @@
/// need to worry about the value part of the map being the
/// well-known types, as messages can't be map keys.
/// </summary>
- public sealed partial class MapWellKnownTypes : pb::IMessage<MapWellKnownTypes> {
+ public sealed partial class MapWellKnownTypes : pb::IMessage<MapWellKnownTypes>, pb::IBufferMessage {
private static readonly pb::MessageParser<MapWellKnownTypes> _parser = new pb::MessageParser<MapWellKnownTypes>(() => new MapWellKnownTypes());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2534,82 +2549,87 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- anyField_.AddEntriesFrom(input, _map_anyField_codec);
+ anyField_.AddEntriesFrom(ref input, _map_anyField_codec);
break;
}
case 18: {
- apiField_.AddEntriesFrom(input, _map_apiField_codec);
+ apiField_.AddEntriesFrom(ref input, _map_apiField_codec);
break;
}
case 26: {
- durationField_.AddEntriesFrom(input, _map_durationField_codec);
+ durationField_.AddEntriesFrom(ref input, _map_durationField_codec);
break;
}
case 34: {
- emptyField_.AddEntriesFrom(input, _map_emptyField_codec);
+ emptyField_.AddEntriesFrom(ref input, _map_emptyField_codec);
break;
}
case 42: {
- fieldMaskField_.AddEntriesFrom(input, _map_fieldMaskField_codec);
+ fieldMaskField_.AddEntriesFrom(ref input, _map_fieldMaskField_codec);
break;
}
case 50: {
- sourceContextField_.AddEntriesFrom(input, _map_sourceContextField_codec);
+ sourceContextField_.AddEntriesFrom(ref input, _map_sourceContextField_codec);
break;
}
case 58: {
- structField_.AddEntriesFrom(input, _map_structField_codec);
+ structField_.AddEntriesFrom(ref input, _map_structField_codec);
break;
}
case 66: {
- timestampField_.AddEntriesFrom(input, _map_timestampField_codec);
+ timestampField_.AddEntriesFrom(ref input, _map_timestampField_codec);
break;
}
case 74: {
- typeField_.AddEntriesFrom(input, _map_typeField_codec);
+ typeField_.AddEntriesFrom(ref input, _map_typeField_codec);
break;
}
case 82: {
- doubleField_.AddEntriesFrom(input, _map_doubleField_codec);
+ doubleField_.AddEntriesFrom(ref input, _map_doubleField_codec);
break;
}
case 90: {
- floatField_.AddEntriesFrom(input, _map_floatField_codec);
+ floatField_.AddEntriesFrom(ref input, _map_floatField_codec);
break;
}
case 98: {
- int64Field_.AddEntriesFrom(input, _map_int64Field_codec);
+ int64Field_.AddEntriesFrom(ref input, _map_int64Field_codec);
break;
}
case 106: {
- uint64Field_.AddEntriesFrom(input, _map_uint64Field_codec);
+ uint64Field_.AddEntriesFrom(ref input, _map_uint64Field_codec);
break;
}
case 114: {
- int32Field_.AddEntriesFrom(input, _map_int32Field_codec);
+ int32Field_.AddEntriesFrom(ref input, _map_int32Field_codec);
break;
}
case 122: {
- uint32Field_.AddEntriesFrom(input, _map_uint32Field_codec);
+ uint32Field_.AddEntriesFrom(ref input, _map_uint32Field_codec);
break;
}
case 130: {
- boolField_.AddEntriesFrom(input, _map_boolField_codec);
+ boolField_.AddEntriesFrom(ref input, _map_boolField_codec);
break;
}
case 138: {
- stringField_.AddEntriesFrom(input, _map_stringField_codec);
+ stringField_.AddEntriesFrom(ref input, _map_stringField_codec);
break;
}
case 146: {
- bytesField_.AddEntriesFrom(input, _map_bytesField_codec);
+ bytesField_.AddEntriesFrom(ref input, _map_bytesField_codec);
break;
}
}
diff --git a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
index ba65b32..bcc6ace 100644
--- a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
+++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
@@ -31,8 +31,10 @@
#endregion
using System;
+using System.Buffers;
using System.IO;
using Google.Protobuf.TestProtos;
+using Proto2 = Google.Protobuf.TestProtos.Proto2;
using NUnit.Framework;
namespace Google.Protobuf
@@ -61,11 +63,22 @@
{
CodedInputStream input = new CodedInputStream(data);
Assert.AreEqual((uint) value, input.ReadRawVarint32());
+ Assert.IsTrue(input.IsAtEnd);
input = new CodedInputStream(data);
Assert.AreEqual(value, input.ReadRawVarint64());
Assert.IsTrue(input.IsAtEnd);
+ AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual((uint) value, ctx.ReadUInt32());
+ }, true);
+
+ AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual(value, ctx.ReadUInt64());
+ }, true);
+
// Try different block sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
@@ -75,6 +88,16 @@
input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
Assert.AreEqual(value, input.ReadRawVarint64());
Assert.IsTrue(input.IsAtEnd);
+
+ AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, bufferSize), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual((uint) value, ctx.ReadUInt32());
+ }, true);
+
+ AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, bufferSize), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual(value, ctx.ReadUInt64());
+ }, true);
}
// Try reading directly from a MemoryStream. We want to verify that it
@@ -103,11 +126,49 @@
exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
Assert.AreEqual(expected.Message, exception.Message);
+ AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
+ {
+ try
+ {
+ ctx.ReadUInt32();
+ Assert.Fail();
+ }
+ catch (InvalidProtocolBufferException ex)
+ {
+ Assert.AreEqual(expected.Message, ex.Message);
+ }
+ }, false);
+
+ AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
+ {
+ try
+ {
+ ctx.ReadUInt64();
+ Assert.Fail();
+ }
+ catch (InvalidProtocolBufferException ex)
+ {
+ Assert.AreEqual(expected.Message, ex.Message);
+ }
+ }, false);
+
// Make sure we get the same error when reading directly from a Stream.
exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
Assert.AreEqual(expected.Message, exception.Message);
}
+ private delegate void ParseContextAssertAction(ref ParseContext ctx);
+
+ private static void AssertReadFromParseContext(ReadOnlySequence<byte> input, ParseContextAssertAction assertAction, bool assertIsAtEnd)
+ {
+ ParseContext.Initialize(input, out ParseContext parseCtx);
+ assertAction(ref parseCtx);
+ if (assertIsAtEnd)
+ {
+ Assert.IsTrue(SegmentedBufferHelper.IsAtEnd(ref parseCtx.buffer, ref parseCtx.state));
+ }
+ }
+
[Test]
public void ReadVarint()
{
@@ -156,6 +217,11 @@
Assert.AreEqual(value, input.ReadRawLittleEndian32());
Assert.IsTrue(input.IsAtEnd);
+ AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual(value, ctx.ReadFixed32());
+ }, true);
+
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
@@ -163,6 +229,11 @@
new SmallBlockInputStream(data, blockSize));
Assert.AreEqual(value, input.ReadRawLittleEndian32());
Assert.IsTrue(input.IsAtEnd);
+
+ AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, blockSize), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual(value, ctx.ReadFixed32());
+ }, true);
}
}
@@ -176,6 +247,11 @@
Assert.AreEqual(value, input.ReadRawLittleEndian64());
Assert.IsTrue(input.IsAtEnd);
+ AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual(value, ctx.ReadFixed64());
+ }, true);
+
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
@@ -183,6 +259,11 @@
new SmallBlockInputStream(data, blockSize));
Assert.AreEqual(value, input.ReadRawLittleEndian64());
Assert.IsTrue(input.IsAtEnd);
+
+ AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, blockSize), (ref ParseContext ctx) =>
+ {
+ Assert.AreEqual(value, ctx.ReadFixed64());
+ }, true);
}
}
@@ -201,29 +282,29 @@
[Test]
public void DecodeZigZag32()
{
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
- Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
- Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
- Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
- Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
- Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(0));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(1));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(2));
+ Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag32(3));
+ Assert.AreEqual(0x3FFFFFFF, ParsingPrimitives.DecodeZigZag32(0x7FFFFFFE));
+ Assert.AreEqual(unchecked((int) 0xC0000000), ParsingPrimitives.DecodeZigZag32(0x7FFFFFFF));
+ Assert.AreEqual(0x7FFFFFFF, ParsingPrimitives.DecodeZigZag32(0xFFFFFFFE));
+ Assert.AreEqual(unchecked((int) 0x80000000), ParsingPrimitives.DecodeZigZag32(0xFFFFFFFF));
}
[Test]
public void DecodeZigZag64()
{
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
- Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
- Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
- Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
- Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
- Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
- Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
- Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(0));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(1));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(2));
+ Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag64(3));
+ Assert.AreEqual(0x000000003FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFFL));
+ Assert.AreEqual(0x000000007FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFFL));
+ Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
+ Assert.AreEqual(unchecked((long) 0x8000000000000000L), ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
[Test]
@@ -337,6 +418,66 @@
CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(atRecursiveLimit.ToByteArray()), 1000000, CodedInputStream.DefaultRecursionLimit - 1);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
}
+
+ private static byte[] MakeMaliciousRecursionUnknownFieldsPayload(int recursionDepth)
+ {
+ // generate recursively nested groups that will be parsed as unknown fields
+ int unknownFieldNumber = 14; // an unused field number
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(ms);
+ for (int i = 0; i < recursionDepth; i++)
+ {
+ output.WriteTag(WireFormat.MakeTag(unknownFieldNumber, WireFormat.WireType.StartGroup));
+ }
+ for (int i = 0; i < recursionDepth; i++)
+ {
+ output.WriteTag(WireFormat.MakeTag(unknownFieldNumber, WireFormat.WireType.EndGroup));
+ }
+ output.Flush();
+ return ms.ToArray();
+ }
+
+ [Test]
+ public void MaliciousRecursion_UnknownFields()
+ {
+ byte[] payloadAtRecursiveLimit = MakeMaliciousRecursionUnknownFieldsPayload(CodedInputStream.DefaultRecursionLimit);
+ byte[] payloadBeyondRecursiveLimit = MakeMaliciousRecursionUnknownFieldsPayload(CodedInputStream.DefaultRecursionLimit + 1);
+
+ Assert.DoesNotThrow(() => TestRecursiveMessage.Parser.ParseFrom(payloadAtRecursiveLimit));
+ Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(payloadBeyondRecursiveLimit));
+ }
+
+ [Test]
+ public void ReadGroup_WrongEndGroupTag()
+ {
+ int groupFieldNumber = Proto2.TestAllTypes.OptionalGroupFieldNumber;
+
+ // write Proto2.TestAllTypes with "optional_group" set, but use wrong EndGroup closing tag
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(ms);
+ output.WriteTag(WireFormat.MakeTag(groupFieldNumber, WireFormat.WireType.StartGroup));
+ output.WriteGroup(new Proto2.TestAllTypes.Types.OptionalGroup { A = 12345 });
+ // end group with different field number
+ output.WriteTag(WireFormat.MakeTag(groupFieldNumber + 1, WireFormat.WireType.EndGroup));
+ output.Flush();
+ var payload = ms.ToArray();
+
+ Assert.Throws<InvalidProtocolBufferException>(() => Proto2.TestAllTypes.Parser.ParseFrom(payload));
+ }
+
+ [Test]
+ public void ReadGroup_UnknownFields_WrongEndGroupTag()
+ {
+ MemoryStream ms = new MemoryStream();
+ CodedOutputStream output = new CodedOutputStream(ms);
+ output.WriteTag(WireFormat.MakeTag(14, WireFormat.WireType.StartGroup));
+ // end group with different field number
+ output.WriteTag(WireFormat.MakeTag(15, WireFormat.WireType.EndGroup));
+ output.Flush();
+ var payload = ms.ToArray();
+
+ Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(payload));
+ }
[Test]
public void SizeLimit()
@@ -735,4 +876,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
index 98cabd5..b9ff515 100644
--- a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
+++ b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
@@ -247,26 +247,26 @@
{
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
- Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
- Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
+ Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
+ Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
}
[Test]
public void RoundTripZigZag64()
{
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
- Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
- Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
+ Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
+ Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
+ Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
+ Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
+ Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
Assert.AreEqual(856912304801416L,
- CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
+ ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
Assert.AreEqual(-75123905439571256L,
- CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
+ ParsingPrimitives.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
}
[Test]
diff --git a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
index f64ebac..d8cdee0 100644
--- a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
@@ -31,6 +31,7 @@
#endregion
using System;
+using System.IO;
using System.Collections.Generic;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
@@ -583,6 +584,33 @@
Assert.False(map.TryGetValue(SampleNaNs.PayloadFlipped, out ignored));
}
+ [Test]
+ public void AddEntriesFrom_CodedInputStream()
+ {
+ // map will have string key and string value
+ var keyTag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
+ var valueTag = WireFormat.MakeTag(2, WireFormat.WireType.LengthDelimited);
+
+ var memoryStream = new MemoryStream();
+ var output = new CodedOutputStream(memoryStream);
+ output.WriteLength(20); // total of keyTag + key + valueTag + value
+ output.WriteTag(keyTag);
+ output.WriteString("the_key");
+ output.WriteTag(valueTag);
+ output.WriteString("the_value");
+ output.Flush();
+
+ var field = new MapField<string,string>();
+ var mapCodec = new MapField<string,string>.Codec(FieldCodec.ForString(keyTag, ""), FieldCodec.ForString(valueTag, ""), 10);
+ var input = new CodedInputStream(memoryStream.ToArray());
+
+ // test the legacy overload of AddEntriesFrom that takes a CodedInputStream
+ field.AddEntriesFrom(input, mapCodec);
+ CollectionAssert.AreEquivalent(new[] { "the_key" }, field.Keys);
+ CollectionAssert.AreEquivalent(new[] { "the_value" }, field.Values);
+ Assert.IsTrue(input.IsAtEnd);
+ }
+
#if !NET35
[Test]
public void IDictionaryKeys_Equals_IReadOnlyDictionaryKeys()
diff --git a/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs b/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs
index 33dc504..934b780 100644
--- a/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs
+++ b/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs
@@ -1,4 +1,4 @@
-using Google.Protobuf.TestProtos.Proto2;
+using Google.Protobuf.TestProtos.Proto2;
using NUnit.Framework;
using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions;
@@ -34,12 +34,14 @@
message.SetExtension(OptionalBoolExtension, true);
var serialized = message.ToByteArray();
- var other = TestAllExtensions.Parser
- .WithExtensionRegistry(new ExtensionRegistry() { OptionalBoolExtension })
- .ParseFrom(serialized);
-
- Assert.AreEqual(message, other);
- Assert.AreEqual(message.CalculateSize(), other.CalculateSize());
+ MessageParsingHelpers.AssertReadingMessage(
+ TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { OptionalBoolExtension }),
+ serialized,
+ other =>
+ {
+ Assert.AreEqual(message, other);
+ Assert.AreEqual(message.CalculateSize(), other.CalculateSize());
+ });
}
[Test]
@@ -60,6 +62,22 @@
}
[Test]
+ public void TryMergeFieldFrom_CodedInputStream()
+ {
+ var message = new TestAllExtensions();
+ message.SetExtension(OptionalStringExtension, "abcd");
+
+ var input = new CodedInputStream(message.ToByteArray());
+ input.ExtensionRegistry = new ExtensionRegistry() { OptionalStringExtension };
+ input.ReadTag(); // TryMergeFieldFrom expects that a tag was just read and will inspect the LastTag value
+
+ ExtensionSet<TestAllExtensions> extensionSet = null;
+ // test the legacy overload of TryMergeFieldFrom that takes a CodedInputStream
+ Assert.IsTrue(ExtensionSet.TryMergeFieldFrom(ref extensionSet, input));
+ Assert.AreEqual("abcd", ExtensionSet.Get(ref extensionSet, OptionalStringExtension));
+ }
+
+ [Test]
public void TestEquals()
{
var message = new TestAllExtensions();
diff --git a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
index b20eccc..5be0cec 100644
--- a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
+++ b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
@@ -128,7 +128,7 @@
codedOutput.Flush();
stream.Position = 0;
var codedInput = new CodedInputStream(stream);
- Assert.AreEqual(sampleValue, codec.ValueReader(codedInput));
+ Assert.AreEqual(sampleValue, codec.Read(codedInput));
Assert.IsTrue(codedInput.IsAtEnd);
}
@@ -158,7 +158,7 @@
{
// WriteTagAndValue ignores default values
var stream = new MemoryStream();
- CodedOutputStream codedOutput;
+ CodedOutputStream codedOutput;
#if !NET35
codedOutput = new CodedOutputStream(stream);
codec.WriteTagAndValue(codedOutput, codec.DefaultValue);
@@ -181,7 +181,7 @@
Assert.AreEqual(stream.Position, codec.ValueSizeCalculator(codec.DefaultValue));
stream.Position = 0;
var codedInput = new CodedInputStream(stream);
- Assert.AreEqual(codec.DefaultValue, codec.ValueReader(codedInput));
+ Assert.AreEqual(codec.DefaultValue, codec.Read(codedInput));
}
}
diff --git a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs
index e1d4d78..5f90c94 100644
--- a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs
+++ b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs
@@ -261,6 +261,18 @@
Assert.True(message.IsInitialized());
}
+ /// <summary>
+ /// Code was accidentally left in message parser that threw exceptions when missing required fields after parsing.
+ /// We've decided to not throw exceptions on missing fields, instead leaving it up to the consumer how they
+ /// want to check and handle missing fields.
+ /// </summary>
+ [Test]
+ public void RequiredFieldsNoThrow()
+ {
+ Assert.DoesNotThrow(() => MessageParsingHelpers.AssertReadingMessage(TestRequired.Parser, new byte[0], m => { }));
+ Assert.DoesNotThrow(() => MessageParsingHelpers.AssertReadingMessage(TestRequired.Parser as MessageParser, new byte[0], m => { }));
+ }
+
[Test]
public void RequiredFieldsInExtensions()
{
@@ -332,9 +344,7 @@
}
};
- byte[] bytes = message.ToByteArray();
- TestAllTypes parsed = Proto2.TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
+ MessageParsingHelpers.AssertRoundtrip(Proto2.TestAllTypes.Parser, message);
}
[Test]
@@ -349,9 +359,9 @@
new RepeatedGroup_extension { A = 30 }
});
- byte[] bytes = message.ToByteArray();
- TestAllExtensions extendable_parsed = TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalGroupExtension, UnittestExtensions.RepeatedGroupExtension }).ParseFrom(bytes);
- Assert.AreEqual(message, extendable_parsed);
+ MessageParsingHelpers.AssertRoundtrip(
+ TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalGroupExtension, UnittestExtensions.RepeatedGroupExtension }),
+ message);
}
[Test]
@@ -360,9 +370,9 @@
var message = new TestGroupExtension();
message.SetExtension(TestNestedExtension.Extensions.OptionalGroupExtension, new TestNestedExtension.Types.OptionalGroup_extension { A = 10 });
- byte[] bytes = message.ToByteArray();
- TestGroupExtension extendable_parsed = TestGroupExtension.Parser.WithExtensionRegistry(new ExtensionRegistry() { TestNestedExtension.Extensions.OptionalGroupExtension }).ParseFrom(bytes);
- Assert.AreEqual(message, extendable_parsed);
+ MessageParsingHelpers.AssertRoundtrip(
+ TestGroupExtension.Parser.WithExtensionRegistry(new ExtensionRegistry() { TestNestedExtension.Extensions.OptionalGroupExtension }),
+ message);
}
}
}
diff --git a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs
index 103df7d..3499e66 100644
--- a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs
+++ b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs
@@ -131,8 +131,8 @@
// Without setting any values, there's nothing to write.
byte[] bytes = message.ToByteArray();
Assert.AreEqual(0, bytes.Length);
- TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
+
+ MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message);
}
[Test]
@@ -165,8 +165,8 @@
};
byte[] bytes = message.ToByteArray();
- TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
+
+ MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message);
}
[Test]
@@ -199,8 +199,8 @@
};
byte[] bytes = message.ToByteArray();
- TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
+
+ MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message);
}
// Note that not every map within map_unittest_proto3 is used. They all go through very
@@ -231,8 +231,8 @@
};
byte[] bytes = message.ToByteArray();
- TestMap parsed = TestMap.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
+
+ MessageParsingHelpers.AssertRoundtrip(TestMap.Parser, message);
}
[Test]
@@ -246,9 +246,14 @@
byte[] bytes = message.ToByteArray();
Assert.AreEqual(2, bytes.Length); // Tag for field entry (1 byte), length of entry (0; 1 byte)
- var parsed = TestMap.Parser.ParseFrom(bytes);
- Assert.AreEqual(1, parsed.MapInt32Bytes.Count);
- Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ bytes,
+ parsed=>
+ {
+ Assert.AreEqual(1, parsed.MapInt32Bytes.Count);
+ Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]);
+ });
}
[Test]
@@ -265,8 +270,13 @@
output.WriteMessage(nestedMessage);
output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ memoryStream.ToArray(),
+ parsed =>
+ {
+ Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]);
+ });
}
[Test]
@@ -282,8 +292,13 @@
output.WriteInt32(key);
output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(0.0, parsed.MapInt32Double[key]);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ memoryStream.ToArray(),
+ parsed =>
+ {
+ Assert.AreEqual(0.0, parsed.MapInt32Double[key]);
+ });
}
[Test]
@@ -299,8 +314,13 @@
output.WriteInt32(key);
output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ memoryStream.ToArray(),
+ parsed =>
+ {
+ Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]);
+ });
}
[Test]
@@ -327,8 +347,13 @@
output.WriteInt32(extra);
output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(value, parsed.MapInt32Int32[key]);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ memoryStream.ToArray(),
+ parsed =>
+ {
+ Assert.AreEqual(value, parsed.MapInt32Int32[key]);
+ });
}
[Test]
@@ -351,8 +376,13 @@
output.WriteInt32(key);
output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(value, parsed.MapInt32Int32[key]);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ memoryStream.ToArray(),
+ parsed =>
+ {
+ Assert.AreEqual(value, parsed.MapInt32Int32[key]);
+ });
}
[Test]
@@ -397,13 +427,19 @@
output.WriteInt32(value3);
output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- var expected = new TestMap
- {
- MapInt32Int32 = { { key1, value1 }, { key3, value3 } },
- MapStringString = { { key2, value2 } }
- };
- Assert.AreEqual(expected, parsed);
+
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ memoryStream.ToArray(),
+ parsed =>
+ {
+ var expected = new TestMap
+ {
+ MapInt32Int32 = { { key1, value1 }, { key3, value3 } },
+ MapStringString = { { key2, value2 } }
+ };
+ Assert.AreEqual(expected, parsed);
+ });
}
[Test]
@@ -433,8 +469,13 @@
output.WriteInt32(value2);
output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(value2, parsed.MapInt32Int32[key]);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestMap.Parser,
+ memoryStream.ToArray(),
+ parsed =>
+ {
+ Assert.AreEqual(value2, parsed.MapInt32Int32[key]);
+ });
}
[Test]
@@ -619,9 +660,10 @@
var bytes = message.ToByteArray();
Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - no string!
- var message2 = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, message2);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
+ MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message, parsedMessage =>
+ {
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, parsedMessage.OneofFieldCase);
+ });
}
[Test]
@@ -633,9 +675,10 @@
var bytes = message.ToByteArray();
Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - it's still serialized
- var message2 = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, message2);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
+ MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message, parsedMessage =>
+ {
+ Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, parsedMessage.OneofFieldCase);
+ });
}
[Test]
@@ -651,10 +694,14 @@
message.WriteTo(output);
output.Flush();
- stream.Position = 0;
- var parsed = TestAllTypes.Parser.ParseFrom(stream);
- // TODO(jieluo): Add test back when DiscardUnknownFields API is supported.
- // Assert.AreEqual(message, parsed);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestAllTypes.Parser,
+ stream.ToArray(),
+ parsed =>
+ {
+ // TODO(jieluo): Add test back when DiscardUnknownFields API is supported.
+ // Assert.AreEqual(message, parsed);
+ });
}
[Test]
@@ -663,8 +710,15 @@
// Simple way of ensuring we can skip all kinds of fields.
var data = SampleMessages.CreateFullTestAllTypes().ToByteArray();
var empty = Empty.Parser.ParseFrom(data);
- // TODO(jieluo): Add test back when DiscardUnknownFields API is supported.
- // Assert.AreNotEqual(new Empty(), empty);
+
+ MessageParsingHelpers.AssertReadingMessage(
+ Empty.Parser,
+ data,
+ parsed =>
+ {
+ // TODO(jieluo): Add test back when DiscardUnknownFields API is supported.
+ // Assert.AreNotEqual(new Empty(), empty);
+ });
}
// This was originally seen as a conformance test failure.
@@ -674,7 +728,7 @@
// 130, 3 is the message tag
// 1 is the data length - but there's no data.
var data = new byte[] { 130, 3, 1 };
- Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(data));
+ MessageParsingHelpers.AssertReadingMessageThrows<TestAllTypes, InvalidProtocolBufferException>(TestAllTypes.Parser, data);
}
/// <summary>
@@ -695,7 +749,7 @@
output.Flush();
stream.Position = 0;
- Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream));
+ MessageParsingHelpers.AssertReadingMessageThrows<TestAllTypes, InvalidProtocolBufferException>(TestAllTypes.Parser, stream.ToArray());
}
[Test]
diff --git a/csharp/src/Google.Protobuf.Test/IssuesTest.cs b/csharp/src/Google.Protobuf.Test/IssuesTest.cs
index 2caf80a..941bce0 100644
--- a/csharp/src/Google.Protobuf.Test/IssuesTest.cs
+++ b/csharp/src/Google.Protobuf.Test/IssuesTest.cs
@@ -33,6 +33,7 @@
using Google.Protobuf.Reflection;
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
+using System.IO;
using static UnitTest.Issues.TestProtos.OneofMerging.Types;
namespace Google.Protobuf
@@ -90,5 +91,26 @@
merged.MergeFrom(message2);
Assert.AreEqual(expected, merged);
}
+
+ // Check that a tag immediately followed by end of limit can still be read.
+ [Test]
+ public void CodedInputStream_LimitReachedRightAfterTag()
+ {
+ MemoryStream ms = new MemoryStream();
+ var cos = new CodedOutputStream(ms);
+ cos.WriteTag(11, WireFormat.WireType.Varint);
+ Assert.AreEqual(1, cos.Position);
+ cos.WriteString("some extra padding"); // ensure is currentLimit distinct from the end of the buffer.
+ cos.Flush();
+
+ var cis = new CodedInputStream(ms.ToArray());
+ cis.PushLimit(1); // make sure we reach the limit right after reading the tag.
+
+ // we still must read the tag correctly, even though the tag is at the very end of our limited input
+ // (which is a corner case and will most likely result in an error when trying to read value of the field
+ // decribed by this tag, but it would be a logical error not to read the tag that's actually present).
+ // See https://github.com/protocolbuffers/protobuf/pull/7289
+ cis.AssertNextTag(WireFormat.MakeTag(11, WireFormat.WireType.Varint));
+ }
}
}
diff --git a/csharp/src/Google.Protobuf.Test/LegacyGeneratedCodeTest.cs b/csharp/src/Google.Protobuf.Test/LegacyGeneratedCodeTest.cs
new file mode 100644
index 0000000..9c9846c
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/LegacyGeneratedCodeTest.cs
@@ -0,0 +1,233 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+using Google.Protobuf;
+using Google.Protobuf.Reflection;
+using System.Buffers;
+using pb = global::Google.Protobuf;
+using pbr = global::Google.Protobuf.Reflection;
+using NUnit.Framework;
+
+
+namespace Google.Protobuf
+{
+ public class LegacyGeneratedCodeTest
+ {
+ [Test]
+ public void IntermixingOfNewAndLegacyGeneratedCodeWorksWithCodedInputStream()
+ {
+ var message = new ParseContextEnabledMessageB
+ {
+ A = new LegacyGeneratedCodeMessageA
+ {
+ Bb = new ParseContextEnabledMessageB { OptionalInt32 = 12345 }
+ },
+ OptionalInt32 = 6789
+ };
+ var data = message.ToByteArray();
+
+ // when parsing started using CodedInputStream and a message with legacy generated code
+ // is encountered somewhere in the parse tree, we still need to be able to use its
+ // MergeFrom(CodedInputStream) method to parse correctly.
+ var codedInput = new CodedInputStream(data);
+ var parsed = new ParseContextEnabledMessageB();
+ codedInput.ReadRawMessage(parsed);
+ Assert.IsTrue(codedInput.IsAtEnd);
+
+ Assert.AreEqual(12345, parsed.A.Bb.OptionalInt32);
+ Assert.AreEqual(6789, parsed.OptionalInt32);
+ }
+
+ [Test]
+ public void LegacyGeneratedCodeThrowsWithReadOnlySequence()
+ {
+ var message = new ParseContextEnabledMessageB
+ {
+ A = new LegacyGeneratedCodeMessageA
+ {
+ Bb = new ParseContextEnabledMessageB { OptionalInt32 = 12345 }
+ },
+ OptionalInt32 = 6789
+ };
+ var data = message.ToByteArray();
+
+ // if parsing started using ReadOnlySequence and we don't have a CodedInputStream
+ // instance at hand, we cannot fall back to the legacy MergeFrom(CodedInputStream)
+ // method and parsing will fail. As a consequence, one can only use parsing
+ // from ReadOnlySequence if all the messages in the parsing tree have their generated
+ // code up to date.
+ var exception = Assert.Throws<InvalidProtocolBufferException>(() =>
+ {
+ ParseContext.Initialize(new ReadOnlySequence<byte>(data), out ParseContext parseCtx);
+ var parsed = new ParseContextEnabledMessageB();
+ ParsingPrimitivesMessages.ReadRawMessage(ref parseCtx, parsed);
+ });
+ Assert.AreEqual($"Message {typeof(LegacyGeneratedCodeMessageA).Name} doesn't provide the generated method that enables ParseContext-based parsing. You might need to regenerate the generated protobuf code.", exception.Message);
+ }
+
+ // hand-modified version of a generated message that only provides the legacy
+ // MergeFrom(CodedInputStream) method and doesn't implement IBufferMessage.
+ private sealed partial class LegacyGeneratedCodeMessageA : pb::IMessage {
+ private pb::UnknownFieldSet _unknownFields;
+
+ pbr::MessageDescriptor pb::IMessage.Descriptor => throw new System.NotImplementedException();
+
+ /// <summary>Field number for the "bb" field.</summary>
+ public const int BbFieldNumber = 1;
+ private ParseContextEnabledMessageB bb_;
+ public ParseContextEnabledMessageB Bb {
+ get { return bb_; }
+ set {
+ bb_ = value;
+ }
+ }
+
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (bb_ != null) {
+ output.WriteRawTag(10);
+ output.WriteMessage(Bb);
+ }
+ if (_unknownFields != null) {
+ _unknownFields.WriteTo(output);
+ }
+ }
+
+ public int CalculateSize() {
+ int size = 0;
+ if (bb_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(Bb);
+ }
+ if (_unknownFields != null) {
+ size += _unknownFields.CalculateSize();
+ }
+ return size;
+ }
+
+ public void MergeFrom(pb::CodedInputStream input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ break;
+ case 10: {
+ if (bb_ == null) {
+ Bb = new ParseContextEnabledMessageB();
+ }
+ input.ReadMessage(Bb);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // hand-modified version of a generated message that does provide
+ // the new InternalMergeFrom(ref ParseContext) method.
+ private sealed partial class ParseContextEnabledMessageB : pb::IBufferMessage {
+ private pb::UnknownFieldSet _unknownFields;
+
+ pbr::MessageDescriptor pb::IMessage.Descriptor => throw new System.NotImplementedException();
+
+ /// <summary>Field number for the "a" field.</summary>
+ public const int AFieldNumber = 1;
+ private LegacyGeneratedCodeMessageA a_;
+ public LegacyGeneratedCodeMessageA A {
+ get { return a_; }
+ set {
+ a_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "optional_int32" field.</summary>
+ public const int OptionalInt32FieldNumber = 2;
+ private int optionalInt32_;
+ public int OptionalInt32 {
+ get { return optionalInt32_; }
+ set {
+ optionalInt32_ = value;
+ }
+ }
+
+ public void WriteTo(pb::CodedOutputStream output) {
+ if (a_ != null) {
+ output.WriteRawTag(10);
+ output.WriteMessage(A);
+ }
+ if (OptionalInt32 != 0) {
+ output.WriteRawTag(16);
+ output.WriteInt32(OptionalInt32);
+ }
+ if (_unknownFields != null) {
+ _unknownFields.WriteTo(output);
+ }
+ }
+ public int CalculateSize() {
+ int size = 0;
+ if (a_ != null) {
+ size += 1 + pb::CodedOutputStream.ComputeMessageSize(A);
+ }
+ if (OptionalInt32 != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeInt32Size(OptionalInt32);
+ }
+ if (_unknownFields != null) {
+ size += _unknownFields.CalculateSize();
+ }
+ return size;
+ }
+ public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
+ uint tag;
+ while ((tag = input.ReadTag()) != 0) {
+ switch(tag) {
+ default:
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
+ break;
+ case 10: {
+ if (a_ == null) {
+ A = new LegacyGeneratedCodeMessageA();
+ }
+ input.ReadMessage(A);
+ break;
+ }
+ case 16: {
+ OptionalInt32 = input.ReadInt32();
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/MessageParsingHelpers.cs b/csharp/src/Google.Protobuf.Test/MessageParsingHelpers.cs
new file mode 100644
index 0000000..ec5f13a
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/MessageParsingHelpers.cs
@@ -0,0 +1,100 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using NUnit.Framework;
+using System;
+using System.Buffers;
+
+namespace Google.Protobuf
+{
+ public static class MessageParsingHelpers
+ {
+ public static void AssertReadingMessage<T>(MessageParser<T> parser, byte[] bytes, Action<T> assert) where T : IMessage<T>
+ {
+ var parsedStream = parser.ParseFrom(bytes);
+
+ // Load content as single segment
+ var parsedBuffer = parser.ParseFrom(new ReadOnlySequence<byte>(bytes));
+ assert(parsedBuffer);
+
+ // Load content as multiple segments
+ parsedBuffer = parser.ParseFrom(ReadOnlySequenceFactory.CreateWithContent(bytes));
+ assert(parsedBuffer);
+
+ assert(parsedStream);
+ }
+
+ public static void AssertReadingMessage(MessageParser parser, byte[] bytes, Action<IMessage> assert)
+ {
+ var parsedStream = parser.ParseFrom(bytes);
+
+ // Load content as single segment
+ var parsedBuffer = parser.ParseFrom(new ReadOnlySequence<byte>(bytes));
+ assert(parsedBuffer);
+
+ // Load content as multiple segments
+ parsedBuffer = parser.ParseFrom(ReadOnlySequenceFactory.CreateWithContent(bytes));
+ assert(parsedBuffer);
+
+ assert(parsedStream);
+ }
+
+ public static void AssertReadingMessageThrows<TMessage, TException>(MessageParser<TMessage> parser, byte[] bytes)
+ where TMessage : IMessage<TMessage>
+ where TException : Exception
+ {
+ Assert.Throws<TException>(() => parser.ParseFrom(bytes));
+
+ Assert.Throws<TException>(() => parser.ParseFrom(new ReadOnlySequence<byte>(bytes)));
+ }
+
+ public static void AssertRoundtrip<T>(MessageParser<T> parser, T message, Action<T> additionalAssert = null) where T : IMessage<T>
+ {
+ var bytes = message.ToByteArray();
+
+ // Load content as single segment
+ var parsedBuffer = parser.ParseFrom(new ReadOnlySequence<byte>(bytes));
+ Assert.AreEqual(message, parsedBuffer);
+ additionalAssert?.Invoke(parsedBuffer);
+
+ // Load content as multiple segments
+ parsedBuffer = parser.ParseFrom(ReadOnlySequenceFactory.CreateWithContent(bytes));
+ Assert.AreEqual(message, parsedBuffer);
+ additionalAssert?.Invoke(parsedBuffer);
+
+ var parsedStream = parser.ParseFrom(bytes);
+
+ Assert.AreEqual(message, parsedStream);
+ additionalAssert?.Invoke(parsedStream);
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs b/csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs
new file mode 100644
index 0000000..20c1846
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs
@@ -0,0 +1,143 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using NUnit.Framework;
+using ProtobufUnittest;
+using System;
+using System.IO;
+
+namespace Google.Protobuf.Test
+{
+ class Proto3OptionalTest
+ {
+ [Test]
+ public void OptionalInt32FieldLifecycle()
+ {
+ var message = new TestProto3Optional();
+ Assert.IsFalse(message.HasOptionalInt32);
+ Assert.AreEqual(0, message.OptionalInt32);
+
+ message.OptionalInt32 = 5;
+ Assert.IsTrue(message.HasOptionalInt32);
+ Assert.AreEqual(5, message.OptionalInt32);
+
+ message.OptionalInt32 = 0;
+ Assert.IsTrue(message.HasOptionalInt32);
+ Assert.AreEqual(0, message.OptionalInt32);
+
+ message.ClearOptionalInt32();
+ Assert.IsFalse(message.HasOptionalInt32);
+ Assert.AreEqual(0, message.OptionalInt32);
+ }
+
+ [Test]
+ public void OptionalStringFieldLifecycle()
+ {
+ var message = new TestProto3Optional();
+ Assert.IsFalse(message.HasOptionalString);
+ Assert.AreEqual("", message.OptionalString);
+
+ message.OptionalString = "x";
+ Assert.IsTrue(message.HasOptionalString);
+ Assert.AreEqual("x", message.OptionalString);
+
+ message.OptionalString = "";
+ Assert.IsTrue(message.HasOptionalString);
+ Assert.AreEqual("", message.OptionalString);
+
+ message.ClearOptionalString();
+ Assert.IsFalse(message.HasOptionalString);
+ Assert.AreEqual("", message.OptionalString);
+
+ Assert.Throws<ArgumentNullException>(() => message.OptionalString = null);
+ }
+
+ [Test]
+ public void Clone()
+ {
+ var original = new TestProto3Optional { OptionalInt64 = 0L };
+
+ var clone = original.Clone();
+ Assert.False(clone.HasOptionalInt32);
+ Assert.AreEqual(0, clone.OptionalInt32);
+ Assert.True(clone.HasOptionalInt64);
+ Assert.AreEqual(0L, clone.OptionalInt64);
+ }
+
+ [Test]
+ public void Serialization_NotSet()
+ {
+ var stream = new MemoryStream();
+ var message = new TestProto3Optional();
+ message.WriteTo(stream);
+ Assert.AreEqual(0, stream.Length);
+ }
+
+ [Test]
+ public void Serialization_SetToDefault()
+ {
+ var stream = new MemoryStream();
+ var message = new TestProto3Optional { OptionalInt32 = 0 };
+ message.WriteTo(stream);
+ Assert.AreEqual(2, stream.Length); // Tag and value
+ }
+
+ [Test]
+ public void Serialization_Roundtrip()
+ {
+ var original = new TestProto3Optional { OptionalInt64 = 0L, OptionalFixed32 = 5U };
+ var stream = new MemoryStream();
+ original.WriteTo(stream);
+ stream.Position = 0;
+ var deserialized = TestProto3Optional.Parser.ParseFrom(stream);
+
+ Assert.AreEqual(0, deserialized.OptionalInt32);
+ Assert.IsFalse(deserialized.HasOptionalInt32);
+
+ Assert.AreEqual(0L, deserialized.OptionalInt64);
+ Assert.IsTrue(deserialized.HasOptionalInt64);
+
+ Assert.AreEqual(5U, deserialized.OptionalFixed32);
+ Assert.IsTrue(deserialized.HasOptionalFixed32);
+ }
+
+ [Test]
+ public void Equality_IgnoresPresence()
+ {
+ var message1 = new TestProto3Optional { OptionalInt32 = 0 };
+ var message2 = new TestProto3Optional();
+
+ Assert.IsTrue(message1.Equals(message2));
+ message1.ClearOptionalInt32();
+ }
+ }
+}
diff --git a/csharp/src/Google.Protobuf.Test/ReadOnlySequenceFactory.cs b/csharp/src/Google.Protobuf.Test/ReadOnlySequenceFactory.cs
new file mode 100644
index 0000000..d2050d3
--- /dev/null
+++ b/csharp/src/Google.Protobuf.Test/ReadOnlySequenceFactory.cs
@@ -0,0 +1,128 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Buffers;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Google.Protobuf
+{
+ internal static class ReadOnlySequenceFactory
+ {
+ public static ReadOnlySequence<byte> CreateWithContent(byte[] data, int segmentSize = 1)
+ {
+ var segments = new List<byte[]>();
+
+ segments.Add(new byte[0]);
+ var currentIndex = 0;
+ while (currentIndex < data.Length)
+ {
+ var segment = new List<byte>();
+ for (; currentIndex < Math.Min(currentIndex + segmentSize, data.Length); currentIndex++)
+ {
+ segment.Add(data[currentIndex]);
+ }
+ segments.Add(segment.ToArray());
+ segments.Add(new byte[0]);
+ }
+
+ return CreateSegments(segments.ToArray());
+ }
+
+ /// <summary>
+ /// Originally from corefx, and has been contributed to Protobuf
+ /// https://github.com/dotnet/corefx/blob/e99ec129cfd594d53f4390bf97d1d736cff6f860/src/System.Memory/tests/ReadOnlyBuffer/ReadOnlySequenceFactory.byte.cs
+ /// </summary>
+ private static ReadOnlySequence<byte> CreateSegments(params byte[][] inputs)
+ {
+ if (inputs == null || inputs.Length == 0)
+ {
+ throw new InvalidOperationException();
+ }
+
+ int i = 0;
+
+ BufferSegment last = null;
+ BufferSegment first = null;
+
+ do
+ {
+ byte[] s = inputs[i];
+ int length = s.Length;
+ int dataOffset = length;
+ var chars = new byte[length * 2];
+
+ for (int j = 0; j < length; j++)
+ {
+ chars[dataOffset + j] = s[j];
+ }
+
+ // Create a segment that has offset relative to the OwnedMemory and OwnedMemory itself has offset relative to array
+ var memory = new Memory<byte>(chars).Slice(length, length);
+
+ if (first == null)
+ {
+ first = new BufferSegment(memory);
+ last = first;
+ }
+ else
+ {
+ last = last.Append(memory);
+ }
+ i++;
+ } while (i < inputs.Length);
+
+ return new ReadOnlySequence<byte>(first, 0, last, last.Memory.Length);
+ }
+
+ private class BufferSegment : ReadOnlySequenceSegment<byte>
+ {
+ public BufferSegment(Memory<byte> memory)
+ {
+ Memory = memory;
+ }
+
+ public BufferSegment Append(Memory<byte> memory)
+ {
+ var segment = new BufferSegment(memory)
+ {
+ RunningIndex = RunningIndex + Memory.Length
+ };
+ Next = segment;
+ return segment;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs
index d65a6f2..68b9bd3 100644
--- a/csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Reflection/CustomOptionsTest.cs
@@ -1,4 +1,4 @@
-#region Copyright notice and license
+#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2017 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
@@ -72,24 +72,48 @@
}
[Test]
+ public void BuiltinOptionsCanBeRetrieved()
+ {
+ // non-custom options (that are not extensions but regular fields) can only be accessed via descriptor.Options
+ var fileOptions = UnittestProto3Reflection.Descriptor.GetOptions();
+ Assert.AreEqual("Google.Protobuf.TestProtos", fileOptions.CsharpNamespace);
+ }
+
+ [Test]
+ public void OptionPresenceCanBeDetected()
+ {
+ // case 1: the descriptor has no options at all so the options message is not present
+ Assert.IsNull(TestAllTypes.Descriptor.GetOptions());
+
+ // case 2: the descriptor has some options, but not the one we're looking for
+ // HasExtension will be false and GetExtension returns extension's default value
+ Assert.IsFalse(UnittestProto3Reflection.Descriptor.GetOptions().HasExtension(FileOpt1));
+ Assert.AreEqual(0, UnittestProto3Reflection.Descriptor.GetOptions().GetExtension(FileOpt1));
+
+ // case 3: option is present
+ Assert.IsTrue(UnittestCustomOptionsProto3Reflection.Descriptor.GetOptions().HasExtension(FileOpt1));
+ Assert.AreEqual(9876543210UL, UnittestCustomOptionsProto3Reflection.Descriptor.GetOptions().GetExtension(FileOpt1));
+ }
+
+ [Test]
public void ScalarOptions()
{
var d = CustomOptionOtherValues.Descriptor;
- var options = d.CustomOptions;
- AssertOption(-100, options.TryGetInt32, Int32Opt, d.GetOption);
- AssertOption(12.3456789f, options.TryGetFloat, FloatOpt, d.GetOption);
- AssertOption(1.234567890123456789d, options.TryGetDouble, DoubleOpt, d.GetOption);
- AssertOption("Hello, \"World\"", options.TryGetString, StringOpt, d.GetOption);
- AssertOption(ByteString.CopyFromUtf8("Hello\0World"), options.TryGetBytes, BytesOpt, d.GetOption);
- AssertOption(TestEnumType.TestOptionEnumType2, EnumFetcher<TestEnumType>(options), EnumOpt, d.GetOption);
+ var customOptions = d.CustomOptions;
+ AssertOption(-100, customOptions.TryGetInt32, Int32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(12.3456789f, customOptions.TryGetFloat, FloatOpt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(1.234567890123456789d, customOptions.TryGetDouble, DoubleOpt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption("Hello, \"World\"", customOptions.TryGetString, StringOpt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(ByteString.CopyFromUtf8("Hello\0World"), customOptions.TryGetBytes, BytesOpt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(TestEnumType.TestOptionEnumType2, EnumFetcher<TestEnumType>(customOptions), EnumOpt, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void MessageOptions()
{
var d = VariousComplexOptions.Descriptor;
- var options = d.CustomOptions;
- AssertOption(new ComplexOptionType1 { Foo = 42, Foo4 = { 99, 88 } }, options.TryGetMessage, ComplexOpt1, d.GetOption);
+ var customOptions = d.CustomOptions;
+ AssertOption(new ComplexOptionType1 { Foo = 42, Foo4 = { 99, 88 } }, customOptions.TryGetMessage, ComplexOpt1, d.GetOption, d.GetOptions().GetExtension);
AssertOption(new ComplexOptionType2
{
Baz = 987,
@@ -97,85 +121,84 @@
Fred = new ComplexOptionType4 { Waldo = 321 },
Barney = { new ComplexOptionType4 { Waldo = 101 }, new ComplexOptionType4 { Waldo = 212 } }
},
- options.TryGetMessage, ComplexOpt2, d.GetOption);
- AssertOption(new ComplexOptionType3 { Qux = 9 }, options.TryGetMessage, ComplexOpt3, d.GetOption);
+ customOptions.TryGetMessage, ComplexOpt2, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(new ComplexOptionType3 { Qux = 9 }, customOptions.TryGetMessage, ComplexOpt3, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void OptionLocations()
{
- var fileOptions = UnittestCustomOptionsProto3Reflection.Descriptor.CustomOptions;
- AssertOption(9876543210UL, fileOptions.TryGetUInt64, FileOpt1, UnittestCustomOptionsProto3Reflection.Descriptor.GetOption);
+ var fileDescriptor = UnittestCustomOptionsProto3Reflection.Descriptor;
+ AssertOption(9876543210UL, fileDescriptor.CustomOptions.TryGetUInt64, FileOpt1, fileDescriptor.GetOption, fileDescriptor.GetOptions().GetExtension);
- var messageOptions = TestMessageWithCustomOptions.Descriptor.CustomOptions;
- AssertOption(-56, messageOptions.TryGetInt32, MessageOpt1, TestMessageWithCustomOptions.Descriptor.GetOption);
+ var messageDescriptor = TestMessageWithCustomOptions.Descriptor;
+ AssertOption(-56, messageDescriptor.CustomOptions.TryGetInt32, MessageOpt1, messageDescriptor.GetOption, messageDescriptor.GetOptions().GetExtension);
- var fieldOptions = TestMessageWithCustomOptions.Descriptor.Fields["field1"].CustomOptions;
- AssertOption(8765432109UL, fieldOptions.TryGetFixed64, FieldOpt1, TestMessageWithCustomOptions.Descriptor.Fields["field1"].GetOption);
+ var fieldDescriptor = TestMessageWithCustomOptions.Descriptor.Fields["field1"];
+ AssertOption(8765432109UL, fieldDescriptor.CustomOptions.TryGetFixed64, FieldOpt1, fieldDescriptor.GetOption, fieldDescriptor.GetOptions().GetExtension);
- var oneofOptions = TestMessageWithCustomOptions.Descriptor.Oneofs[0].CustomOptions;
- AssertOption(-99, oneofOptions.TryGetInt32, OneofOpt1, TestMessageWithCustomOptions.Descriptor.Oneofs[0].GetOption);
+ var oneofDescriptor = TestMessageWithCustomOptions.Descriptor.Oneofs[0];
+ AssertOption(-99, oneofDescriptor.CustomOptions.TryGetInt32, OneofOpt1, oneofDescriptor.GetOption, oneofDescriptor.GetOptions().GetExtension);
- var enumOptions = TestMessageWithCustomOptions.Descriptor.EnumTypes[0].CustomOptions;
- AssertOption(-789, enumOptions.TryGetSFixed32, EnumOpt1, TestMessageWithCustomOptions.Descriptor.EnumTypes[0].GetOption);
+ var enumDescriptor = TestMessageWithCustomOptions.Descriptor.EnumTypes[0];
+ AssertOption(-789, enumDescriptor.CustomOptions.TryGetSFixed32, EnumOpt1, enumDescriptor.GetOption, enumDescriptor.GetOptions().GetExtension);
- var enumValueOptions = TestMessageWithCustomOptions.Descriptor.EnumTypes[0].FindValueByNumber(2).CustomOptions;
- AssertOption(123, enumValueOptions.TryGetInt32, EnumValueOpt1, TestMessageWithCustomOptions.Descriptor.EnumTypes[0].FindValueByNumber(2).GetOption);
+ var enumValueDescriptor = TestMessageWithCustomOptions.Descriptor.EnumTypes[0].FindValueByNumber(2);
+ AssertOption(123, enumValueDescriptor.CustomOptions.TryGetInt32, EnumValueOpt1, enumValueDescriptor.GetOption, enumValueDescriptor.GetOptions().GetExtension);
- var service = UnittestCustomOptionsProto3Reflection.Descriptor.Services
+ var serviceDescriptor = UnittestCustomOptionsProto3Reflection.Descriptor.Services
.Single(s => s.Name == "TestServiceWithCustomOptions");
- var serviceOptions = service.CustomOptions;
- AssertOption(-9876543210, serviceOptions.TryGetSInt64, ServiceOpt1, service.GetOption);
+ AssertOption(-9876543210, serviceDescriptor.CustomOptions.TryGetSInt64, ServiceOpt1, serviceDescriptor.GetOption, serviceDescriptor.GetOptions().GetExtension);
- var methodOptions = service.Methods[0].CustomOptions;
- AssertOption(UnitTest.Issues.TestProtos.MethodOpt1.Val2, EnumFetcher<UnitTest.Issues.TestProtos.MethodOpt1>(methodOptions), UnittestCustomOptionsProto3Extensions.MethodOpt1, service.Methods[0].GetOption);
+ var methodDescriptor = serviceDescriptor.Methods[0];
+ AssertOption(UnitTest.Issues.TestProtos.MethodOpt1.Val2, EnumFetcher<UnitTest.Issues.TestProtos.MethodOpt1>(methodDescriptor.CustomOptions), UnittestCustomOptionsProto3Extensions.MethodOpt1, methodDescriptor.GetOption, methodDescriptor.GetOptions().GetExtension);
}
[Test]
public void MinValues()
{
var d = CustomOptionMinIntegerValues.Descriptor;
- var options = d.CustomOptions;
- AssertOption(false, options.TryGetBool, BoolOpt, d.GetOption);
- AssertOption(int.MinValue, options.TryGetInt32, Int32Opt, d.GetOption);
- AssertOption(long.MinValue, options.TryGetInt64, Int64Opt, d.GetOption);
- AssertOption(uint.MinValue, options.TryGetUInt32, Uint32Opt, d.GetOption);
- AssertOption(ulong.MinValue, options.TryGetUInt64, Uint64Opt, d.GetOption);
- AssertOption(int.MinValue, options.TryGetSInt32, Sint32Opt, d.GetOption);
- AssertOption(long.MinValue, options.TryGetSInt64, Sint64Opt, d.GetOption);
- AssertOption(uint.MinValue, options.TryGetUInt32, Fixed32Opt, d.GetOption);
- AssertOption(ulong.MinValue, options.TryGetUInt64, Fixed64Opt, d.GetOption);
- AssertOption(int.MinValue, options.TryGetInt32, Sfixed32Opt, d.GetOption);
- AssertOption(long.MinValue, options.TryGetInt64, Sfixed64Opt, d.GetOption);
+ var customOptions = d.CustomOptions;
+ AssertOption(false, customOptions.TryGetBool, BoolOpt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(int.MinValue, customOptions.TryGetInt32, Int32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(long.MinValue, customOptions.TryGetInt64, Int64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(uint.MinValue, customOptions.TryGetUInt32, Uint32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(ulong.MinValue, customOptions.TryGetUInt64, Uint64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(int.MinValue, customOptions.TryGetSInt32, Sint32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(long.MinValue, customOptions.TryGetSInt64, Sint64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(uint.MinValue, customOptions.TryGetUInt32, Fixed32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(ulong.MinValue, customOptions.TryGetUInt64, Fixed64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(int.MinValue, customOptions.TryGetInt32, Sfixed32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(long.MinValue, customOptions.TryGetInt64, Sfixed64Opt, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void MaxValues()
{
var d = CustomOptionMaxIntegerValues.Descriptor;
- var options = d.CustomOptions;
- AssertOption(true, options.TryGetBool, BoolOpt, d.GetOption);
- AssertOption(int.MaxValue, options.TryGetInt32, Int32Opt, d.GetOption);
- AssertOption(long.MaxValue, options.TryGetInt64, Int64Opt, d.GetOption);
- AssertOption(uint.MaxValue, options.TryGetUInt32, Uint32Opt, d.GetOption);
- AssertOption(ulong.MaxValue, options.TryGetUInt64, Uint64Opt, d.GetOption);
- AssertOption(int.MaxValue, options.TryGetSInt32, Sint32Opt, d.GetOption);
- AssertOption(long.MaxValue, options.TryGetSInt64, Sint64Opt, d.GetOption);
- AssertOption(uint.MaxValue, options.TryGetFixed32, Fixed32Opt, d.GetOption);
- AssertOption(ulong.MaxValue, options.TryGetFixed64, Fixed64Opt, d.GetOption);
- AssertOption(int.MaxValue, options.TryGetSFixed32, Sfixed32Opt, d.GetOption);
- AssertOption(long.MaxValue, options.TryGetSFixed64, Sfixed64Opt, d.GetOption);
+ var customOptions = d.CustomOptions;
+ AssertOption(true, customOptions.TryGetBool, BoolOpt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(int.MaxValue, customOptions.TryGetInt32, Int32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(long.MaxValue, customOptions.TryGetInt64, Int64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(uint.MaxValue, customOptions.TryGetUInt32, Uint32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(ulong.MaxValue, customOptions.TryGetUInt64, Uint64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(int.MaxValue, customOptions.TryGetSInt32, Sint32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(long.MaxValue, customOptions.TryGetSInt64, Sint64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(uint.MaxValue, customOptions.TryGetFixed32, Fixed32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(ulong.MaxValue, customOptions.TryGetFixed64, Fixed64Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(int.MaxValue, customOptions.TryGetSFixed32, Sfixed32Opt, d.GetOption, d.GetOptions().GetExtension);
+ AssertOption(long.MaxValue, customOptions.TryGetSFixed64, Sfixed64Opt, d.GetOption, d.GetOptions().GetExtension);
}
[Test]
public void AggregateOptions()
{
// Just two examples
- var messageOptions = AggregateMessage.Descriptor.CustomOptions;
- AssertOption(new Aggregate { I = 101, S = "MessageAnnotation" }, messageOptions.TryGetMessage, Msgopt, AggregateMessage.Descriptor.GetOption);
+ var messageDescriptor = AggregateMessage.Descriptor;
+ AssertOption(new Aggregate { I = 101, S = "MessageAnnotation" }, messageDescriptor.CustomOptions.TryGetMessage, Msgopt, messageDescriptor.GetOption, messageDescriptor.GetOptions().GetExtension);
- var fieldOptions = AggregateMessage.Descriptor.Fields["fieldname"].CustomOptions;
- AssertOption(new Aggregate { S = "FieldAnnotation" }, fieldOptions.TryGetMessage, Fieldopt, AggregateMessage.Descriptor.Fields["fieldname"].GetOption);
+ var fieldDescriptor = messageDescriptor.Fields["fieldname"];
+ AssertOption(new Aggregate { S = "FieldAnnotation" }, fieldDescriptor.CustomOptions.TryGetMessage, Fieldopt, fieldDescriptor.GetOption, fieldDescriptor.GetOptions().GetExtension);
}
[Test]
@@ -193,12 +216,47 @@
Assert.NotNull(TestAllTypes.Descriptor.Oneofs[0].CustomOptions);
}
- private void AssertOption<T, D>(T expected, OptionFetcher<T> fetcher, Extension<D, T> extension, Func<Extension<D, T>, T> descriptorOptionFetcher) where D : IExtendableMessage<D>
+ [Test]
+ public void MultipleImportOfSameFileWithExtension()
{
- T customOptionsValue;
- T extensionValue = descriptorOptionFetcher(extension);
- Assert.IsTrue(fetcher(extension.FieldNumber, out customOptionsValue));
+ var descriptor = UnittestIssue6936CReflection.Descriptor;
+ var foo = Foo.Descriptor;
+ var bar = Bar.Descriptor;
+ AssertOption("foo", foo.CustomOptions.TryGetString, UnittestIssue6936AExtensions.Opt, foo.GetOption, foo.GetOptions().GetExtension);
+ AssertOption("bar", bar.CustomOptions.TryGetString, UnittestIssue6936AExtensions.Opt, bar.GetOption, bar.GetOptions().GetExtension);
+ }
+
+ [Test]
+ public void SelfReferentialOptions()
+ {
+ // Custom field option used in definition of the custom option's message.
+ var fooField = UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Descriptor.FindFieldByName("foo");
+ var fooFieldFooExtensionValue = fooField.GetOptions().GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooOptions);
+ Assert.AreEqual(1234, fooFieldFooExtensionValue.Foo);
+
+ // Custom field option used on the definition of that field option.
+ var fileDescriptor = UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsReflection.Descriptor;
+ var barOptionsField = fileDescriptor.Extensions.UnorderedExtensions.Single(field => field.Name == "bar_options");
+ var barExtensionValue = barOptionsField.GetOptions().GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.BarOptions);
+ Assert.AreEqual(1234, barExtensionValue);
+
+ // Custom field option used in definition of the extension message.
+ var intOptField = UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Descriptor.FindFieldByName("int_opt");
+ var intOptFieldFooExtensionValue = intOptField.GetOptions().GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooOptions);
+ Assert.AreEqual(1, intOptFieldFooExtensionValue.IntOpt);
+ Assert.AreEqual(2, intOptFieldFooExtensionValue.GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooIntOpt));
+ Assert.AreEqual(3, intOptFieldFooExtensionValue.GetExtension(UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsExtensions.FooFooOpt).IntOpt);
+ }
+
+ private void AssertOption<T, D>(T expected, OptionFetcher<T> customOptionFetcher, Extension<D, T> extension, Func<Extension<D, T>, T> getOptionFetcher, Func<Extension<D, T>, T> extensionFetcher) where D : IExtendableMessage<D>
+ {
+ Assert.IsTrue(customOptionFetcher(extension.FieldNumber, out T customOptionsValue));
Assert.AreEqual(expected, customOptionsValue);
+
+ T getOptionValue = getOptionFetcher(extension);
+ Assert.AreEqual(expected, getOptionValue);
+
+ T extensionValue = extensionFetcher(extension);
Assert.AreEqual(expected, extensionValue);
}
}
diff --git a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
index 482db53..ebb8394 100644
--- a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
@@ -32,6 +32,7 @@
using Google.Protobuf.TestProtos;
using NUnit.Framework;
+using ProtobufUnittest;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -247,6 +248,7 @@
FieldDescriptor enumField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_nested_enum");
FieldDescriptor foreignMessageField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_foreign_message");
FieldDescriptor importMessageField = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("single_import_message");
+ FieldDescriptor fieldInOneof = testAllTypesDescriptor.FindDescriptor<FieldDescriptor>("oneof_string");
Assert.AreEqual("single_int32", primitiveField.Name);
Assert.AreEqual("protobuf_unittest3.TestAllTypes.single_int32",
@@ -268,6 +270,10 @@
Assert.AreEqual("single_import_message", importMessageField.Name);
Assert.AreEqual(FieldType.Message, importMessageField.FieldType);
Assert.AreEqual(importMessageDescriptor, importMessageField.MessageType);
+
+ // For a field in a regular onoef, ContainingOneof and RealContainingOneof should be the same.
+ Assert.AreEqual("oneof_field", fieldInOneof.ContainingOneof.Name);
+ Assert.AreSame(fieldInOneof.ContainingOneof, fieldInOneof.RealContainingOneof);
}
[Test]
@@ -318,6 +324,7 @@
public void OneofDescriptor()
{
OneofDescriptor descriptor = TestAllTypes.Descriptor.FindDescriptor<OneofDescriptor>("oneof_field");
+ Assert.IsFalse(descriptor.IsSynthetic);
Assert.AreEqual("oneof_field", descriptor.Name);
Assert.AreEqual("protobuf_unittest3.TestAllTypes.oneof_field", descriptor.FullName);
@@ -383,5 +390,48 @@
var importingDescriptor = TestProtos.OldGenerator.OldExtensions1Reflection.Descriptor;
Assert.NotNull(importingDescriptor);
}
+
+ [Test]
+ public void Proto3OptionalDescriptors()
+ {
+ var descriptor = TestProto3Optional.Descriptor;
+ var field = descriptor.Fields[TestProto3Optional.OptionalInt32FieldNumber];
+ Assert.NotNull(field.ContainingOneof);
+ Assert.IsTrue(field.ContainingOneof.IsSynthetic);
+ Assert.Null(field.RealContainingOneof);
+ }
+
+
+ [Test]
+ public void SyntheticOneofReflection()
+ {
+ // Expect every oneof in TestProto3Optional to be synthetic
+ var proto3OptionalDescriptor = TestProto3Optional.Descriptor;
+ Assert.AreEqual(0, proto3OptionalDescriptor.RealOneofCount);
+ foreach (var oneof in proto3OptionalDescriptor.Oneofs)
+ {
+ Assert.True(oneof.IsSynthetic);
+ }
+
+ // Expect no oneof in the original proto3 unit test file to be synthetic.
+ foreach (var descriptor in ProtobufTestMessages.Proto3.TestMessagesProto3Reflection.Descriptor.MessageTypes)
+ {
+ Assert.AreEqual(descriptor.Oneofs.Count, descriptor.RealOneofCount);
+ foreach (var oneof in descriptor.Oneofs)
+ {
+ Assert.False(oneof.IsSynthetic);
+ }
+ }
+
+ // Expect no oneof in the original proto2 unit test file to be synthetic.
+ foreach (var descriptor in ProtobufTestMessages.Proto2.TestMessagesProto2Reflection.Descriptor.MessageTypes)
+ {
+ Assert.AreEqual(descriptor.Oneofs.Count, descriptor.RealOneofCount);
+ foreach (var oneof in descriptor.Oneofs)
+ {
+ Assert.False(oneof.IsSynthetic);
+ }
+ }
+ }
}
}
diff --git a/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs
index 9651ec3..b4dcdab 100644
--- a/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs
@@ -38,6 +38,7 @@
using System.Collections.Generic;
using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions;
+using ProtobufUnittest;
namespace Google.Protobuf.Reflection
{
@@ -97,7 +98,48 @@
}
[Test]
- public void HasValue_Proto3()
+ public void HasValue_Proto3_Message()
+ {
+ var message = new TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[TestProtos.TestAllTypes.SingleForeignMessageFieldNumber].Accessor;
+ Assert.False(accessor.HasValue(message));
+ message.SingleForeignMessage = new ForeignMessage();
+ Assert.True(accessor.HasValue(message));
+ message.SingleForeignMessage = null;
+ Assert.False(accessor.HasValue(message));
+ }
+
+ [Test]
+ public void HasValue_Proto3_Oneof()
+ {
+ TestAllTypes message = new TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[TestProtos.TestAllTypes.OneofStringFieldNumber].Accessor;
+ Assert.False(accessor.HasValue(message));
+ // Even though it's the default value, we still have a value.
+ message.OneofString = "";
+ Assert.True(accessor.HasValue(message));
+ message.OneofString = "hello";
+ Assert.True(accessor.HasValue(message));
+ message.OneofUint32 = 10;
+ Assert.False(accessor.HasValue(message));
+ }
+
+ [Test]
+ public void HasValue_Proto3_Primitive_Optional()
+ {
+ var message = new TestProto3Optional();
+ var accessor = ((IMessage) message).Descriptor.Fields[TestProto3Optional.OptionalInt64FieldNumber].Accessor;
+ Assert.IsFalse(accessor.HasValue(message));
+ message.OptionalInt64 = 5L;
+ Assert.IsTrue(accessor.HasValue(message));
+ message.ClearOptionalInt64();
+ Assert.IsFalse(accessor.HasValue(message));
+ message.OptionalInt64 = 0L;
+ Assert.IsTrue(accessor.HasValue(message));
+ }
+
+ [Test]
+ public void HasValue_Proto3_Primitive_NotOptional()
{
IMessage message = SampleMessages.CreateFullTestAllTypes();
var fields = message.Descriptor.Fields;
@@ -105,22 +147,64 @@
}
[Test]
- public void HasValue()
+ public void HasValue_Proto3_Repeated()
{
- IMessage message = new Proto2.TestAllTypes();
- var fields = message.Descriptor.Fields;
- var accessor = fields[Proto2.TestAllTypes.OptionalBoolFieldNumber].Accessor;
+ var message = new TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[TestProtos.TestAllTypes.RepeatedBoolFieldNumber].Accessor;
+ Assert.Throws<InvalidOperationException>(() => accessor.HasValue(message));
+ }
+ [Test]
+ public void HasValue_Proto2_Primitive()
+ {
+ var message = new Proto2.TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[Proto2.TestAllTypes.OptionalInt64FieldNumber].Accessor;
+
+ Assert.IsFalse(accessor.HasValue(message));
+ message.OptionalInt64 = 5L;
+ Assert.IsTrue(accessor.HasValue(message));
+ message.ClearOptionalInt64();
+ Assert.IsFalse(accessor.HasValue(message));
+ message.OptionalInt64 = 0L;
+ Assert.IsTrue(accessor.HasValue(message));
+ }
+
+ [Test]
+ public void HasValue_Proto2_Message()
+ {
+ var message = new Proto2.TestAllTypes();
+ var field = ((IMessage) message).Descriptor.Fields[Proto2.TestAllTypes.OptionalForeignMessageFieldNumber];
+ Assert.False(field.Accessor.HasValue(message));
+ message.OptionalForeignMessage = new Proto2.ForeignMessage();
+ Assert.True(field.Accessor.HasValue(message));
+ message.OptionalForeignMessage = null;
+ Assert.False(field.Accessor.HasValue(message));
+ }
+
+ [Test]
+ public void HasValue_Proto2_Oneof()
+ {
+ var message = new Proto2.TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[Proto2.TestAllTypes.OneofStringFieldNumber].Accessor;
Assert.False(accessor.HasValue(message));
-
- accessor.SetValue(message, true);
+ // Even though it's the default value, we still have a value.
+ message.OneofString = "";
Assert.True(accessor.HasValue(message));
-
- accessor.Clear(message);
+ message.OneofString = "hello";
+ Assert.True(accessor.HasValue(message));
+ message.OneofUint32 = 10;
Assert.False(accessor.HasValue(message));
}
[Test]
+ public void HasValue_Proto2_Repeated()
+ {
+ var message = new Proto2.TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[Proto2.TestAllTypes.RepeatedBoolFieldNumber].Accessor;
+ Assert.Throws<InvalidOperationException>(() => accessor.HasValue(message));
+ }
+
+ [Test]
public void SetValue_SingleFields()
{
// Just a sample (primitives, messages, enums, strings, byte strings)
@@ -226,6 +310,63 @@
}
[Test]
+ public void Clear_Proto3Optional()
+ {
+ TestProto3Optional message = new TestProto3Optional
+ {
+ OptionalInt32 = 0,
+ OptionalNestedMessage = new TestProto3Optional.Types.NestedMessage()
+ };
+ var primitiveField = TestProto3Optional.Descriptor.Fields[TestProto3Optional.OptionalInt32FieldNumber];
+ var messageField = TestProto3Optional.Descriptor.Fields[TestProto3Optional.OptionalNestedMessageFieldNumber];
+
+ Assert.True(message.HasOptionalInt32);
+ Assert.NotNull(message.OptionalNestedMessage);
+
+ primitiveField.Accessor.Clear(message);
+ messageField.Accessor.Clear(message);
+
+ Assert.False(message.HasOptionalInt32);
+ Assert.Null(message.OptionalNestedMessage);
+ }
+
+ [Test]
+ public void Clear_Proto3_Oneof()
+ {
+ var message = new TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[TestProtos.TestAllTypes.OneofUint32FieldNumber].Accessor;
+
+ // The field accessor Clear method only affects a oneof if the current case is the one being cleared.
+ message.OneofString = "hello";
+ Assert.AreEqual(TestProtos.TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase);
+ accessor.Clear(message);
+ Assert.AreEqual(TestProtos.TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase);
+
+ message.OneofUint32 = 100;
+ Assert.AreEqual(TestProtos.TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase);
+ accessor.Clear(message);
+ Assert.AreEqual(TestProtos.TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
+ }
+
+ [Test]
+ public void Clear_Proto2_Oneof()
+ {
+ var message = new Proto2.TestAllTypes();
+ var accessor = ((IMessage) message).Descriptor.Fields[Proto2.TestAllTypes.OneofUint32FieldNumber].Accessor;
+
+ // The field accessor Clear method only affects a oneof if the current case is the one being cleared.
+ message.OneofString = "hello";
+ Assert.AreEqual(Proto2.TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase);
+ accessor.Clear(message);
+ Assert.AreEqual(Proto2.TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase);
+
+ message.OneofUint32 = 100;
+ Assert.AreEqual(Proto2.TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase);
+ accessor.Clear(message);
+ Assert.AreEqual(Proto2.TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
+ }
+
+ [Test]
public void FieldDescriptor_ByName()
{
var descriptor = TestProtos.TestAllTypes.Descriptor;
@@ -264,5 +405,32 @@
message.ClearExtension(RepeatedBoolExtension);
Assert.IsNull(message.GetExtension(RepeatedBoolExtension));
}
+
+ [Test]
+ public void HasPresence()
+ {
+ // Proto3
+ var fields = TestProtos.TestAllTypes.Descriptor.Fields;
+ Assert.IsFalse(fields[TestProtos.TestAllTypes.SingleBoolFieldNumber].HasPresence);
+ Assert.IsTrue(fields[TestProtos.TestAllTypes.OneofBytesFieldNumber].HasPresence);
+ Assert.IsTrue(fields[TestProtos.TestAllTypes.SingleForeignMessageFieldNumber].HasPresence);
+ Assert.IsFalse(fields[TestProtos.TestAllTypes.RepeatedBoolFieldNumber].HasPresence);
+
+ fields = TestMap.Descriptor.Fields;
+ Assert.IsFalse(fields[TestMap.MapBoolBoolFieldNumber].HasPresence);
+
+ fields = TestProto3Optional.Descriptor.Fields;
+ Assert.IsTrue(fields[TestProto3Optional.OptionalBoolFieldNumber].HasPresence);
+
+ // Proto2
+ fields = Proto2.TestAllTypes.Descriptor.Fields;
+ Assert.IsTrue(fields[Proto2.TestAllTypes.OptionalBoolFieldNumber].HasPresence);
+ Assert.IsTrue(fields[Proto2.TestAllTypes.OneofBytesFieldNumber].HasPresence);
+ Assert.IsTrue(fields[Proto2.TestAllTypes.OptionalForeignMessageFieldNumber].HasPresence);
+ Assert.IsFalse(fields[Proto2.TestAllTypes.RepeatedBoolFieldNumber].HasPresence);
+
+ fields = Proto2.TestRequired.Descriptor.Fields;
+ Assert.IsTrue(fields[Proto2.TestRequired.AFieldNumber].HasPresence);
+ }
}
}
diff --git a/csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs b/csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs
index 886937d..15debc1 100644
--- a/csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs
+++ b/csharp/src/Google.Protobuf.Test/UnknownFieldSetTest.cs
@@ -161,10 +161,10 @@
MessageParser discardingParser2 = retainingParser2.WithDiscardUnknownFields(true);
// Test parse from byte[]
- assertFull(retainingParser1.ParseFrom(data));
- assertFull(retainingParser2.ParseFrom(data));
- assertEmpty(discardingParser1.ParseFrom(data));
- assertEmpty(discardingParser2.ParseFrom(data));
+ MessageParsingHelpers.AssertReadingMessage(retainingParser1, data, m => assertFull(m));
+ MessageParsingHelpers.AssertReadingMessage(retainingParser2, data, m => assertFull(m));
+ MessageParsingHelpers.AssertReadingMessage(discardingParser1, data, m => assertEmpty(m));
+ MessageParsingHelpers.AssertReadingMessage(discardingParser2, data, m => assertEmpty(m));
// Test parse from byte[] with offset
assertFull(retainingParser1.ParseFrom(data, 0, data.Length));
diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs
index 4a425f7..47ff2a1 100644
--- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs
+++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs
@@ -71,18 +71,18 @@
Uint64Field = 4
};
- var bytes = message.ToByteArray();
- var parsed = TestWellKnownTypes.Parser.ParseFrom(bytes);
-
- Assert.AreEqual("x", parsed.StringField);
- Assert.AreEqual(ByteString.CopyFrom(1, 2, 3), parsed.BytesField);
- Assert.AreEqual(true, parsed.BoolField);
- Assert.AreEqual(12.5f, parsed.FloatField);
- Assert.AreEqual(12.25d, parsed.DoubleField);
- Assert.AreEqual(1, parsed.Int32Field);
- Assert.AreEqual(2L, parsed.Int64Field);
- Assert.AreEqual(3U, parsed.Uint32Field);
- Assert.AreEqual(4UL, parsed.Uint64Field);
+ MessageParsingHelpers.AssertRoundtrip(TestWellKnownTypes.Parser, message, parsed =>
+ {
+ Assert.AreEqual("x", parsed.StringField);
+ Assert.AreEqual(ByteString.CopyFrom(1, 2, 3), parsed.BytesField);
+ Assert.AreEqual(true, parsed.BoolField);
+ Assert.AreEqual(12.5f, parsed.FloatField);
+ Assert.AreEqual(12.25d, parsed.DoubleField);
+ Assert.AreEqual(1, parsed.Int32Field);
+ Assert.AreEqual(2L, parsed.Int64Field);
+ Assert.AreEqual(3U, parsed.Uint32Field);
+ Assert.AreEqual(4UL, parsed.Uint64Field);
+ });
}
[Test]
@@ -101,18 +101,18 @@
Uint64Field = 0
};
- var bytes = message.ToByteArray();
- var parsed = TestWellKnownTypes.Parser.ParseFrom(bytes);
-
- Assert.AreEqual("", parsed.StringField);
- Assert.AreEqual(ByteString.Empty, parsed.BytesField);
- Assert.AreEqual(false, parsed.BoolField);
- Assert.AreEqual(0f, parsed.FloatField);
- Assert.AreEqual(0d, parsed.DoubleField);
- Assert.AreEqual(0, parsed.Int32Field);
- Assert.AreEqual(0L, parsed.Int64Field);
- Assert.AreEqual(0U, parsed.Uint32Field);
- Assert.AreEqual(0UL, parsed.Uint64Field);
+ MessageParsingHelpers.AssertRoundtrip(TestWellKnownTypes.Parser, message, parsed =>
+ {
+ Assert.AreEqual("", parsed.StringField);
+ Assert.AreEqual(ByteString.Empty, parsed.BytesField);
+ Assert.AreEqual(false, parsed.BoolField);
+ Assert.AreEqual(0f, parsed.FloatField);
+ Assert.AreEqual(0d, parsed.DoubleField);
+ Assert.AreEqual(0, parsed.Int32Field);
+ Assert.AreEqual(0L, parsed.Int64Field);
+ Assert.AreEqual(0U, parsed.Uint32Field);
+ Assert.AreEqual(0UL, parsed.Uint64Field);
+ });
}
[Test]
@@ -140,12 +140,11 @@
Uint32Field = { uint.MaxValue, uint.MinValue, 0U },
Uint64Field = { ulong.MaxValue, ulong.MinValue, 0UL },
};
- var bytes = message.ToByteArray();
- var parsed = RepeatedWellKnownTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
// Just to test a single value for sanity...
Assert.AreEqual("Second", message.StringField[1]);
+
+ MessageParsingHelpers.AssertRoundtrip(RepeatedWellKnownTypes.Parser, message);
}
[Test]
@@ -194,12 +193,10 @@
Uint64Field = { { 18, ulong.MaxValue }, { 19, ulong.MinValue }, { 20, 0UL } },
};
- var bytes = message.ToByteArray();
- var parsed = MapWellKnownTypes.Parser.ParseFrom(bytes);
-
- Assert.AreEqual(message, parsed);
// Just to test a single value for sanity...
Assert.AreEqual("Second", message.StringField[12]);
+
+ MessageParsingHelpers.AssertRoundtrip(MapWellKnownTypes.Parser, message);
}
[Test]
@@ -288,10 +285,10 @@
private void AssertOneofRoundTrip(OneofWellKnownTypes message)
{
// Normal roundtrip, but explicitly checking the case...
- var bytes = message.ToByteArray();
- var parsed = OneofWellKnownTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
- Assert.AreEqual(message.OneofFieldCase, parsed.OneofFieldCase);
+ MessageParsingHelpers.AssertRoundtrip(OneofWellKnownTypes.Parser, message, parsed =>
+ {
+ Assert.AreEqual(message.OneofFieldCase, parsed.OneofFieldCase);
+ });
}
[Test]
@@ -406,8 +403,10 @@
Assert.AreEqual(8, stream.Length); // tag (1 byte) + length (1 byte) + message (6 bytes)
stream.Position = 0;
- var message = TestWellKnownTypes.Parser.ParseFrom(stream);
- Assert.AreEqual(65536, message.Int32Field);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestWellKnownTypes.Parser,
+ stream.ToArray(),
+ message => Assert.AreEqual(65536, message.Int32Field));
}
[Test]
@@ -431,8 +430,10 @@
Assert.Less(stream.Length, 8); // tag (1 byte) + length (1 byte) + message
stream.Position = 0;
- var message = TestWellKnownTypes.Parser.ParseFrom(stream);
- Assert.AreEqual(6, message.Int32Field);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestWellKnownTypes.Parser,
+ stream.ToArray(),
+ message => Assert.AreEqual(6, message.Int32Field));
}
[Test]
@@ -456,8 +457,10 @@
Assert.AreEqual(13, stream.Length); // tag (1 byte) + length (1 byte) + message (11 bytes)
stream.Position = 0;
- var message = TestWellKnownTypes.Parser.ParseFrom(stream);
- Assert.AreEqual(0xfffffffffffffL, message.Int64Field);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestWellKnownTypes.Parser,
+ stream.ToArray(),
+ message => Assert.AreEqual(0xfffffffffffffL, message.Int64Field));
}
[Test]
@@ -481,8 +484,10 @@
Assert.Less(stream.Length, 12); // tag (1 byte) + length (1 byte) + message
stream.Position = 0;
- var message = TestWellKnownTypes.Parser.ParseFrom(stream);
- Assert.AreEqual(6L, message.Int64Field);
+ MessageParsingHelpers.AssertReadingMessage(
+ TestWellKnownTypes.Parser,
+ stream.ToArray(),
+ message => Assert.AreEqual(6L, message.Int64Field));
}
[Test]
diff --git a/csharp/src/Google.Protobuf.Test/testprotos.pb b/csharp/src/Google.Protobuf.Test/testprotos.pb
index 818b227..05312db 100644
--- a/csharp/src/Google.Protobuf.Test/testprotos.pb
+++ b/csharp/src/Google.Protobuf.Test/testprotos.pb
Binary files differ
diff --git a/csharp/src/Google.Protobuf/ByteString.cs b/csharp/src/Google.Protobuf/ByteString.cs
index b158953..027c8d8 100644
--- a/csharp/src/Google.Protobuf/ByteString.cs
+++ b/csharp/src/Google.Protobuf/ByteString.cs
@@ -166,7 +166,7 @@
int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0;
var memoryStream = new MemoryStream(capacity);
stream.CopyTo(memoryStream);
-#if NETSTANDARD1_0 || NETSTANDARD2_0
+#if NETSTANDARD1_1 || NETSTANDARD2_0
byte[] bytes = memoryStream.ToArray();
#else
// Avoid an extra copy if we can.
@@ -192,7 +192,7 @@
// We have to specify the buffer size here, as there's no overload accepting the cancellation token
// alone. But it's documented to use 81920 by default if not specified.
await stream.CopyToAsync(memoryStream, 81920, cancellationToken);
-#if NETSTANDARD1_0 || NETSTANDARD2_0
+#if NETSTANDARD1_1 || NETSTANDARD2_0
byte[] bytes = memoryStream.ToArray();
#else
// Avoid an extra copy if we can.
diff --git a/csharp/src/Google.Protobuf/CodedInputStream.cs b/csharp/src/Google.Protobuf/CodedInputStream.cs
index 44934f3..4050cbe 100644
--- a/csharp/src/Google.Protobuf/CodedInputStream.cs
+++ b/csharp/src/Google.Protobuf/CodedInputStream.cs
@@ -34,6 +34,9 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
namespace Google.Protobuf
{
@@ -51,6 +54,7 @@
/// and <see cref="MapField{TKey, TValue}"/> to serialize such fields.
/// </para>
/// </remarks>
+ [SecuritySafeCritical]
public sealed class CodedInputStream : IDisposable
{
/// <summary>
@@ -65,55 +69,21 @@
private readonly byte[] buffer;
/// <summary>
- /// The index of the buffer at which we need to refill from the stream (if there is one).
- /// </summary>
- private int bufferSize;
-
- private int bufferSizeAfterLimit = 0;
- /// <summary>
- /// The position within the current buffer (i.e. the next byte to read)
- /// </summary>
- private int bufferPos = 0;
-
- /// <summary>
/// The stream to read further input from, or null if the byte array buffer was provided
/// directly on construction, with no further data available.
/// </summary>
private readonly Stream input;
/// <summary>
- /// The last tag we read. 0 indicates we've read to the end of the stream
- /// (or haven't read anything yet).
+ /// The parser state is kept separately so that other parse implementations can reuse the same
+ /// parsing primitives.
/// </summary>
- private uint lastTag = 0;
-
- /// <summary>
- /// The next tag, used to store the value read by PeekTag.
- /// </summary>
- private uint nextTag = 0;
- private bool hasNextTag = false;
+ private ParserInternalState state;
internal const int DefaultRecursionLimit = 100;
internal const int DefaultSizeLimit = Int32.MaxValue;
internal const int BufferSize = 4096;
- /// <summary>
- /// The total number of bytes read before the current buffer. The
- /// total bytes read up to the current position can be computed as
- /// totalBytesRetired + bufferPos.
- /// </summary>
- private int totalBytesRetired = 0;
-
- /// <summary>
- /// The absolute position of the end of the current message.
- /// </summary>
- private int currentLimit = int.MaxValue;
-
- private int recursionDepth = 0;
-
- private readonly int recursionLimit;
- private readonly int sizeLimit;
-
#region Construction
// Note that the checks are performed such that we don't end up checking obviously-valid things
// like non-null references for arrays we've just created.
@@ -170,11 +140,14 @@
{
this.input = input;
this.buffer = buffer;
- this.bufferPos = bufferPos;
- this.bufferSize = bufferSize;
- this.sizeLimit = DefaultSizeLimit;
- this.recursionLimit = DefaultRecursionLimit;
+ this.state.bufferPos = bufferPos;
+ this.state.bufferSize = bufferSize;
+ this.state.sizeLimit = DefaultSizeLimit;
+ this.state.recursionLimit = DefaultRecursionLimit;
+ SegmentedBufferHelper.Initialize(this, out this.state.segmentedBufferHelper);
this.leaveOpen = leaveOpen;
+
+ this.state.currentLimit = int.MaxValue;
}
/// <summary>
@@ -196,8 +169,8 @@
{
throw new ArgumentOutOfRangeException("recursionLimit!", "Recursion limit must be positive");
}
- this.sizeLimit = sizeLimit;
- this.recursionLimit = recursionLimit;
+ this.state.sizeLimit = sizeLimit;
+ this.state.recursionLimit = recursionLimit;
}
#endregion
@@ -230,9 +203,9 @@
{
if (input != null)
{
- return input.Position - ((bufferSize + bufferSizeAfterLimit) - bufferPos);
+ return input.Position - ((state.bufferSize + state.bufferSizeAfterLimit) - state.bufferPos);
}
- return bufferPos;
+ return state.bufferPos;
}
}
@@ -240,7 +213,7 @@
/// Returns the last tag read, or 0 if no tags have been read or we've read beyond
/// the end of the stream.
/// </summary>
- internal uint LastTag { get { return lastTag; } }
+ internal uint LastTag { get { return state.lastTag; } }
/// <summary>
/// Returns the size limit for this stream.
@@ -253,7 +226,7 @@
/// <value>
/// The size limit.
/// </value>
- public int SizeLimit { get { return sizeLimit; } }
+ public int SizeLimit { get { return state.sizeLimit; } }
/// <summary>
/// Returns the recursion limit for this stream. This limit is applied whilst reading messages,
@@ -265,17 +238,31 @@
/// <value>
/// The recursion limit for this stream.
/// </value>
- public int RecursionLimit { get { return recursionLimit; } }
+ public int RecursionLimit { get { return state.recursionLimit; } }
/// <summary>
/// Internal-only property; when set to true, unknown fields will be discarded while parsing.
/// </summary>
- internal bool DiscardUnknownFields { get; set; }
+ internal bool DiscardUnknownFields
+ {
+ get { return state.DiscardUnknownFields; }
+ set { state.DiscardUnknownFields = value; }
+ }
/// <summary>
/// Internal-only property; provides extension identifiers to compatible messages while parsing.
/// </summary>
- internal ExtensionRegistry ExtensionRegistry { get; set; }
+ internal ExtensionRegistry ExtensionRegistry
+ {
+ get { return state.ExtensionRegistry; }
+ set { state.ExtensionRegistry = value; }
+ }
+
+ internal byte[] InternalBuffer => buffer;
+
+ internal Stream InternalInputStream => input;
+
+ internal ref ParserInternalState InternalState => ref state;
/// <summary>
/// Disposes of this instance, potentially closing any underlying stream.
@@ -302,10 +289,7 @@
/// tag read was not the one specified</exception>
internal void CheckReadEndOfStreamTag()
{
- if (lastTag != 0)
- {
- throw InvalidProtocolBufferException.MoreDataAvailable();
- }
+ ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref state);
}
#endregion
@@ -318,16 +302,8 @@
/// </summary>
public uint PeekTag()
{
- if (hasNextTag)
- {
- return nextTag;
- }
-
- uint savedLast = lastTag;
- nextTag = ReadTag();
- hasNextTag = true;
- lastTag = savedLast; // Undo the side effect of ReadTag
- return nextTag;
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.PeekTag(ref span, ref state);
}
/// <summary>
@@ -341,58 +317,8 @@
/// <returns>The next field tag, or 0 for end of stream. (0 is never a valid tag.)</returns>
public uint ReadTag()
{
- if (hasNextTag)
- {
- lastTag = nextTag;
- hasNextTag = false;
- return lastTag;
- }
-
- // Optimize for the incredibly common case of having at least two bytes left in the buffer,
- // and those two bytes being enough to get the tag. This will be true for fields up to 4095.
- if (bufferPos + 2 <= bufferSize)
- {
- int tmp = buffer[bufferPos++];
- if (tmp < 128)
- {
- lastTag = (uint)tmp;
- }
- else
- {
- int result = tmp & 0x7f;
- if ((tmp = buffer[bufferPos++]) < 128)
- {
- result |= tmp << 7;
- lastTag = (uint) result;
- }
- else
- {
- // Nope, rewind and go the potentially slow route.
- bufferPos -= 2;
- lastTag = ReadRawVarint32();
- }
- }
- }
- else
- {
- if (IsAtEnd)
- {
- lastTag = 0;
- return 0;
- }
-
- lastTag = ReadRawVarint32();
- }
- if (WireFormat.GetTagFieldNumber(lastTag) == 0)
- {
- // If we actually read a tag with a field of 0, that's not a valid tag.
- throw InvalidProtocolBufferException.InvalidTag();
- }
- if (ReachedLimit)
- {
- return 0;
- }
- return lastTag;
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseTag(ref span, ref state);
}
/// <summary>
@@ -410,32 +336,8 @@
/// <exception cref="InvalidOperationException">The last read operation read to the end of the logical stream</exception>
public void SkipLastField()
{
- if (lastTag == 0)
- {
- throw new InvalidOperationException("SkipLastField cannot be called at the end of a stream");
- }
- switch (WireFormat.GetTagWireType(lastTag))
- {
- case WireFormat.WireType.StartGroup:
- SkipGroup(lastTag);
- break;
- case WireFormat.WireType.EndGroup:
- throw new InvalidProtocolBufferException(
- "SkipLastField called on an end-group tag, indicating that the corresponding start-group was missing");
- case WireFormat.WireType.Fixed32:
- ReadFixed32();
- break;
- case WireFormat.WireType.Fixed64:
- ReadFixed64();
- break;
- case WireFormat.WireType.LengthDelimited:
- var length = ReadLength();
- SkipRawBytes(length);
- break;
- case WireFormat.WireType.Varint:
- ReadRawVarint32();
- break;
- }
+ var span = new ReadOnlySpan<byte>(buffer);
+ ParsingPrimitivesMessages.SkipLastField(ref span, ref state);
}
/// <summary>
@@ -443,37 +345,8 @@
/// </summary>
internal void SkipGroup(uint startGroupTag)
{
- // Note: Currently we expect this to be the way that groups are read. We could put the recursion
- // depth changes into the ReadTag method instead, potentially...
- recursionDepth++;
- if (recursionDepth >= recursionLimit)
- {
- throw InvalidProtocolBufferException.RecursionLimitExceeded();
- }
- uint tag;
- while (true)
- {
- tag = ReadTag();
- if (tag == 0)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- // Can't call SkipLastField for this case- that would throw.
- if (WireFormat.GetTagWireType(tag) == WireFormat.WireType.EndGroup)
- {
- break;
- }
- // This recursion will allow us to handle nested groups.
- SkipLastField();
- }
- int startField = WireFormat.GetTagFieldNumber(startGroupTag);
- int endField = WireFormat.GetTagFieldNumber(tag);
- if (startField != endField)
- {
- throw new InvalidProtocolBufferException(
- $"Mismatched end-group tag. Started with field {startField}; ended with field {endField}");
- }
- recursionDepth--;
+ var span = new ReadOnlySpan<byte>(buffer);
+ ParsingPrimitivesMessages.SkipGroup(ref span, ref state, startGroupTag);
}
/// <summary>
@@ -481,33 +354,8 @@
/// </summary>
public double ReadDouble()
{
- if (bufferPos + 8 <= bufferSize)
- {
- if (BitConverter.IsLittleEndian)
- {
- var result = BitConverter.ToDouble(buffer, bufferPos);
- bufferPos += 8;
- return result;
- }
- else
- {
- var bytes = new byte[8];
- bytes[0] = buffer[bufferPos + 7];
- bytes[1] = buffer[bufferPos + 6];
- bytes[2] = buffer[bufferPos + 5];
- bytes[3] = buffer[bufferPos + 4];
- bytes[4] = buffer[bufferPos + 3];
- bytes[5] = buffer[bufferPos + 2];
- bytes[6] = buffer[bufferPos + 1];
- bytes[7] = buffer[bufferPos];
- bufferPos += 8;
- return BitConverter.ToDouble(bytes, 0);
- }
- }
- else
- {
- return BitConverter.Int64BitsToDouble((long)ReadRawLittleEndian64());
- }
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseDouble(ref span, ref state);
}
/// <summary>
@@ -515,21 +363,8 @@
/// </summary>
public float ReadFloat()
{
- if (BitConverter.IsLittleEndian && 4 <= bufferSize - bufferPos)
- {
- float ret = BitConverter.ToSingle(buffer, bufferPos);
- bufferPos += 4;
- return ret;
- }
- else
- {
- byte[] rawBytes = ReadRawBytes(4);
- if (!BitConverter.IsLittleEndian)
- {
- ByteArray.Reverse(rawBytes);
- }
- return BitConverter.ToSingle(rawBytes, 0);
- }
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseFloat(ref span, ref state);
}
/// <summary>
@@ -577,7 +412,7 @@
/// </summary>
public bool ReadBool()
{
- return ReadRawVarint32() != 0;
+ return ReadRawVarint64() != 0;
}
/// <summary>
@@ -585,22 +420,8 @@
/// </summary>
public string ReadString()
{
- int length = ReadLength();
- // No need to read any data for an empty string.
- if (length == 0)
- {
- return "";
- }
- if (length <= bufferSize - bufferPos && length > 0)
- {
- // Fast path: We already have the bytes in a contiguous buffer, so
- // just copy directly from it.
- String result = CodedOutputStream.Utf8Encoding.GetString(buffer, bufferPos, length);
- bufferPos += length;
- return result;
- }
- // Slow path: Build a byte array first then copy it.
- return CodedOutputStream.Utf8Encoding.GetString(ReadRawBytes(length), 0, length);
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ReadString(ref span, ref state);
}
/// <summary>
@@ -608,22 +429,22 @@
/// </summary>
public void ReadMessage(IMessage builder)
{
- int length = ReadLength();
- if (recursionDepth >= recursionLimit)
+ // TODO(jtattermusch): if the message doesn't implement IBufferMessage (and thus does not provide the InternalMergeFrom method),
+ // what we're doing here works fine, but could be more efficient.
+ // What happends is that we first initialize a ParseContext from the current coded input stream only to parse the length of the message, at which point
+ // we will need to switch back again to CodedInputStream-based parsing (which involves copying and storing the state) to be able to
+ // invoke the legacy MergeFrom(CodedInputStream) method.
+ // For now, this inefficiency is fine, considering this is only a backward-compatibility scenario (and regenerating the code fixes it).
+ var span = new ReadOnlySpan<byte>(buffer);
+ ParseContext.Initialize(ref span, ref state, out ParseContext ctx);
+ try
{
- throw InvalidProtocolBufferException.RecursionLimitExceeded();
+ ParsingPrimitivesMessages.ReadMessage(ref ctx, builder);
}
- int oldLimit = PushLimit(length);
- ++recursionDepth;
- builder.MergeFrom(this);
- CheckReadEndOfStreamTag();
- // Check that we've read exactly as much data as expected.
- if (!ReachedLimit)
+ finally
{
- throw InvalidProtocolBufferException.TruncatedMessage();
+ ctx.CopyStateTo(this);
}
- --recursionDepth;
- PopLimit(oldLimit);
}
/// <summary>
@@ -631,13 +452,15 @@
/// </summary>
public void ReadGroup(IMessage builder)
{
- if (recursionDepth >= recursionLimit)
+ ParseContext.Initialize(this, out ParseContext ctx);
+ try
{
- throw InvalidProtocolBufferException.RecursionLimitExceeded();
+ ParsingPrimitivesMessages.ReadGroup(ref ctx, builder);
}
- ++recursionDepth;
- builder.MergeFrom(this);
- --recursionDepth;
+ finally
+ {
+ ctx.CopyStateTo(this);
+ }
}
/// <summary>
@@ -645,20 +468,8 @@
/// </summary>
public ByteString ReadBytes()
{
- int length = ReadLength();
- if (length <= bufferSize - bufferPos && length > 0)
- {
- // Fast path: We already have the bytes in a contiguous buffer, so
- // just copy directly from it.
- ByteString result = ByteString.CopyFrom(buffer, bufferPos, length);
- bufferPos += length;
- return result;
- }
- else
- {
- // Slow path: Build a byte array and attach it to a new ByteString.
- return ByteString.AttachBytes(ReadRawBytes(length));
- }
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ReadBytes(ref span, ref state);
}
/// <summary>
@@ -699,7 +510,7 @@
/// </summary>
public int ReadSInt32()
{
- return DecodeZigZag32(ReadRawVarint32());
+ return ParsingPrimitives.DecodeZigZag32(ReadRawVarint32());
}
/// <summary>
@@ -707,7 +518,7 @@
/// </summary>
public long ReadSInt64()
{
- return DecodeZigZag64(ReadRawVarint64());
+ return ParsingPrimitives.DecodeZigZag64(ReadRawVarint64());
}
/// <summary>
@@ -719,7 +530,8 @@
/// </remarks>
public int ReadLength()
{
- return (int) ReadRawVarint32();
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseLength(ref span, ref state);
}
/// <summary>
@@ -729,265 +541,8 @@
/// </summary>
public bool MaybeConsumeTag(uint tag)
{
- if (PeekTag() == tag)
- {
- hasNextTag = false;
- return true;
- }
- return false;
- }
-
- internal static float? ReadFloatWrapperLittleEndian(CodedInputStream input)
- {
- // length:1 + tag:1 + value:4 = 6 bytes
- if (input.bufferPos + 6 <= input.bufferSize)
- {
- // The entire wrapper message is already contained in `buffer`.
- int length = input.buffer[input.bufferPos];
- if (length == 0)
- {
- input.bufferPos++;
- return 0F;
- }
- // tag:1 + value:4 = length of 5 bytes
- // field=1, type=32-bit = tag of 13
- if (length != 5 || input.buffer[input.bufferPos + 1] != 13)
- {
- return ReadFloatWrapperSlow(input);
- }
- var result = BitConverter.ToSingle(input.buffer, input.bufferPos + 2);
- input.bufferPos += 6;
- return result;
- }
- else
- {
- return ReadFloatWrapperSlow(input);
- }
- }
-
- internal static float? ReadFloatWrapperSlow(CodedInputStream input)
- {
- int length = input.ReadLength();
- if (length == 0)
- {
- return 0F;
- }
- int finalBufferPos = input.totalBytesRetired + input.bufferPos + length;
- float result = 0F;
- do
- {
- // field=1, type=32-bit = tag of 13
- if (input.ReadTag() == 13)
- {
- result = input.ReadFloat();
- }
- else
- {
- input.SkipLastField();
- }
- }
- while (input.totalBytesRetired + input.bufferPos < finalBufferPos);
- return result;
- }
-
- internal static double? ReadDoubleWrapperLittleEndian(CodedInputStream input)
- {
- // length:1 + tag:1 + value:8 = 10 bytes
- if (input.bufferPos + 10 <= input.bufferSize)
- {
- // The entire wrapper message is already contained in `buffer`.
- int length = input.buffer[input.bufferPos];
- if (length == 0)
- {
- input.bufferPos++;
- return 0D;
- }
- // tag:1 + value:8 = length of 9 bytes
- // field=1, type=64-bit = tag of 9
- if (length != 9 || input.buffer[input.bufferPos + 1] != 9)
- {
- return ReadDoubleWrapperSlow(input);
- }
- var result = BitConverter.ToDouble(input.buffer, input.bufferPos + 2);
- input.bufferPos += 10;
- return result;
- }
- else
- {
- return ReadDoubleWrapperSlow(input);
- }
- }
-
- internal static double? ReadDoubleWrapperSlow(CodedInputStream input)
- {
- int length = input.ReadLength();
- if (length == 0)
- {
- return 0D;
- }
- int finalBufferPos = input.totalBytesRetired + input.bufferPos + length;
- double result = 0D;
- do
- {
- // field=1, type=64-bit = tag of 9
- if (input.ReadTag() == 9)
- {
- result = input.ReadDouble();
- }
- else
- {
- input.SkipLastField();
- }
- }
- while (input.totalBytesRetired + input.bufferPos < finalBufferPos);
- return result;
- }
-
- internal static bool? ReadBoolWrapper(CodedInputStream input)
- {
- return ReadUInt32Wrapper(input) != 0;
- }
-
- internal static uint? ReadUInt32Wrapper(CodedInputStream input)
- {
- // length:1 + tag:1 + value:5(varint32-max) = 7 bytes
- if (input.bufferPos + 7 <= input.bufferSize)
- {
- // The entire wrapper message is already contained in `buffer`.
- int pos0 = input.bufferPos;
- int length = input.buffer[input.bufferPos++];
- if (length == 0)
- {
- return 0;
- }
- // Length will always fit in a single byte.
- if (length >= 128)
- {
- input.bufferPos = pos0;
- return ReadUInt32WrapperSlow(input);
- }
- int finalBufferPos = input.bufferPos + length;
- // field=1, type=varint = tag of 8
- if (input.buffer[input.bufferPos++] != 8)
- {
- input.bufferPos = pos0;
- return ReadUInt32WrapperSlow(input);
- }
- var result = input.ReadUInt32();
- // Verify this message only contained a single field.
- if (input.bufferPos != finalBufferPos)
- {
- input.bufferPos = pos0;
- return ReadUInt32WrapperSlow(input);
- }
- return result;
- }
- else
- {
- return ReadUInt32WrapperSlow(input);
- }
- }
-
- private static uint? ReadUInt32WrapperSlow(CodedInputStream input)
- {
- int length = input.ReadLength();
- if (length == 0)
- {
- return 0;
- }
- int finalBufferPos = input.totalBytesRetired + input.bufferPos + length;
- uint result = 0;
- do
- {
- // field=1, type=varint = tag of 8
- if (input.ReadTag() == 8)
- {
- result = input.ReadUInt32();
- }
- else
- {
- input.SkipLastField();
- }
- }
- while (input.totalBytesRetired + input.bufferPos < finalBufferPos);
- return result;
- }
-
- internal static int? ReadInt32Wrapper(CodedInputStream input)
- {
- return (int?)ReadUInt32Wrapper(input);
- }
-
- internal static ulong? ReadUInt64Wrapper(CodedInputStream input)
- {
- // field=1, type=varint = tag of 8
- const int expectedTag = 8;
- // length:1 + tag:1 + value:10(varint64-max) = 12 bytes
- if (input.bufferPos + 12 <= input.bufferSize)
- {
- // The entire wrapper message is already contained in `buffer`.
- int pos0 = input.bufferPos;
- int length = input.buffer[input.bufferPos++];
- if (length == 0)
- {
- return 0L;
- }
- // Length will always fit in a single byte.
- if (length >= 128)
- {
- input.bufferPos = pos0;
- return ReadUInt64WrapperSlow(input);
- }
- int finalBufferPos = input.bufferPos + length;
- if (input.buffer[input.bufferPos++] != expectedTag)
- {
- input.bufferPos = pos0;
- return ReadUInt64WrapperSlow(input);
- }
- var result = input.ReadUInt64();
- // Verify this message only contained a single field.
- if (input.bufferPos != finalBufferPos)
- {
- input.bufferPos = pos0;
- return ReadUInt64WrapperSlow(input);
- }
- return result;
- }
- else
- {
- return ReadUInt64WrapperSlow(input);
- }
- }
-
- internal static ulong? ReadUInt64WrapperSlow(CodedInputStream input)
- {
- // field=1, type=varint = tag of 8
- const int expectedTag = 8;
- int length = input.ReadLength();
- if (length == 0)
- {
- return 0L;
- }
- int finalBufferPos = input.totalBytesRetired + input.bufferPos + length;
- ulong result = 0L;
- do
- {
- if (input.ReadTag() == expectedTag)
- {
- result = input.ReadUInt64();
- }
- else
- {
- input.SkipLastField();
- }
- }
- while (input.totalBytesRetired + input.bufferPos < finalBufferPos);
- return result;
- }
-
- internal static long? ReadInt64Wrapper(CodedInputStream input)
- {
- return (long?)ReadUInt64Wrapper(input);
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.MaybeConsumeTag(ref span, ref state, tag);
}
#endregion
@@ -995,58 +550,6 @@
#region Underlying reading primitives
/// <summary>
- /// Same code as ReadRawVarint32, but read each byte individually, checking for
- /// buffer overflow.
- /// </summary>
- private uint SlowReadRawVarint32()
- {
- int tmp = ReadRawByte();
- if (tmp < 128)
- {
- return (uint) tmp;
- }
- int result = tmp & 0x7f;
- if ((tmp = ReadRawByte()) < 128)
- {
- result |= tmp << 7;
- }
- else
- {
- result |= (tmp & 0x7f) << 7;
- if ((tmp = ReadRawByte()) < 128)
- {
- result |= tmp << 14;
- }
- else
- {
- result |= (tmp & 0x7f) << 14;
- if ((tmp = ReadRawByte()) < 128)
- {
- result |= tmp << 21;
- }
- else
- {
- result |= (tmp & 0x7f) << 21;
- result |= (tmp = ReadRawByte()) << 28;
- if (tmp >= 128)
- {
- // Discard upper 32 bits.
- for (int i = 0; i < 5; i++)
- {
- if (ReadRawByte() < 128)
- {
- return (uint) result;
- }
- }
- throw InvalidProtocolBufferException.MalformedVarint();
- }
- }
- }
- }
- return (uint) result;
- }
-
- /// <summary>
/// Reads a raw Varint from the stream. If larger than 32 bits, discard the upper bits.
/// This method is optimised for the case where we've got lots of data in the buffer.
/// That means we can check the size just once, then just read directly from the buffer
@@ -1054,58 +557,8 @@
/// </summary>
internal uint ReadRawVarint32()
{
- if (bufferPos + 5 > bufferSize)
- {
- return SlowReadRawVarint32();
- }
-
- int tmp = buffer[bufferPos++];
- if (tmp < 128)
- {
- return (uint) tmp;
- }
- int result = tmp & 0x7f;
- if ((tmp = buffer[bufferPos++]) < 128)
- {
- result |= tmp << 7;
- }
- else
- {
- result |= (tmp & 0x7f) << 7;
- if ((tmp = buffer[bufferPos++]) < 128)
- {
- result |= tmp << 14;
- }
- else
- {
- result |= (tmp & 0x7f) << 14;
- if ((tmp = buffer[bufferPos++]) < 128)
- {
- result |= tmp << 21;
- }
- else
- {
- result |= (tmp & 0x7f) << 21;
- result |= (tmp = buffer[bufferPos++]) << 28;
- if (tmp >= 128)
- {
- // Discard upper 32 bits.
- // Note that this has to use ReadRawByte() as we only ensure we've
- // got at least 5 bytes at the start of the method. This lets us
- // use the fast path in more cases, and we rarely hit this section of code.
- for (int i = 0; i < 5; i++)
- {
- if (ReadRawByte() < 128)
- {
- return (uint) result;
- }
- }
- throw InvalidProtocolBufferException.MalformedVarint();
- }
- }
- }
- }
- return (uint) result;
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseRawVarint32(ref span, ref state);
}
/// <summary>
@@ -1119,35 +572,7 @@
/// <returns></returns>
internal static uint ReadRawVarint32(Stream input)
{
- int result = 0;
- int offset = 0;
- for (; offset < 32; offset += 7)
- {
- int b = input.ReadByte();
- if (b == -1)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- result |= (b & 0x7f) << offset;
- if ((b & 0x80) == 0)
- {
- return (uint) result;
- }
- }
- // Keep reading up to 64 bits.
- for (; offset < 64; offset += 7)
- {
- int b = input.ReadByte();
- if (b == -1)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- if ((b & 0x80) == 0)
- {
- return (uint) result;
- }
- }
- throw InvalidProtocolBufferException.MalformedVarint();
+ return ParsingPrimitives.ReadRawVarint32(input);
}
/// <summary>
@@ -1155,44 +580,8 @@
/// </summary>
internal ulong ReadRawVarint64()
{
- if (bufferPos + 10 <= bufferSize)
- {
- ulong result = buffer[bufferPos++];
- if (result < 128)
- {
- return result;
- }
- result &= 0x7f;
- int shift = 7;
- do
- {
- byte b = buffer[bufferPos++];
- result |= (ulong)(b & 0x7F) << shift;
- if (b < 0x80)
- {
- return result;
- }
- shift += 7;
- }
- while (shift < 64);
- }
- else
- {
- int shift = 0;
- ulong result = 0;
- do
- {
- byte b = ReadRawByte();
- result |= (ulong)(b & 0x7F) << shift;
- if (b < 0x80)
- {
- return result;
- }
- shift += 7;
- }
- while (shift < 64);
- }
- throw InvalidProtocolBufferException.MalformedVarint();
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseRawVarint64(ref span, ref state);
}
/// <summary>
@@ -1200,32 +589,8 @@
/// </summary>
internal uint ReadRawLittleEndian32()
{
- if (bufferPos + 4 <= bufferSize)
- {
- if (BitConverter.IsLittleEndian)
- {
- var result = BitConverter.ToUInt32(buffer, bufferPos);
- bufferPos += 4;
- return result;
- }
- else
- {
- uint b1 = buffer[bufferPos];
- uint b2 = buffer[bufferPos + 1];
- uint b3 = buffer[bufferPos + 2];
- uint b4 = buffer[bufferPos + 3];
- bufferPos += 4;
- return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
- }
- }
- else
- {
- uint b1 = ReadRawByte();
- uint b2 = ReadRawByte();
- uint b3 = ReadRawByte();
- uint b4 = ReadRawByte();
- return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
- }
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseRawLittleEndian32(ref span, ref state);
}
/// <summary>
@@ -1233,70 +598,8 @@
/// </summary>
internal ulong ReadRawLittleEndian64()
{
- if (bufferPos + 8 <= bufferSize)
- {
- if (BitConverter.IsLittleEndian)
- {
- var result = BitConverter.ToUInt64(buffer, bufferPos);
- bufferPos += 8;
- return result;
- }
- else
- {
- ulong b1 = buffer[bufferPos];
- ulong b2 = buffer[bufferPos + 1];
- ulong b3 = buffer[bufferPos + 2];
- ulong b4 = buffer[bufferPos + 3];
- ulong b5 = buffer[bufferPos + 4];
- ulong b6 = buffer[bufferPos + 5];
- ulong b7 = buffer[bufferPos + 6];
- ulong b8 = buffer[bufferPos + 7];
- bufferPos += 8;
- return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)
- | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
- }
- }
- else
- {
- ulong b1 = ReadRawByte();
- ulong b2 = ReadRawByte();
- ulong b3 = ReadRawByte();
- ulong b4 = ReadRawByte();
- ulong b5 = ReadRawByte();
- ulong b6 = ReadRawByte();
- ulong b7 = ReadRawByte();
- ulong b8 = ReadRawByte();
- return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)
- | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
- }
- }
-
- /// <summary>
- /// Decode a 32-bit value with ZigZag encoding.
- /// </summary>
- /// <remarks>
- /// 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.)
- /// </remarks>
- internal static int DecodeZigZag32(uint n)
- {
- return (int)(n >> 1) ^ -(int)(n & 1);
- }
-
- /// <summary>
- /// Decode a 32-bit value with ZigZag encoding.
- /// </summary>
- /// <remarks>
- /// 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.)
- /// </remarks>
- internal static long DecodeZigZag64(ulong n)
- {
- return (long)(n >> 1) ^ -(long)(n & 1);
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ParseRawLittleEndian64(ref span, ref state);
}
#endregion
@@ -1310,37 +613,7 @@
/// <returns>The old limit.</returns>
internal int PushLimit(int byteLimit)
{
- if (byteLimit < 0)
- {
- throw InvalidProtocolBufferException.NegativeSize();
- }
- byteLimit += totalBytesRetired + bufferPos;
- int oldLimit = currentLimit;
- if (byteLimit > oldLimit)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- currentLimit = byteLimit;
-
- RecomputeBufferSizeAfterLimit();
-
- return oldLimit;
- }
-
- private void RecomputeBufferSizeAfterLimit()
- {
- bufferSize += bufferSizeAfterLimit;
- int bufferEnd = totalBytesRetired + bufferSize;
- if (bufferEnd > currentLimit)
- {
- // Limit is in current buffer.
- bufferSizeAfterLimit = bufferEnd - currentLimit;
- bufferSize -= bufferSizeAfterLimit;
- }
- else
- {
- bufferSizeAfterLimit = 0;
- }
+ return SegmentedBufferHelper.PushLimit(ref state, byteLimit);
}
/// <summary>
@@ -1348,8 +621,7 @@
/// </summary>
internal void PopLimit(int oldLimit)
{
- currentLimit = oldLimit;
- RecomputeBufferSizeAfterLimit();
+ SegmentedBufferHelper.PopLimit(ref state, oldLimit);
}
/// <summary>
@@ -1360,12 +632,7 @@
{
get
{
- if (currentLimit == int.MaxValue)
- {
- return false;
- }
- int currentAbsolutePosition = totalBytesRetired + bufferPos;
- return currentAbsolutePosition >= currentLimit;
+ return SegmentedBufferHelper.IsReachedLimit(ref state);
}
}
@@ -1376,7 +643,11 @@
/// </summary>
public bool IsAtEnd
{
- get { return bufferPos == bufferSize && !RefillBuffer(false); }
+ get
+ {
+ var span = new ReadOnlySpan<byte>(buffer);
+ return SegmentedBufferHelper.IsAtEnd(ref span, ref state);
+ }
}
/// <summary>
@@ -1390,69 +661,8 @@
/// <returns></returns>
private bool RefillBuffer(bool mustSucceed)
{
- if (bufferPos < bufferSize)
- {
- throw new InvalidOperationException("RefillBuffer() called when buffer wasn't empty.");
- }
-
- if (totalBytesRetired + bufferSize == currentLimit)
- {
- // Oops, we hit a limit.
- if (mustSucceed)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- else
- {
- return false;
- }
- }
-
- totalBytesRetired += bufferSize;
-
- bufferPos = 0;
- bufferSize = (input == null) ? 0 : input.Read(buffer, 0, buffer.Length);
- if (bufferSize < 0)
- {
- throw new InvalidOperationException("Stream.Read returned a negative count");
- }
- if (bufferSize == 0)
- {
- if (mustSucceed)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- else
- {
- return false;
- }
- }
- else
- {
- RecomputeBufferSizeAfterLimit();
- int totalBytesRead =
- totalBytesRetired + bufferSize + bufferSizeAfterLimit;
- if (totalBytesRead < 0 || totalBytesRead > sizeLimit)
- {
- throw InvalidProtocolBufferException.SizeLimitExceeded();
- }
- return true;
- }
- }
-
- /// <summary>
- /// Read one byte from the input.
- /// </summary>
- /// <exception cref="InvalidProtocolBufferException">
- /// the end of the stream or the current limit was reached
- /// </exception>
- internal byte ReadRawByte()
- {
- if (bufferPos == bufferSize)
- {
- RefillBuffer(true);
- }
- return buffer[bufferPos++];
+ var span = new ReadOnlySpan<byte>(buffer);
+ return state.segmentedBufferHelper.RefillBuffer(ref span, ref state, mustSucceed);
}
/// <summary>
@@ -1463,195 +673,27 @@
/// </exception>
internal byte[] ReadRawBytes(int size)
{
- if (size < 0)
- {
- throw InvalidProtocolBufferException.NegativeSize();
- }
-
- if (totalBytesRetired + bufferPos + size > currentLimit)
- {
- // Read to the end of the stream (up to the current limit) anyway.
- SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
- // Then fail.
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
-
- if (size <= bufferSize - bufferPos)
- {
- // We have all the bytes we need already.
- byte[] bytes = new byte[size];
- ByteArray.Copy(buffer, bufferPos, bytes, 0, size);
- bufferPos += size;
- return bytes;
- }
- else if (size < buffer.Length)
- {
- // Reading more bytes than are in the buffer, but not an excessive number
- // of bytes. We can safely allocate the resulting array ahead of time.
-
- // First copy what we have.
- byte[] bytes = new byte[size];
- int pos = bufferSize - bufferPos;
- ByteArray.Copy(buffer, bufferPos, bytes, 0, pos);
- bufferPos = bufferSize;
-
- // We want to use RefillBuffer() and then copy from the buffer into our
- // byte array rather than reading directly into our byte array because
- // the input may be unbuffered.
- RefillBuffer(true);
-
- while (size - pos > bufferSize)
- {
- Buffer.BlockCopy(buffer, 0, bytes, pos, bufferSize);
- pos += bufferSize;
- bufferPos = bufferSize;
- RefillBuffer(true);
- }
-
- ByteArray.Copy(buffer, 0, bytes, pos, size - pos);
- bufferPos = size - pos;
-
- return bytes;
- }
- else
- {
- // 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.
-
- // Remember the buffer markers since we'll have to copy the bytes out of
- // it later.
- int originalBufferPos = bufferPos;
- int originalBufferSize = bufferSize;
-
- // Mark the current buffer consumed.
- totalBytesRetired += bufferSize;
- bufferPos = 0;
- bufferSize = 0;
-
- // Read all the rest of the bytes we need.
- int sizeLeft = size - (originalBufferSize - originalBufferPos);
- List<byte[]> chunks = new List<byte[]>();
-
- while (sizeLeft > 0)
- {
- byte[] chunk = new byte[Math.Min(sizeLeft, buffer.Length)];
- int pos = 0;
- while (pos < chunk.Length)
- {
- int n = (input == null) ? -1 : input.Read(chunk, pos, chunk.Length - pos);
- if (n <= 0)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- totalBytesRetired += n;
- pos += n;
- }
- sizeLeft -= chunk.Length;
- chunks.Add(chunk);
- }
-
- // OK, got everything. Now concatenate it all into one buffer.
- byte[] bytes = new byte[size];
-
- // Start by copying the leftover bytes from this.buffer.
- int newPos = originalBufferSize - originalBufferPos;
- ByteArray.Copy(buffer, originalBufferPos, bytes, 0, newPos);
-
- // And now all the chunks.
- foreach (byte[] chunk in chunks)
- {
- Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length);
- newPos += chunk.Length;
- }
-
- // Done.
- return bytes;
- }
+ var span = new ReadOnlySpan<byte>(buffer);
+ return ParsingPrimitives.ReadRawBytes(ref span, ref state, size);
}
/// <summary>
- /// Reads and discards <paramref name="size"/> bytes.
+ /// Reads a top-level message or a nested message after the limits for this message have been pushed.
+ /// (parser will proceed until the end of the current limit)
+ /// NOTE: this method needs to be public because it's invoked by the generated code - e.g. msg.MergeFrom(CodedInputStream input) method
/// </summary>
- /// <exception cref="InvalidProtocolBufferException">the end of the stream
- /// or the current limit was reached</exception>
- private void SkipRawBytes(int size)
+ public void ReadRawMessage(IMessage message)
{
- if (size < 0)
+ ParseContext.Initialize(this, out ParseContext ctx);
+ try
{
- throw InvalidProtocolBufferException.NegativeSize();
+ ParsingPrimitivesMessages.ReadRawMessage(ref ctx, message);
}
-
- if (totalBytesRetired + bufferPos + size > currentLimit)
+ finally
{
- // Read to the end of the stream anyway.
- SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
- // Then fail.
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
-
- if (size <= bufferSize - bufferPos)
- {
- // We have all the bytes we need already.
- bufferPos += size;
- }
- else
- {
- // Skipping more bytes than are in the buffer. First skip what we have.
- int pos = bufferSize - bufferPos;
-
- // ROK 5/7/2013 Issue #54: should retire all bytes in buffer (bufferSize)
- // totalBytesRetired += pos;
- totalBytesRetired += bufferSize;
-
- bufferPos = 0;
- bufferSize = 0;
-
- // Then skip directly from the InputStream for the rest.
- if (pos < size)
- {
- if (input == null)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- SkipImpl(size - pos);
- totalBytesRetired += size - pos;
- }
- }
- }
-
- /// <summary>
- /// Abstraction of skipping to cope with streams which can't really skip.
- /// </summary>
- private void SkipImpl(int amountToSkip)
- {
- if (input.CanSeek)
- {
- long previousPosition = input.Position;
- input.Position += amountToSkip;
- if (input.Position != previousPosition + amountToSkip)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- }
- else
- {
- byte[] skipBuffer = new byte[Math.Min(1024, amountToSkip)];
- while (amountToSkip > 0)
- {
- int bytesRead = input.Read(skipBuffer, 0, Math.Min(skipBuffer.Length, amountToSkip));
- if (bytesRead <= 0)
- {
- throw InvalidProtocolBufferException.TruncatedMessage();
- }
- amountToSkip -= bytesRead;
- }
+ ctx.CopyStateTo(this);
}
}
#endregion
}
-}
\ No newline at end of file
+}
diff --git a/csharp/src/Google.Protobuf/CodedOutputStream.cs b/csharp/src/Google.Protobuf/CodedOutputStream.cs
index f9ad290..1d76d27 100644
--- a/csharp/src/Google.Protobuf/CodedOutputStream.cs
+++ b/csharp/src/Google.Protobuf/CodedOutputStream.cs
@@ -89,7 +89,7 @@
private CodedOutputStream(byte[] buffer, int offset, int length)
{
this.output = null;
- this.buffer = buffer;
+ this.buffer = ProtoPreconditions.CheckNotNull(buffer, nameof(buffer));
this.position = offset;
this.limit = offset + length;
leaveOpen = true; // Simple way of avoiding trying to dispose of a null reference
diff --git a/csharp/src/Google.Protobuf/Collections/MapField.cs b/csharp/src/Google.Protobuf/Collections/MapField.cs
index 1924439..48cd7ab 100644
--- a/csharp/src/Google.Protobuf/Collections/MapField.cs
+++ b/csharp/src/Google.Protobuf/Collections/MapField.cs
@@ -33,10 +33,12 @@
using Google.Protobuf.Compatibility;
using Google.Protobuf.Reflection;
using System;
+using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Security;
namespace Google.Protobuf.Collections
{
@@ -422,13 +424,37 @@
/// <param name="codec">Codec describing how the key/value pairs are encoded</param>
public void AddEntriesFrom(CodedInputStream input, Codec codec)
{
+ ParseContext.Initialize(input, out ParseContext ctx);
+ try
+ {
+ AddEntriesFrom(ref ctx, codec);
+ }
+ finally
+ {
+ ctx.CopyStateTo(input);
+ }
+ }
+
+ /// <summary>
+ /// Adds entries to the map from the given parse context.
+ /// </summary>
+ /// <remarks>
+ /// It is assumed that the input is initially positioned after the tag specified by the codec.
+ /// This method will continue reading entries from the input until the end is reached, or
+ /// a different tag is encountered.
+ /// </remarks>
+ /// <param name="ctx">Input to read from</param>
+ /// <param name="codec">Codec describing how the key/value pairs are encoded</param>
+ [SecuritySafeCritical]
+ public void AddEntriesFrom(ref ParseContext ctx, Codec codec)
+ {
var adapter = new Codec.MessageAdapter(codec);
do
{
adapter.Reset();
- input.ReadMessage(adapter);
+ ctx.ReadMessage(adapter);
this[adapter.Key] = adapter.Value;
- } while (input.MaybeConsumeTag(codec.MapTag));
+ } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, codec.MapTag));
}
/// <summary>
@@ -620,7 +646,7 @@
/// This is nested inside Codec as it's tightly coupled to the associated codec,
/// and it's simpler if it has direct access to all its fields.
/// </summary>
- internal class MessageAdapter : IMessage
+ internal class MessageAdapter : IMessage, IBufferMessage
{
private static readonly byte[] ZeroLengthMessageStreamData = new byte[] { 0 };
@@ -641,28 +667,45 @@
public void MergeFrom(CodedInputStream input)
{
+ // Message adapter is an internal class and we know that all the parsing will happen via InternalMergeFrom.
+ throw new NotImplementedException();
+ }
+
+ [SecuritySafeCritical]
+ public void InternalMergeFrom(ref ParseContext ctx)
+ {
uint tag;
- while ((tag = input.ReadTag()) != 0)
+ while ((tag = ctx.ReadTag()) != 0)
{
if (tag == codec.keyCodec.Tag)
{
- Key = codec.keyCodec.Read(input);
+ Key = codec.keyCodec.Read(ref ctx);
}
else if (tag == codec.valueCodec.Tag)
{
- Value = codec.valueCodec.Read(input);
+ Value = codec.valueCodec.Read(ref ctx);
}
else
{
- input.SkipLastField();
+ ParsingPrimitivesMessages.SkipLastField(ref ctx.buffer, ref ctx.state);
}
}
// Corner case: a map entry with a key but no value, where the value type is a message.
- // Read it as if we'd seen an input stream with no data (i.e. create a "default" message).
+ // Read it as if we'd seen input with no data (i.e. create a "default" message).
if (Value == null)
{
- Value = codec.valueCodec.Read(new CodedInputStream(ZeroLengthMessageStreamData));
+ if (ctx.state.CodedInputStream != null)
+ {
+ // the decoded message might not support parsing from ParseContext, so
+ // we need to allow fallback to the legacy MergeFrom(CodedInputStream) parsing.
+ Value = codec.valueCodec.Read(new CodedInputStream(ZeroLengthMessageStreamData));
+ }
+ else
+ {
+ ParseContext.Initialize(new ReadOnlySequence<byte>(ZeroLengthMessageStreamData), out ParseContext zeroLengthCtx);
+ Value = codec.valueCodec.Read(ref zeroLengthCtx);
+ }
}
}
diff --git a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
index 0e8bb61..5c39aab 100644
--- a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
+++ b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
@@ -34,6 +34,7 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
+using System.Security;
namespace Google.Protobuf.Collections
{
@@ -95,22 +96,41 @@
/// <param name="codec">The codec to use in order to read each entry.</param>
public void AddEntriesFrom(CodedInputStream input, FieldCodec<T> codec)
{
+ ParseContext.Initialize(input, out ParseContext ctx);
+ try
+ {
+ AddEntriesFrom(ref ctx, codec);
+ }
+ finally
+ {
+ ctx.CopyStateTo(input);
+ }
+ }
+
+ /// <summary>
+ /// Adds the entries from the given parse context, decoding them with the specified codec.
+ /// </summary>
+ /// <param name="ctx">The input to read from.</param>
+ /// <param name="codec">The codec to use in order to read each entry.</param>
+ [SecuritySafeCritical]
+ public void AddEntriesFrom(ref ParseContext ctx, FieldCodec<T> codec)
+ {
// TODO: Inline some of the Add code, so we can avoid checking the size on every
// iteration.
- uint tag = input.LastTag;
+ uint tag = ctx.state.lastTag;
var reader = codec.ValueReader;
// Non-nullable value types can be packed or not.
if (FieldCodec<T>.IsPackedRepeatedField(tag))
{
- int length = input.ReadLength();
+ int length = ctx.ReadLength();
if (length > 0)
{
- int oldLimit = input.PushLimit(length);
- while (!input.ReachedLimit)
+ int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length);
+ while (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state))
{
- Add(reader(input));
+ Add(reader(ref ctx));
}
- input.PopLimit(oldLimit);
+ SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit);
}
// Empty packed field. Odd, but valid - just ignore.
}
@@ -119,8 +139,8 @@
// Not packed... (possibly not packable)
do
{
- Add(reader(input));
- } while (input.MaybeConsumeTag(tag));
+ Add(reader(ref ctx));
+ } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, tag));
}
}
diff --git a/csharp/src/Google.Protobuf/Extension.cs b/csharp/src/Google.Protobuf/Extension.cs
index a96f8d2..6dd1cea 100644
--- a/csharp/src/Google.Protobuf/Extension.cs
+++ b/csharp/src/Google.Protobuf/Extension.cs
@@ -55,6 +55,8 @@
/// Gets the field number of this extension
/// </summary>
public int FieldNumber { get; }
+
+ internal abstract bool IsRepeated { get; }
}
/// <summary>
@@ -79,6 +81,8 @@
internal override Type TargetType => typeof(TTarget);
+ internal override bool IsRepeated => false;
+
internal override IExtensionValue CreateValue()
{
return new ExtensionValue<TValue>(codec);
@@ -105,6 +109,8 @@
internal override Type TargetType => typeof(TTarget);
+ internal override bool IsRepeated => true;
+
internal override IExtensionValue CreateValue()
{
return new RepeatedExtensionValue<TValue>(codec);
diff --git a/csharp/src/Google.Protobuf/ExtensionRegistry.cs b/csharp/src/Google.Protobuf/ExtensionRegistry.cs
index 2318e44..e72314b 100644
--- a/csharp/src/Google.Protobuf/ExtensionRegistry.cs
+++ b/csharp/src/Google.Protobuf/ExtensionRegistry.cs
@@ -42,6 +42,19 @@
/// </summary>
public sealed class ExtensionRegistry : ICollection<Extension>, IDeepCloneable<ExtensionRegistry>
{
+ internal sealed class ExtensionComparer : IEqualityComparer<Extension>
+ {
+ public bool Equals(Extension a, Extension b)
+ {
+ return new ObjectIntPair<Type>(a.TargetType, a.FieldNumber).Equals(new ObjectIntPair<Type>(b.TargetType, b.FieldNumber));
+ }
+ public int GetHashCode(Extension a)
+ {
+ return new ObjectIntPair<Type>(a.TargetType, a.FieldNumber).GetHashCode();
+ }
+
+ internal static ExtensionComparer Instance = new ExtensionComparer();
+ }
private IDictionary<ObjectIntPair<Type>, Extension> extensions;
/// <summary>
@@ -67,9 +80,9 @@
/// </summary>
bool ICollection<Extension>.IsReadOnly => false;
- internal bool ContainsInputField(CodedInputStream stream, Type target, out Extension extension)
+ internal bool ContainsInputField(uint lastTag, Type target, out Extension extension)
{
- return extensions.TryGetValue(new ObjectIntPair<Type>(target, WireFormat.GetTagFieldNumber(stream.LastTag)), out extension);
+ return extensions.TryGetValue(new ObjectIntPair<Type>(target, WireFormat.GetTagFieldNumber(lastTag)), out extension);
}
/// <summary>
@@ -83,7 +96,7 @@
}
/// <summary>
- /// Adds the specified extensions to the reigstry
+ /// Adds the specified extensions to the registry
/// </summary>
public void AddRange(IEnumerable<Extension> extensions)
{
diff --git a/csharp/src/Google.Protobuf/ExtensionSet.cs b/csharp/src/Google.Protobuf/ExtensionSet.cs
index d1bbf69..dd0b9a5 100644
--- a/csharp/src/Google.Protobuf/ExtensionSet.cs
+++ b/csharp/src/Google.Protobuf/ExtensionSet.cs
@@ -183,19 +183,36 @@
/// </summary>
public static bool TryMergeFieldFrom<TTarget>(ref ExtensionSet<TTarget> set, CodedInputStream stream) where TTarget : IExtendableMessage<TTarget>
{
+ ParseContext.Initialize(stream, out ParseContext ctx);
+ try
+ {
+ return TryMergeFieldFrom<TTarget>(ref set, ref ctx);
+ }
+ finally
+ {
+ ctx.CopyStateTo(stream);
+ }
+ }
+
+ /// <summary>
+ /// Tries to merge a field from the coded input, returning true if the field was merged.
+ /// If the set is null or the field was not otherwise merged, this returns false.
+ /// </summary>
+ public static bool TryMergeFieldFrom<TTarget>(ref ExtensionSet<TTarget> set, ref ParseContext ctx) where TTarget : IExtendableMessage<TTarget>
+ {
Extension extension;
- int lastFieldNumber = WireFormat.GetTagFieldNumber(stream.LastTag);
-
+ int lastFieldNumber = WireFormat.GetTagFieldNumber(ctx.LastTag);
+
IExtensionValue extensionValue;
if (set != null && set.ValuesByNumber.TryGetValue(lastFieldNumber, out extensionValue))
{
- extensionValue.MergeFrom(stream);
+ extensionValue.MergeFrom(ref ctx);
return true;
}
- else if (stream.ExtensionRegistry != null && stream.ExtensionRegistry.ContainsInputField(stream, typeof(TTarget), out extension))
+ else if (ctx.ExtensionRegistry != null && ctx.ExtensionRegistry.ContainsInputField(ctx.LastTag, typeof(TTarget), out extension))
{
IExtensionValue value = extension.CreateValue();
- value.MergeFrom(stream);
+ value.MergeFrom(ref ctx);
set = (set ?? new ExtensionSet<TTarget>());
set.ValuesByNumber.Add(extension.FieldNumber, value);
return true;
diff --git a/csharp/src/Google.Protobuf/ExtensionValue.cs b/csharp/src/Google.Protobuf/ExtensionValue.cs
index 6ee737a..df934ed 100644
--- a/csharp/src/Google.Protobuf/ExtensionValue.cs
+++ b/csharp/src/Google.Protobuf/ExtensionValue.cs
@@ -38,7 +38,8 @@
{
internal interface IExtensionValue : IEquatable<IExtensionValue>, IDeepCloneable<IExtensionValue>
{
- void MergeFrom(CodedInputStream input);
+ void MergeFrom(ref ParseContext ctx);
+
void MergeFrom(IExtensionValue value);
void WriteTo(CodedOutputStream output);
int CalculateSize();
@@ -91,16 +92,16 @@
}
}
- public void MergeFrom(CodedInputStream input)
+ public void MergeFrom(ref ParseContext ctx)
{
- codec.ValueMerger(input, ref field);
+ codec.ValueMerger(ref ctx, ref field);
}
public void MergeFrom(IExtensionValue value)
{
if (value is ExtensionValue<T>)
{
- var extensionValue = value as ExtensionValue<T>;
+ var extensionValue = value as ExtensionValue<T>;
codec.FieldMerger(ref field, extensionValue.field);
}
}
@@ -124,13 +125,13 @@
public bool IsInitialized()
{
- if (field is IMessage)
- {
- return (field as IMessage).IsInitialized();
+ if (field is IMessage)
+ {
+ return (field as IMessage).IsInitialized();
}
- else
- {
- return true;
+ else
+ {
+ return true;
}
}
}
@@ -185,6 +186,11 @@
field.AddEntriesFrom(input, codec);
}
+ public void MergeFrom(ref ParseContext ctx)
+ {
+ field.AddEntriesFrom(ref ctx, codec);
+ }
+
public void MergeFrom(IExtensionValue value)
{
if (value is RepeatedExtensionValue<T>)
@@ -202,20 +208,20 @@
public bool IsInitialized()
{
- for (int i = 0; i < field.Count; i++)
- {
- var element = field[i];
- if (element is IMessage)
- {
- if (!(element as IMessage).IsInitialized())
- {
- return false;
- }
- }
- else
- {
- break;
- }
+ for (int i = 0; i < field.Count; i++)
+ {
+ var element = field[i];
+ if (element is IMessage)
+ {
+ if (!(element as IMessage).IsInitialized())
+ {
+ return false;
+ }
+ }
+ else
+ {
+ break;
+ }
}
return true;
diff --git a/csharp/src/Google.Protobuf/FieldCodec.cs b/csharp/src/Google.Protobuf/FieldCodec.cs
index 1971261..ee87736 100644
--- a/csharp/src/Google.Protobuf/FieldCodec.cs
+++ b/csharp/src/Google.Protobuf/FieldCodec.cs
@@ -35,6 +35,7 @@
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
+using System.Security;
namespace Google.Protobuf
{
@@ -218,7 +219,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<string> ForString(uint tag, string defaultValue)
{
- return new FieldCodec<string>(input => input.ReadString(), (output, value) => output.WriteString(value), CodedOutputStream.ComputeStringSize, tag, defaultValue);
+ return new FieldCodec<string>((ref ParseContext ctx) => ctx.ReadString(), (output, value) => output.WriteString(value), CodedOutputStream.ComputeStringSize, tag, defaultValue);
}
/// <summary>
@@ -229,7 +230,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<ByteString> ForBytes(uint tag, ByteString defaultValue)
{
- return new FieldCodec<ByteString>(input => input.ReadBytes(), (output, value) => output.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag, defaultValue);
+ return new FieldCodec<ByteString>((ref ParseContext ctx) => ctx.ReadBytes(), (output, value) => output.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag, defaultValue);
}
/// <summary>
@@ -240,7 +241,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<bool> ForBool(uint tag, bool defaultValue)
{
- return new FieldCodec<bool>(input => input.ReadBool(), (output, value) => output.WriteBool(value), CodedOutputStream.BoolSize, tag, defaultValue);
+ return new FieldCodec<bool>((ref ParseContext ctx) => ctx.ReadBool(), (output, value) => output.WriteBool(value), CodedOutputStream.BoolSize, tag, defaultValue);
}
/// <summary>
@@ -251,7 +252,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<int> ForInt32(uint tag, int defaultValue)
{
- return new FieldCodec<int>(input => input.ReadInt32(), (output, value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag, defaultValue);
+ return new FieldCodec<int>((ref ParseContext ctx) => ctx.ReadInt32(), (output, value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag, defaultValue);
}
/// <summary>
@@ -262,7 +263,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<int> ForSInt32(uint tag, int defaultValue)
{
- return new FieldCodec<int>(input => input.ReadSInt32(), (output, value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag, defaultValue);
+ return new FieldCodec<int>((ref ParseContext ctx) => ctx.ReadSInt32(), (output, value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag, defaultValue);
}
/// <summary>
@@ -273,7 +274,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<uint> ForFixed32(uint tag, uint defaultValue)
{
- return new FieldCodec<uint>(input => input.ReadFixed32(), (output, value) => output.WriteFixed32(value), 4, tag, defaultValue);
+ return new FieldCodec<uint>((ref ParseContext ctx) => ctx.ReadFixed32(), (output, value) => output.WriteFixed32(value), 4, tag, defaultValue);
}
/// <summary>
@@ -284,7 +285,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<int> ForSFixed32(uint tag, int defaultValue)
{
- return new FieldCodec<int>(input => input.ReadSFixed32(), (output, value) => output.WriteSFixed32(value), 4, tag, defaultValue);
+ return new FieldCodec<int>((ref ParseContext ctx) => ctx.ReadSFixed32(), (output, value) => output.WriteSFixed32(value), 4, tag, defaultValue);
}
/// <summary>
@@ -295,7 +296,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<uint> ForUInt32(uint tag, uint defaultValue)
{
- return new FieldCodec<uint>(input => input.ReadUInt32(), (output, value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag, defaultValue);
+ return new FieldCodec<uint>((ref ParseContext ctx) => ctx.ReadUInt32(), (output, value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag, defaultValue);
}
/// <summary>
@@ -306,7 +307,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<long> ForInt64(uint tag, long defaultValue)
{
- return new FieldCodec<long>(input => input.ReadInt64(), (output, value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag, defaultValue);
+ return new FieldCodec<long>((ref ParseContext ctx) => ctx.ReadInt64(), (output, value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag, defaultValue);
}
/// <summary>
@@ -317,7 +318,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<long> ForSInt64(uint tag, long defaultValue)
{
- return new FieldCodec<long>(input => input.ReadSInt64(), (output, value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag, defaultValue);
+ return new FieldCodec<long>((ref ParseContext ctx) => ctx.ReadSInt64(), (output, value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag, defaultValue);
}
/// <summary>
@@ -328,7 +329,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<ulong> ForFixed64(uint tag, ulong defaultValue)
{
- return new FieldCodec<ulong>(input => input.ReadFixed64(), (output, value) => output.WriteFixed64(value), 8, tag, defaultValue);
+ return new FieldCodec<ulong>((ref ParseContext ctx) => ctx.ReadFixed64(), (output, value) => output.WriteFixed64(value), 8, tag, defaultValue);
}
/// <summary>
@@ -339,7 +340,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<long> ForSFixed64(uint tag, long defaultValue)
{
- return new FieldCodec<long>(input => input.ReadSFixed64(), (output, value) => output.WriteSFixed64(value), 8, tag, defaultValue);
+ return new FieldCodec<long>((ref ParseContext ctx) => ctx.ReadSFixed64(), (output, value) => output.WriteSFixed64(value), 8, tag, defaultValue);
}
/// <summary>
@@ -350,7 +351,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<ulong> ForUInt64(uint tag, ulong defaultValue)
{
- return new FieldCodec<ulong>(input => input.ReadUInt64(), (output, value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag, defaultValue);
+ return new FieldCodec<ulong>((ref ParseContext ctx) => ctx.ReadUInt64(), (output, value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag, defaultValue);
}
/// <summary>
@@ -361,7 +362,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<float> ForFloat(uint tag, float defaultValue)
{
- return new FieldCodec<float>(input => input.ReadFloat(), (output, value) => output.WriteFloat(value), CodedOutputStream.FloatSize, tag, defaultValue);
+ return new FieldCodec<float>((ref ParseContext ctx) => ctx.ReadFloat(), (output, value) => output.WriteFloat(value), CodedOutputStream.FloatSize, tag, defaultValue);
}
/// <summary>
@@ -372,7 +373,7 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<double> ForDouble(uint tag, double defaultValue)
{
- return new FieldCodec<double>(input => input.ReadDouble(), (output, value) => output.WriteDouble(value), CodedOutputStream.DoubleSize, tag, defaultValue);
+ return new FieldCodec<double>((ref ParseContext ctx) => ctx.ReadDouble(), (output, value) => output.WriteDouble(value), CodedOutputStream.DoubleSize, tag, defaultValue);
}
// Enums are tricky. We can probably use expression trees to build these delegates automatically,
@@ -388,8 +389,8 @@
/// <returns>A codec for the given tag.</returns>
public static FieldCodec<T> ForEnum<T>(uint tag, Func<T, int> toInt32, Func<int, T> fromInt32, T defaultValue)
{
- return new FieldCodec<T>(input => fromInt32(
- input.ReadEnum()),
+ return new FieldCodec<T>((ref ParseContext ctx) => fromInt32(
+ ctx.ReadEnum()),
(output, value) => output.WriteEnum(toInt32(value)),
value => CodedOutputStream.ComputeEnumSize(toInt32(value)), tag, defaultValue);
}
@@ -403,21 +404,21 @@
public static FieldCodec<T> ForMessage<T>(uint tag, MessageParser<T> parser) where T : class, IMessage<T>
{
return new FieldCodec<T>(
- input =>
+ (ref ParseContext ctx) =>
{
T message = parser.CreateTemplate();
- input.ReadMessage(message);
+ ctx.ReadMessage(message);
return message;
},
(output, value) => output.WriteMessage(value),
- (CodedInputStream i, ref T v) =>
+ (ref ParseContext ctx, ref T v) =>
{
if (v == null)
{
v = parser.CreateTemplate();
}
- i.ReadMessage(v);
+ ctx.ReadMessage(v);
},
(ref T v, T v2) =>
{
@@ -448,21 +449,21 @@
public static FieldCodec<T> ForGroup<T>(uint startTag, uint endTag, MessageParser<T> parser) where T : class, IMessage<T>
{
return new FieldCodec<T>(
- input =>
+ (ref ParseContext ctx) =>
{
T message = parser.CreateTemplate();
- input.ReadGroup(message);
+ ctx.ReadGroup(message);
return message;
},
(output, value) => output.WriteGroup(value),
- (CodedInputStream i, ref T v) =>
+ (ref ParseContext ctx, ref T v) =>
{
if (v == null)
{
v = parser.CreateTemplate();
}
- i.ReadGroup(v);
+ ctx.ReadGroup(v);
},
(ref T v, T v2) =>
{
@@ -490,9 +491,9 @@
{
var nestedCodec = WrapperCodecs.GetCodec<T>();
return new FieldCodec<T>(
- input => WrapperCodecs.Read<T>(input, nestedCodec),
+ (ref ParseContext ctx) => WrapperCodecs.Read<T>(ref ctx, nestedCodec),
(output, value) => WrapperCodecs.Write<T>(output, value, nestedCodec),
- (CodedInputStream i, ref T v) => v = WrapperCodecs.Read<T>(i, nestedCodec),
+ (ref ParseContext ctx, ref T v) => v = WrapperCodecs.Read<T>(ref ctx, nestedCodec),
(ref T v, T v2) => { v = v2; return v == null; },
value => WrapperCodecs.CalculateSize<T>(value, nestedCodec),
tag, 0,
@@ -509,7 +510,7 @@
return new FieldCodec<T?>(
WrapperCodecs.GetReader<T>(),
(output, value) => WrapperCodecs.Write<T>(output, value.Value, nestedCodec),
- (CodedInputStream i, ref T? v) => v = WrapperCodecs.Read<T>(i, nestedCodec),
+ (ref ParseContext ctx, ref T? v) => v = WrapperCodecs.Read<T>(ref ctx, nestedCodec),
(ref T? v, T? v2) => { if (v2.HasValue) { v = v2; } return v.HasValue; },
value => value == null ? 0 : WrapperCodecs.CalculateSize<T>(value.Value, nestedCodec),
tag, 0,
@@ -542,17 +543,17 @@
private static readonly Dictionary<System.Type, object> Readers = new Dictionary<System.Type, object>
{
// TODO: Provide more optimized readers.
- { typeof(bool), (Func<CodedInputStream, bool?>)CodedInputStream.ReadBoolWrapper },
- { typeof(int), (Func<CodedInputStream, int?>)CodedInputStream.ReadInt32Wrapper },
- { typeof(long), (Func<CodedInputStream, long?>)CodedInputStream.ReadInt64Wrapper },
- { typeof(uint), (Func<CodedInputStream, uint?>)CodedInputStream.ReadUInt32Wrapper },
- { typeof(ulong), (Func<CodedInputStream, ulong?>)CodedInputStream.ReadUInt64Wrapper },
+ { typeof(bool), (ValueReader<bool?>)ParsingPrimitivesWrappers.ReadBoolWrapper },
+ { typeof(int), (ValueReader<int?>)ParsingPrimitivesWrappers.ReadInt32Wrapper },
+ { typeof(long), (ValueReader<long?>)ParsingPrimitivesWrappers.ReadInt64Wrapper },
+ { typeof(uint), (ValueReader<uint?>)ParsingPrimitivesWrappers.ReadUInt32Wrapper },
+ { typeof(ulong), (ValueReader<ulong?>)ParsingPrimitivesWrappers.ReadUInt64Wrapper },
{ typeof(float), BitConverter.IsLittleEndian ?
- (Func<CodedInputStream, float?>)CodedInputStream.ReadFloatWrapperLittleEndian :
- (Func<CodedInputStream, float?>)CodedInputStream.ReadFloatWrapperSlow },
+ (ValueReader<float?>)ParsingPrimitivesWrappers.ReadFloatWrapperLittleEndian :
+ (ValueReader<float?>)ParsingPrimitivesWrappers.ReadFloatWrapperSlow },
{ typeof(double), BitConverter.IsLittleEndian ?
- (Func<CodedInputStream, double?>)CodedInputStream.ReadDoubleWrapperLittleEndian :
- (Func<CodedInputStream, double?>)CodedInputStream.ReadDoubleWrapperSlow },
+ (ValueReader<double?>)ParsingPrimitivesWrappers.ReadDoubleWrapperLittleEndian :
+ (ValueReader<double?>)ParsingPrimitivesWrappers.ReadDoubleWrapperSlow },
// `string` and `ByteString` less performance-sensitive. Do not implement for now.
{ typeof(string), null },
{ typeof(ByteString), null },
@@ -572,7 +573,7 @@
return (FieldCodec<T>) value;
}
- internal static Func<CodedInputStream, T?> GetReader<T>() where T : struct
+ internal static ValueReader<T?> GetReader<T>() where T : struct
{
object value;
if (!Readers.TryGetValue(typeof(T), out value))
@@ -583,33 +584,34 @@
{
// Return default unoptimized reader for the wrapper type.
var nestedCoded = GetCodec<T>();
- return input => Read<T>(input, nestedCoded);
+ return (ref ParseContext ctx) => Read<T>(ref ctx, nestedCoded);
}
// Return optimized read for the wrapper type.
- return (Func<CodedInputStream, T?>)value;
+ return (ValueReader<T?>)value;
}
- internal static T Read<T>(CodedInputStream input, FieldCodec<T> codec)
+ [SecuritySafeCritical]
+ internal static T Read<T>(ref ParseContext ctx, FieldCodec<T> codec)
{
- int length = input.ReadLength();
- int oldLimit = input.PushLimit(length);
+ int length = ctx.ReadLength();
+ int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length);
uint tag;
T value = codec.DefaultValue;
- while ((tag = input.ReadTag()) != 0)
+ while ((tag = ctx.ReadTag()) != 0)
{
if (tag == codec.Tag)
{
- value = codec.Read(input);
+ value = codec.Read(ref ctx);
}
else
{
- input.SkipLastField();
+ ParsingPrimitivesMessages.SkipLastField(ref ctx.buffer, ref ctx.state);
}
}
- input.CheckReadEndOfStreamTag();
- input.PopLimit(oldLimit);
+ ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref ctx.state);
+ SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit);
return value;
}
@@ -628,6 +630,8 @@
}
}
+ internal delegate TValue ValueReader<out TValue>(ref ParseContext ctx);
+
/// <summary>
/// <para>
/// An encode/decode pair for a single field. This effectively encapsulates
@@ -653,7 +657,7 @@
/// <summary>
/// Merges an input stream into a value
/// </summary>
- internal delegate void InputMerger(CodedInputStream input, ref T value);
+ internal delegate void InputMerger(ref ParseContext ctx, ref T value);
/// <summary>
/// Merges a value into a reference to another value, returning a boolean if the value was set
@@ -692,7 +696,7 @@
/// Returns a delegate to read a value from a coded input stream. It is assumed that
/// the stream is already positioned on the appropriate tag.
/// </summary>
- internal Func<CodedInputStream, T> ValueReader { get; }
+ internal ValueReader<T> ValueReader { get; }
/// <summary>
/// Returns a delegate to merge a value from a coded input stream.
@@ -739,7 +743,7 @@
private readonly int tagSize;
internal FieldCodec(
- Func<CodedInputStream, T> reader,
+ ValueReader<T> reader,
Action<CodedOutputStream, T> writer,
int fixedSize,
uint tag,
@@ -749,16 +753,16 @@
}
internal FieldCodec(
- Func<CodedInputStream, T> reader,
+ ValueReader<T> reader,
Action<CodedOutputStream, T> writer,
Func<T, int> sizeCalculator,
uint tag,
- T defaultValue) : this(reader, writer, (CodedInputStream i, ref T v) => v = reader(i), (ref T v, T v2) => { v = v2; return true; }, sizeCalculator, tag, 0, defaultValue)
+ T defaultValue) : this(reader, writer, (ref ParseContext ctx, ref T v) => v = reader(ref ctx), (ref T v, T v2) => { v = v2; return true; }, sizeCalculator, tag, 0, defaultValue)
{
}
internal FieldCodec(
- Func<CodedInputStream, T> reader,
+ ValueReader<T> reader,
Action<CodedOutputStream, T> writer,
InputMerger inputMerger,
ValuesMerger valuesMerger,
@@ -769,7 +773,7 @@
}
internal FieldCodec(
- Func<CodedInputStream, T> reader,
+ ValueReader<T> reader,
Action<CodedOutputStream, T> writer,
InputMerger inputMerger,
ValuesMerger valuesMerger,
@@ -815,7 +819,28 @@
/// </summary>
/// <param name="input">The input stream to read from.</param>
/// <returns>The value read from the stream.</returns>
- public T Read(CodedInputStream input) => ValueReader(input);
+ public T Read(CodedInputStream input)
+ {
+ ParseContext.Initialize(input, out ParseContext ctx);
+ try
+ {
+ return ValueReader(ref ctx);
+ }
+ finally
+ {
+ ctx.CopyStateTo(input);
+ }
+ }
+
+ /// <summary>
+ /// Reads a value of the codec type from the given <see cref="ParseContext"/>.
+ /// </summary>
+ /// <param name="ctx">The parse context to read from.</param>
+ /// <returns>The value read.</returns>
+ public T Read(ref ParseContext ctx)
+ {
+ return ValueReader(ref ctx);
+ }
/// <summary>
/// Calculates the size required to write the given value, with a tag,
diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
index 837b565..5c5b4e7 100644
--- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj
+++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
@@ -4,10 +4,11 @@
<Description>C# runtime library for Protocol Buffers - Google's data interchange format.</Description>
<Copyright>Copyright 2015, Google Inc.</Copyright>
<AssemblyTitle>Google Protocol Buffers</AssemblyTitle>
- <VersionPrefix>3.11.0-rc1</VersionPrefix>
- <LangVersion>6</LangVersion>
+ <VersionPrefix>3.12.0-rc2</VersionPrefix>
+ <!-- C# 7.2 is required for Span/BufferWriter/ReadOnlySequence -->
+ <LangVersion>7.2</LangVersion>
<Authors>Google Inc.</Authors>
- <TargetFrameworks>netstandard1.0;netstandard2.0;net45</TargetFrameworks>
+ <TargetFrameworks>netstandard1.1;netstandard2.0;net45</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
@@ -18,25 +19,26 @@
<PackageLicenseUrl>https://github.com/protocolbuffers/protobuf/blob/master/LICENSE</PackageLicenseUrl>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/protocolbuffers/protobuf.git</RepositoryUrl>
+ <DefineConstants>$(DefineConstants);GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY</DefineConstants>
+ <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<!-- Include PDB in the built .nupkg -->
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
</PropertyGroup>
- <PropertyGroup Condition=" '$(TargetFramework)' == 'net45' or '$(TargetFramework)' == 'netstandard2.0' ">
- <DefineConstants>$(DefineConstants);GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY</DefineConstants>
+ <PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
+ <DefineConstants>$(DefineConstants);GOOGLE_PROTOBUF_SUPPORT_FAST_STRING</DefineConstants>
</PropertyGroup>
- <!-- Needed for the net45 build to work on Unix. See https://github.com/dotnet/designs/pull/33 -->
<ItemGroup>
- <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" PrivateAssets="All" Version="1.0.0-preview.2"/>
- </ItemGroup>
-
- <ItemGroup Condition=" '$(TargetFramework)' == 'net45' or '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="System.Memory" Version="4.5.2"/>
+ <PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="1.0.0-beta2-18618-05"/>
+ <!-- Needed for the net45 build to work on Unix. See https://github.com/dotnet/designs/pull/33 -->
+ <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" PrivateAssets="All" Version="1.0.0"/>
</ItemGroup>
- <ItemGroup>
- <PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="1.0.0-beta2-18618-05"/>
+ <!-- Needed for netcoreapp2.1 to work correctly. .NET is not able to load the assembly without this -->
+ <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
+ <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.5.2"/>
</ItemGroup>
</Project>
diff --git a/csharp/src/Google.Protobuf/IBufferMessage.cs b/csharp/src/Google.Protobuf/IBufferMessage.cs
new file mode 100644
index 0000000..f6d174b
--- /dev/null
+++ b/csharp/src/Google.Protobuf/IBufferMessage.cs
@@ -0,0 +1,49 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+namespace Google.Protobuf
+{
+#if GOOGLE_PROTOBUF_SUPPORT_SYSTEM_MEMORY
+ /// <summary>
+ /// Interface for a Protocol Buffers message, supporting
+ /// parsing from <see cref="ParseContext"/>.
+ /// </summary>
+ public interface IBufferMessage : IMessage
+ {
+ /// <summary>
+ /// Internal implementation of merging data from given parse context into this message.
+ /// Users should never invoke this method directly.
+ /// </summary>
+ void InternalMergeFrom(ref ParseContext ctx);
+ }
+#endif
+}
diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs
index 2b4c5f0..5aaefe7 100644
--- a/csharp/src/Google.Protobuf/JsonFormatter.cs
+++ b/csharp/src/Google.Protobuf/JsonFormatter.cs
@@ -133,7 +133,7 @@
/// <param name="settings">The settings.</param>
public JsonFormatter(Settings settings)
{
- this.settings = settings;
+ this.settings = ProtoPreconditions.CheckNotNull(settings, nameof(settings));
}
/// <summary>
diff --git a/csharp/src/Google.Protobuf/JsonParser.cs b/csharp/src/Google.Protobuf/JsonParser.cs
index fb594f2..3f88ea3 100644
--- a/csharp/src/Google.Protobuf/JsonParser.cs
+++ b/csharp/src/Google.Protobuf/JsonParser.cs
@@ -110,7 +110,7 @@
/// <param name="settings">The settings.</param>
public JsonParser(Settings settings)
{
- this.settings = settings;
+ this.settings = ProtoPreconditions.CheckNotNull(settings, nameof(settings));
}
/// <summary>
diff --git a/csharp/src/Google.Protobuf/MessageExtensions.cs b/csharp/src/Google.Protobuf/MessageExtensions.cs
index 06e0980..51e4091 100644
--- a/csharp/src/Google.Protobuf/MessageExtensions.cs
+++ b/csharp/src/Google.Protobuf/MessageExtensions.cs
@@ -31,9 +31,11 @@
#endregion
using Google.Protobuf.Reflection;
+using System.Buffers;
using System.Collections;
using System.IO;
using System.Linq;
+using System.Security;
namespace Google.Protobuf
{
@@ -248,6 +250,16 @@
codedInput.CheckReadEndOfStreamTag();
}
+ [SecuritySafeCritical]
+ internal static void MergeFrom(this IMessage message, ReadOnlySequence<byte> data, bool discardUnknownFields, ExtensionRegistry registry)
+ {
+ ParseContext.Initialize(data, out ParseContext ctx);
+ ctx.DiscardUnknownFields = discardUnknownFields;
+ ctx.ExtensionRegistry = registry;
+ ParsingPrimitivesMessages.ReadRawMessage(ref ctx, message);
+ ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref ctx.state);
+ }
+
internal static void MergeDelimitedFrom(this IMessage message, Stream input, bool discardUnknownFields, ExtensionRegistry registry)
{
ProtoPreconditions.CheckNotNull(message, "message");
diff --git a/csharp/src/Google.Protobuf/MessageParser.cs b/csharp/src/Google.Protobuf/MessageParser.cs
index 76a350c..f8b26c2 100644
--- a/csharp/src/Google.Protobuf/MessageParser.cs
+++ b/csharp/src/Google.Protobuf/MessageParser.cs
@@ -31,7 +31,9 @@
#endregion
using System;
+using System.Buffers;
using System.IO;
+using System.Security;
namespace Google.Protobuf
{
@@ -72,7 +74,6 @@
{
IMessage message = factory();
message.MergeFrom(data, DiscardUnknownFields, Extensions);
- CheckMergedRequiredFields(message);
return message;
}
@@ -87,7 +88,6 @@
{
IMessage message = factory();
message.MergeFrom(data, offset, length, DiscardUnknownFields, Extensions);
- CheckMergedRequiredFields(message);
return message;
}
@@ -100,7 +100,6 @@
{
IMessage message = factory();
message.MergeFrom(data, DiscardUnknownFields, Extensions);
- CheckMergedRequiredFields(message);
return message;
}
@@ -113,7 +112,19 @@
{
IMessage message = factory();
message.MergeFrom(input, DiscardUnknownFields, Extensions);
- CheckMergedRequiredFields(message);
+ return message;
+ }
+
+ /// <summary>
+ /// Parses a message from the given sequence.
+ /// </summary>
+ /// <param name="data">The data to parse.</param>
+ /// <returns>The parsed message.</returns>
+ [SecuritySafeCritical]
+ public IMessage ParseFrom(ReadOnlySequence<byte> data)
+ {
+ IMessage message = factory();
+ message.MergeFrom(data, DiscardUnknownFields, Extensions);
return message;
}
@@ -130,7 +141,6 @@
{
IMessage message = factory();
message.MergeDelimitedFrom(input, DiscardUnknownFields, Extensions);
- CheckMergedRequiredFields(message);
return message;
}
@@ -143,7 +153,6 @@
{
IMessage message = factory();
MergeFrom(message, input);
- CheckMergedRequiredFields(message);
return message;
}
@@ -176,12 +185,6 @@
}
}
- internal static void CheckMergedRequiredFields(IMessage message)
- {
- if (!message.IsInitialized())
- throw new InvalidOperationException("Parsed message does not contain all required fields");
- }
-
/// <summary>
/// Creates a new message parser which optionally discards unknown fields when parsing.
/// </summary>
@@ -300,6 +303,19 @@
}
/// <summary>
+ /// Parses a message from the given sequence.
+ /// </summary>
+ /// <param name="data">The data to parse.</param>
+ /// <returns>The parsed message.</returns>
+ [SecuritySafeCritical]
+ public new T ParseFrom(ReadOnlySequence<byte> data)
+ {
+ T message = factory();
+ message.MergeFrom(data, DiscardUnknownFields, Extensions);
+ return message;
+ }
+
+ /// <summary>
/// Parses a length-delimited message from the given stream.
/// </summary>
/// <remarks>
diff --git a/csharp/src/Google.Protobuf/ParseContext.cs b/csharp/src/Google.Protobuf/ParseContext.cs
new file mode 100644
index 0000000..bf46236
--- /dev/null
+++ b/csharp/src/Google.Protobuf/ParseContext.cs
@@ -0,0 +1,329 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+using Google.Protobuf.Collections;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// An opaque struct that represents the current parsing state and is passed along
+ /// as the parsing proceeds.
+ /// All the public methods are intended to be invoked only by the generated code,
+ /// users should never invoke them directly.
+ /// </summary>
+ [SecuritySafeCritical]
+ public ref struct ParseContext
+ {
+ internal const int DefaultRecursionLimit = 100;
+ internal const int DefaultSizeLimit = Int32.MaxValue;
+
+ internal ReadOnlySpan<byte> buffer;
+ internal ParserInternalState state;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static void Initialize(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, out ParseContext ctx)
+ {
+ ctx.buffer = buffer;
+ ctx.state = state;
+ }
+
+ /// <summary>
+ /// Creates a ParseContext instance from CodedInputStream.
+ /// WARNING: internally this copies the CodedInputStream's state, so after done with the ParseContext,
+ /// the CodedInputStream's state needs to be updated.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static void Initialize(CodedInputStream input, out ParseContext ctx)
+ {
+ ctx.buffer = new ReadOnlySpan<byte>(input.InternalBuffer);
+ // ideally we would use a reference to the original state, but that doesn't seem possible
+ // so we just copy the struct that holds the state. We will need to later store the state back
+ // into CodedInputStream if we want to keep it usable.
+ ctx.state = input.InternalState;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static void Initialize(ReadOnlySequence<byte> input, out ParseContext ctx)
+ {
+ Initialize(input, DefaultRecursionLimit, out ctx);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static void Initialize(ReadOnlySequence<byte> input, int recursionLimit, out ParseContext ctx)
+ {
+ ctx.buffer = default;
+ ctx.state = default;
+ ctx.state.lastTag = 0;
+ ctx.state.recursionDepth = 0;
+ ctx.state.sizeLimit = DefaultSizeLimit;
+ ctx.state.recursionLimit = recursionLimit;
+ ctx.state.currentLimit = int.MaxValue;
+ SegmentedBufferHelper.Initialize(input, out ctx.state.segmentedBufferHelper, out ctx.buffer);
+ ctx.state.bufferPos = 0;
+ ctx.state.bufferSize = ctx.buffer.Length;
+
+ ctx.state.DiscardUnknownFields = false;
+ ctx.state.ExtensionRegistry = null;
+ }
+
+ /// <summary>
+ /// Returns the last tag read, or 0 if no tags have been read or we've read beyond
+ /// the end of the input.
+ /// </summary>
+ internal uint LastTag { get { return state.lastTag; } }
+
+ /// <summary>
+ /// Internal-only property; when set to true, unknown fields will be discarded while parsing.
+ /// </summary>
+ internal bool DiscardUnknownFields {
+ get { return state.DiscardUnknownFields; }
+ set { state.DiscardUnknownFields = value; }
+ }
+
+ /// <summary>
+ /// Internal-only property; provides extension identifiers to compatible messages while parsing.
+ /// </summary>
+ internal ExtensionRegistry ExtensionRegistry
+ {
+ get { return state.ExtensionRegistry; }
+ set { state.ExtensionRegistry = value; }
+ }
+
+ /// <summary>
+ /// Reads a field tag, returning the tag of 0 for "end of input".
+ /// </summary>
+ /// <remarks>
+ /// If this method returns 0, it doesn't necessarily mean the end of all
+ /// the data in this CodedInputReader; it may be the end of the logical input
+ /// for an embedded message, for example.
+ /// </remarks>
+ /// <returns>The next field tag, or 0 for end of input. (0 is never a valid tag.)</returns>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public uint ReadTag()
+ {
+ return ParsingPrimitives.ParseTag(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads a double field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public double ReadDouble()
+ {
+ return ParsingPrimitives.ParseDouble(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads a float field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public float ReadFloat()
+ {
+ return ParsingPrimitives.ParseFloat(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads a uint64 field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ulong ReadUInt64()
+ {
+ return ParsingPrimitives.ParseRawVarint64(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads an int64 field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public long ReadInt64()
+ {
+ return (long)ParsingPrimitives.ParseRawVarint64(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads an int32 field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int ReadInt32()
+ {
+ return (int)ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads a fixed64 field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ulong ReadFixed64()
+ {
+ return ParsingPrimitives.ParseRawLittleEndian64(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads a fixed32 field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public uint ReadFixed32()
+ {
+ return ParsingPrimitives.ParseRawLittleEndian32(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads a bool field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool ReadBool()
+ {
+ return ParsingPrimitives.ParseRawVarint64(ref buffer, ref state) != 0;
+ }
+ /// <summary>
+ /// Reads a string field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public string ReadString()
+ {
+ return ParsingPrimitives.ReadString(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads an embedded message field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void ReadMessage(IMessage message)
+ {
+ ParsingPrimitivesMessages.ReadMessage(ref this, message);
+ }
+
+ /// <summary>
+ /// Reads an embedded group field from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void ReadGroup(IMessage message)
+ {
+ ParsingPrimitivesMessages.ReadGroup(ref this, message);
+ }
+
+ /// <summary>
+ /// Reads a bytes field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ByteString ReadBytes()
+ {
+ return ParsingPrimitives.ReadBytes(ref buffer, ref state);
+ }
+ /// <summary>
+ /// Reads a uint32 field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public uint ReadUInt32()
+ {
+ return ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads an enum field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int ReadEnum()
+ {
+ // Currently just a pass-through, but it's nice to separate it logically from WriteInt32.
+ return (int)ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads an sfixed32 field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int ReadSFixed32()
+ {
+ return (int)ParsingPrimitives.ParseRawLittleEndian32(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads an sfixed64 field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public long ReadSFixed64()
+ {
+ return (long)ParsingPrimitives.ParseRawLittleEndian64(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Reads an sint32 field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int ReadSInt32()
+ {
+ return ParsingPrimitives.DecodeZigZag32(ParsingPrimitives.ParseRawVarint32(ref buffer, ref state));
+ }
+
+ /// <summary>
+ /// Reads an sint64 field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public long ReadSInt64()
+ {
+ return ParsingPrimitives.DecodeZigZag64(ParsingPrimitives.ParseRawVarint64(ref buffer, ref state));
+ }
+
+ /// <summary>
+ /// Reads a length for length-delimited data.
+ /// </summary>
+ /// <remarks>
+ /// This is internally just reading a varint, but this method exists
+ /// to make the calling code clearer.
+ /// </remarks>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int ReadLength()
+ {
+ return (int)ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ }
+
+ internal void CopyStateTo(CodedInputStream input)
+ {
+ input.InternalState = state;
+ }
+
+ internal void LoadStateFrom(CodedInputStream input)
+ {
+ state = input.InternalState;
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/ParserInternalState.cs b/csharp/src/Google.Protobuf/ParserInternalState.cs
new file mode 100644
index 0000000..4f0500b
--- /dev/null
+++ b/csharp/src/Google.Protobuf/ParserInternalState.cs
@@ -0,0 +1,115 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+using Google.Protobuf.Collections;
+
+namespace Google.Protobuf
+{
+
+ // warning: this is a mutable struct, so it needs to be only passed as a ref!
+ internal struct ParserInternalState
+ {
+ // NOTE: the Span representing the current buffer is kept separate so that this doesn't have to be a ref struct and so it can live
+ // be included in CodedInputStream's internal state
+
+ /// <summary>
+ /// The position within the current buffer (i.e. the next byte to read)
+ /// </summary>
+ internal int bufferPos;
+
+ /// <summary>
+ /// Size of the current buffer
+ /// </summary>
+ internal int bufferSize;
+
+ /// <summary>
+ /// If we are currently inside a length-delimited block, this is the number of
+ /// bytes in the buffer that are still available once we leave the delimited block.
+ /// </summary>
+ internal int bufferSizeAfterLimit;
+
+ /// <summary>
+ /// The absolute position of the end of the current length-delimited block (including totalBytesRetired)
+ /// </summary>
+ internal int currentLimit;
+
+ /// <summary>
+ /// The total number of consumed before the start of the current buffer. The
+ /// total bytes read up to the current position can be computed as
+ /// totalBytesRetired + bufferPos.
+ /// </summary>
+ internal int totalBytesRetired;
+
+ internal int recursionDepth; // current recursion depth
+
+ internal SegmentedBufferHelper segmentedBufferHelper;
+
+ /// <summary>
+ /// The last tag we read. 0 indicates we've read to the end of the stream
+ /// (or haven't read anything yet).
+ /// </summary>
+ internal uint lastTag;
+
+ /// <summary>
+ /// The next tag, used to store the value read by PeekTag.
+ /// </summary>
+ internal uint nextTag;
+ internal bool hasNextTag;
+
+ // these fields are configuration, they should be readonly
+ internal int sizeLimit;
+ internal int recursionLimit;
+
+ // If non-null, the top level parse method was started with given coded input stream as an argument
+ // which also means we can potentially fallback to calling MergeFrom(CodedInputStream cis) if needed.
+ internal CodedInputStream CodedInputStream => segmentedBufferHelper.CodedInputStream;
+
+ /// <summary>
+ /// Internal-only property; when set to true, unknown fields will be discarded while parsing.
+ /// </summary>
+ internal bool DiscardUnknownFields { get; set; }
+
+ /// <summary>
+ /// Internal-only property; provides extension identifiers to compatible messages while parsing.
+ /// </summary>
+ internal ExtensionRegistry ExtensionRegistry { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/ParsingPrimitives.cs b/csharp/src/Google.Protobuf/ParsingPrimitives.cs
new file mode 100644
index 0000000..28a1949
--- /dev/null
+++ b/csharp/src/Google.Protobuf/ParsingPrimitives.cs
@@ -0,0 +1,735 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+using Google.Protobuf.Collections;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Primitives for parsing protobuf wire format.
+ /// </summary>
+ [SecuritySafeCritical]
+ internal static class ParsingPrimitives
+ {
+
+ /// <summary>
+ /// Reads a length for length-delimited data.
+ /// </summary>
+ /// <remarks>
+ /// This is internally just reading a varint, but this method exists
+ /// to make the calling code clearer.
+ /// </remarks>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+
+ public static int ParseLength(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ return (int)ParseRawVarint32(ref buffer, ref state);
+ }
+
+ /// <summary>
+ /// Parses the next tag.
+ /// If the end of logical stream was reached, an invalid tag of 0 is returned.
+ /// </summary>
+ public static uint ParseTag(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ // The "nextTag" logic is there only as an optimization for reading non-packed repeated / map
+ // fields and is strictly speaking not necessary.
+ // TODO(jtattermusch): look into simplifying the ParseTag logic.
+ if (state.hasNextTag)
+ {
+ state.lastTag = state.nextTag;
+ state.hasNextTag = false;
+ return state.lastTag;
+ }
+
+ // Optimize for the incredibly common case of having at least two bytes left in the buffer,
+ // and those two bytes being enough to get the tag. This will be true for fields up to 4095.
+ if (state.bufferPos + 2 <= state.bufferSize)
+ {
+ int tmp = buffer[state.bufferPos++];
+ if (tmp < 128)
+ {
+ state.lastTag = (uint)tmp;
+ }
+ else
+ {
+ int result = tmp & 0x7f;
+ if ((tmp = buffer[state.bufferPos++]) < 128)
+ {
+ result |= tmp << 7;
+ state.lastTag = (uint) result;
+ }
+ else
+ {
+ // Nope, rewind and go the potentially slow route.
+ state.bufferPos -= 2;
+ state.lastTag = ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ }
+ }
+ }
+ else
+ {
+ if (SegmentedBufferHelper.IsAtEnd(ref buffer, ref state))
+ {
+ state.lastTag = 0;
+ return 0;
+ }
+
+ state.lastTag = ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ }
+ if (WireFormat.GetTagFieldNumber(state.lastTag) == 0)
+ {
+ // If we actually read a tag with a field of 0, that's not a valid tag.
+ throw InvalidProtocolBufferException.InvalidTag();
+ }
+ return state.lastTag;
+ }
+
+ /// <summary>
+ /// Peeks at the next tag in the stream. If it matches <paramref name="tag"/>,
+ /// the tag is consumed and the method returns <c>true</c>; otherwise, the
+ /// stream is left in the original position and the method returns <c>false</c>.
+ /// </summary>
+ public static bool MaybeConsumeTag(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, uint tag)
+ {
+ if (PeekTag(ref buffer, ref state) == tag)
+ {
+ state.hasNextTag = false;
+ return true;
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// Peeks at the next field tag. This is like calling <see cref="ParseTag"/>, but the
+ /// tag is not consumed. (So a subsequent call to <see cref="ParseTag"/> will return the
+ /// same value.)
+ /// </summary>
+ public static uint PeekTag(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ if (state.hasNextTag)
+ {
+ return state.nextTag;
+ }
+
+ uint savedLast = state.lastTag;
+ state.nextTag = ParseTag(ref buffer, ref state);
+ state.hasNextTag = true;
+ state.lastTag = savedLast; // Undo the side effect of ReadTag
+ return state.nextTag;
+ }
+
+ /// <summary>
+ /// Parses a raw varint.
+ /// </summary>
+ public static ulong ParseRawVarint64(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ if (state.bufferPos + 10 > state.bufferSize)
+ {
+ return ParseRawVarint64SlowPath(ref buffer, ref state);
+ }
+
+ ulong result = buffer[state.bufferPos++];
+ if (result < 128)
+ {
+ return result;
+ }
+ result &= 0x7f;
+ int shift = 7;
+ do
+ {
+ byte b = buffer[state.bufferPos++];
+ result |= (ulong)(b & 0x7F) << shift;
+ if (b < 0x80)
+ {
+ return result;
+ }
+ shift += 7;
+ }
+ while (shift < 64);
+
+ throw InvalidProtocolBufferException.MalformedVarint();
+ }
+
+ private static ulong ParseRawVarint64SlowPath(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ int shift = 0;
+ ulong result = 0;
+ do
+ {
+ byte b = ReadRawByte(ref buffer, ref state);
+ result |= (ulong)(b & 0x7F) << shift;
+ if (b < 0x80)
+ {
+ return result;
+ }
+ shift += 7;
+ }
+ while (shift < 64);
+
+ throw InvalidProtocolBufferException.MalformedVarint();
+ }
+
+ /// <summary>
+ /// Parses a raw Varint. If larger than 32 bits, discard the upper bits.
+ /// This method is optimised for the case where we've got lots of data in the buffer.
+ /// That means we can check the size just once, then just read directly from the buffer
+ /// without constant rechecking of the buffer length.
+ /// </summary>
+ public static uint ParseRawVarint32(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ if (state.bufferPos + 5 > state.bufferSize)
+ {
+ return ParseRawVarint32SlowPath(ref buffer, ref state);
+ }
+
+ int tmp = buffer[state.bufferPos++];
+ if (tmp < 128)
+ {
+ return (uint)tmp;
+ }
+ int result = tmp & 0x7f;
+ if ((tmp = buffer[state.bufferPos++]) < 128)
+ {
+ result |= tmp << 7;
+ }
+ else
+ {
+ result |= (tmp & 0x7f) << 7;
+ if ((tmp = buffer[state.bufferPos++]) < 128)
+ {
+ result |= tmp << 14;
+ }
+ else
+ {
+ result |= (tmp & 0x7f) << 14;
+ if ((tmp = buffer[state.bufferPos++]) < 128)
+ {
+ result |= tmp << 21;
+ }
+ else
+ {
+ result |= (tmp & 0x7f) << 21;
+ result |= (tmp = buffer[state.bufferPos++]) << 28;
+ if (tmp >= 128)
+ {
+ // Discard upper 32 bits.
+ // Note that this has to use ReadRawByte() as we only ensure we've
+ // got at least 5 bytes at the start of the method. This lets us
+ // use the fast path in more cases, and we rarely hit this section of code.
+ for (int i = 0; i < 5; i++)
+ {
+ if (ReadRawByte(ref buffer, ref state) < 128)
+ {
+ return (uint) result;
+ }
+ }
+ throw InvalidProtocolBufferException.MalformedVarint();
+ }
+ }
+ }
+ }
+ return (uint)result;
+ }
+
+ private static uint ParseRawVarint32SlowPath(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ int tmp = ReadRawByte(ref buffer, ref state);
+ if (tmp < 128)
+ {
+ return (uint) tmp;
+ }
+ int result = tmp & 0x7f;
+ if ((tmp = ReadRawByte(ref buffer, ref state)) < 128)
+ {
+ result |= tmp << 7;
+ }
+ else
+ {
+ result |= (tmp & 0x7f) << 7;
+ if ((tmp = ReadRawByte(ref buffer, ref state)) < 128)
+ {
+ result |= tmp << 14;
+ }
+ else
+ {
+ result |= (tmp & 0x7f) << 14;
+ if ((tmp = ReadRawByte(ref buffer, ref state)) < 128)
+ {
+ result |= tmp << 21;
+ }
+ else
+ {
+ result |= (tmp & 0x7f) << 21;
+ result |= (tmp = ReadRawByte(ref buffer, ref state)) << 28;
+ if (tmp >= 128)
+ {
+ // Discard upper 32 bits.
+ for (int i = 0; i < 5; i++)
+ {
+ if (ReadRawByte(ref buffer, ref state) < 128)
+ {
+ return (uint) result;
+ }
+ }
+ throw InvalidProtocolBufferException.MalformedVarint();
+ }
+ }
+ }
+ }
+ return (uint) result;
+ }
+
+ /// <summary>
+ /// Parses a 32-bit little-endian integer.
+ /// </summary>
+ public static uint ParseRawLittleEndian32(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ const int uintLength = sizeof(uint);
+ const int ulongLength = sizeof(ulong);
+ if (state.bufferPos + ulongLength > state.bufferSize)
+ {
+ return ParseRawLittleEndian32SlowPath(ref buffer, ref state);
+ }
+ // ReadUInt32LittleEndian is many times slower than ReadUInt64LittleEndian (at least on some runtimes)
+ // so it's faster better to use ReadUInt64LittleEndian and truncate the result.
+ uint result = (uint) BinaryPrimitives.ReadUInt64LittleEndian(buffer.Slice(state.bufferPos, ulongLength));
+ state.bufferPos += uintLength;
+ return result;
+ }
+
+ private static uint ParseRawLittleEndian32SlowPath(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ uint b1 = ReadRawByte(ref buffer, ref state);
+ uint b2 = ReadRawByte(ref buffer, ref state);
+ uint b3 = ReadRawByte(ref buffer, ref state);
+ uint b4 = ReadRawByte(ref buffer, ref state);
+ return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
+ }
+
+ /// <summary>
+ /// Parses a 64-bit little-endian integer.
+ /// </summary>
+ public static ulong ParseRawLittleEndian64(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ const int length = sizeof(ulong);
+ if (state.bufferPos + length > state.bufferSize)
+ {
+ return ParseRawLittleEndian64SlowPath(ref buffer, ref state);
+ }
+ ulong result = BinaryPrimitives.ReadUInt64LittleEndian(buffer.Slice(state.bufferPos, length));
+ state.bufferPos += length;
+ return result;
+ }
+
+ private static ulong ParseRawLittleEndian64SlowPath(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ ulong b1 = ReadRawByte(ref buffer, ref state);
+ ulong b2 = ReadRawByte(ref buffer, ref state);
+ ulong b3 = ReadRawByte(ref buffer, ref state);
+ ulong b4 = ReadRawByte(ref buffer, ref state);
+ ulong b5 = ReadRawByte(ref buffer, ref state);
+ ulong b6 = ReadRawByte(ref buffer, ref state);
+ ulong b7 = ReadRawByte(ref buffer, ref state);
+ ulong b8 = ReadRawByte(ref buffer, ref state);
+ return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)
+ | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
+ }
+
+ /// <summary>
+ /// Parses a double value.
+ /// </summary>
+ public static double ParseDouble(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ const int length = sizeof(double);
+ if (!BitConverter.IsLittleEndian || state.bufferPos + length > state.bufferSize)
+ {
+ return BitConverter.Int64BitsToDouble((long)ParseRawLittleEndian64(ref buffer, ref state));
+ }
+ // ReadUnaligned uses processor architecture for endianness.
+ double result = Unsafe.ReadUnaligned<double>(ref MemoryMarshal.GetReference(buffer.Slice(state.bufferPos, length)));
+ state.bufferPos += length;
+ return result;
+ }
+
+ /// <summary>
+ /// Parses a float value.
+ /// </summary>
+ public static float ParseFloat(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ const int length = sizeof(float);
+ if (!BitConverter.IsLittleEndian || state.bufferPos + length > state.bufferSize)
+ {
+ return ParseFloatSlow(ref buffer, ref state);
+ }
+ // ReadUnaligned uses processor architecture for endianness.
+ float result = Unsafe.ReadUnaligned<float>(ref MemoryMarshal.GetReference(buffer.Slice(state.bufferPos, length)));
+ state.bufferPos += length;
+ return result;
+ }
+
+ private static unsafe float ParseFloatSlow(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ const int length = sizeof(float);
+ byte* stackBuffer = stackalloc byte[length];
+ Span<byte> tempSpan = new Span<byte>(stackBuffer, length);
+ for (int i = 0; i < length; i++)
+ {
+ tempSpan[i] = ReadRawByte(ref buffer, ref state);
+ }
+
+ // Content is little endian. Reverse if needed to match endianness of architecture.
+ if (!BitConverter.IsLittleEndian)
+ {
+ tempSpan.Reverse();
+ }
+ return Unsafe.ReadUnaligned<float>(ref MemoryMarshal.GetReference(tempSpan));
+ }
+
+ /// <summary>
+ /// Reads a fixed size of bytes from the input.
+ /// </summary>
+ /// <exception cref="InvalidProtocolBufferException">
+ /// the end of the stream or the current limit was reached
+ /// </exception>
+ public static byte[] ReadRawBytes(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, int size)
+ {
+ if (size < 0)
+ {
+ throw InvalidProtocolBufferException.NegativeSize();
+ }
+
+ if (state.totalBytesRetired + state.bufferPos + size > state.currentLimit)
+ {
+ // Read to the end of the stream (up to the current limit) anyway.
+ SkipRawBytes(ref buffer, ref state, state.currentLimit - state.totalBytesRetired - state.bufferPos);
+ // Then fail.
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+
+ if (size <= state.bufferSize - state.bufferPos)
+ {
+ // We have all the bytes we need already.
+ byte[] bytes = new byte[size];
+ buffer.Slice(state.bufferPos, size).CopyTo(bytes);
+ state.bufferPos += size;
+ return bytes;
+ }
+ else if (size < buffer.Length || size < state.segmentedBufferHelper.TotalLength)
+ {
+ // Reading more bytes than are in the buffer, but not an excessive number
+ // of bytes. We can safely allocate the resulting array ahead of time.
+
+ // First copy what we have.
+ byte[] bytes = new byte[size];
+ var bytesSpan = new Span<byte>(bytes);
+ int pos = state.bufferSize - state.bufferPos;
+ buffer.Slice(state.bufferPos, pos).CopyTo(bytesSpan.Slice(0, pos));
+ state.bufferPos = state.bufferSize;
+
+ // We want to use RefillBuffer() and then copy from the buffer into our
+ // byte array rather than reading directly into our byte array because
+ // the input may be unbuffered.
+ state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, true);
+
+ while (size - pos > state.bufferSize)
+ {
+ buffer.Slice(0, state.bufferSize)
+ .CopyTo(bytesSpan.Slice(pos, state.bufferSize));
+ pos += state.bufferSize;
+ state.bufferPos = state.bufferSize;
+ state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, true);
+ }
+
+ buffer.Slice(0, size - pos)
+ .CopyTo(bytesSpan.Slice(pos, size - pos));
+ state.bufferPos = size - pos;
+
+ return bytes;
+ }
+ else
+ {
+ // 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.
+
+ List<byte[]> chunks = new List<byte[]>();
+
+ int pos = state.bufferSize - state.bufferPos;
+ byte[] firstChunk = new byte[pos];
+ buffer.Slice(state.bufferPos, pos).CopyTo(firstChunk);
+ chunks.Add(firstChunk);
+ state.bufferPos = state.bufferSize;
+
+ // Read all the rest of the bytes we need.
+ int sizeLeft = size - pos;
+ while (sizeLeft > 0)
+ {
+ state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, true);
+ byte[] chunk = new byte[Math.Min(sizeLeft, state.bufferSize)];
+
+ buffer.Slice(0, chunk.Length)
+ .CopyTo(chunk);
+ state.bufferPos += chunk.Length;
+ sizeLeft -= chunk.Length;
+ chunks.Add(chunk);
+ }
+
+ // OK, got everything. Now concatenate it all into one buffer.
+ byte[] bytes = new byte[size];
+ int newPos = 0;
+ foreach (byte[] chunk in chunks)
+ {
+ Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length);
+ newPos += chunk.Length;
+ }
+
+ // Done.
+ return bytes;
+ }
+ }
+
+ /// <summary>
+ /// Reads and discards <paramref name="size"/> bytes.
+ /// </summary>
+ /// <exception cref="InvalidProtocolBufferException">the end of the stream
+ /// or the current limit was reached</exception>
+ public static void SkipRawBytes(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, int size)
+ {
+ if (size < 0)
+ {
+ throw InvalidProtocolBufferException.NegativeSize();
+ }
+
+ if (state.totalBytesRetired + state.bufferPos + size > state.currentLimit)
+ {
+ // Read to the end of the stream anyway.
+ SkipRawBytes(ref buffer, ref state, state.currentLimit - state.totalBytesRetired - state.bufferPos);
+ // Then fail.
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+
+ if (size <= state.bufferSize - state.bufferPos)
+ {
+ // We have all the bytes we need already.
+ state.bufferPos += size;
+ }
+ else
+ {
+ // Skipping more bytes than are in the buffer. First skip what we have.
+ int pos = state.bufferSize - state.bufferPos;
+ state.bufferPos = state.bufferSize;
+
+ // TODO: If our segmented buffer is backed by a Stream that is seekable, we could skip the bytes more efficiently
+ // by simply updating stream's Position property. This used to be supported in the past, but the support was dropped
+ // because it would make the segmentedBufferHelper more complex. Support can be reintroduced if needed.
+ state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, true);
+
+ while (size - pos > state.bufferSize)
+ {
+ pos += state.bufferSize;
+ state.bufferPos = state.bufferSize;
+ state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, true);
+ }
+
+ state.bufferPos = size - pos;
+ }
+ }
+
+ /// <summary>
+ /// Reads a string field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static string ReadString(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
+ return ParsingPrimitives.ReadRawString(ref buffer, ref state, length);
+ }
+
+ /// <summary>
+ /// Reads a bytes field value from the input.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static ByteString ReadBytes(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
+ return ByteString.AttachBytes(ParsingPrimitives.ReadRawBytes(ref buffer, ref state, length));
+ }
+
+ /// <summary>
+ /// Reads a UTF-8 string from the next "length" bytes.
+ /// </summary>
+ /// <exception cref="InvalidProtocolBufferException">
+ /// the end of the stream or the current limit was reached
+ /// </exception>
+ [SecuritySafeCritical]
+ public static string ReadRawString(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, int length)
+ {
+ // No need to read any data for an empty string.
+ if (length == 0)
+ {
+ return string.Empty;
+ }
+
+ if (length < 0)
+ {
+ throw InvalidProtocolBufferException.NegativeSize();
+ }
+
+#if GOOGLE_PROTOBUF_SUPPORT_FAST_STRING
+ if (length <= state.bufferSize - state.bufferPos && length > 0)
+ {
+ // Fast path: all bytes to decode appear in the same span.
+ ReadOnlySpan<byte> data = buffer.Slice(state.bufferPos, length);
+
+ string value;
+ unsafe
+ {
+ fixed (byte* sourceBytes = &MemoryMarshal.GetReference(data))
+ {
+ value = CodedOutputStream.Utf8Encoding.GetString(sourceBytes, length);
+ }
+ }
+
+ state.bufferPos += length;
+ return value;
+ }
+#endif
+
+ var decoder = CodedOutputStream.Utf8Encoding.GetDecoder();
+
+ // TODO: even if GOOGLE_PROTOBUF_SUPPORT_FAST_STRING is not supported,
+ // we could still create a string efficiently by using Utf8Encoding.GetString(byte[] bytes, int index, int count)
+ // whenever the buffer is backed by a byte array (and avoid creating a new byte array), but the problem is
+ // there is no way to get the underlying byte array from a span.
+
+ // TODO: in case the string spans multiple buffer segments, creating a char[] and decoding into it and then
+ // creating a string from that array might be more efficient than creating a string from the copied bytes.
+
+ // Slow path: Build a byte array first then copy it.
+ return CodedOutputStream.Utf8Encoding.GetString(ReadRawBytes(ref buffer, ref state, length), 0, length);
+ }
+
+ [SecuritySafeCritical]
+ private static byte ReadRawByte(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ if (state.bufferPos == state.bufferSize)
+ {
+ state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, true);
+ }
+ return buffer[state.bufferPos++];
+ }
+
+ /// <summary>
+ /// 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 ReadRawVarint32(Stream)
+ /// then you would probably end up reading past the end of the varint since
+ /// CodedInputStream buffers its input.
+ /// </summary>
+ /// <param name="input"></param>
+ /// <returns></returns>
+ public static uint ReadRawVarint32(Stream input)
+ {
+ int result = 0;
+ int offset = 0;
+ for (; offset < 32; offset += 7)
+ {
+ int b = input.ReadByte();
+ if (b == -1)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ result |= (b & 0x7f) << offset;
+ if ((b & 0x80) == 0)
+ {
+ return (uint) result;
+ }
+ }
+ // Keep reading up to 64 bits.
+ for (; offset < 64; offset += 7)
+ {
+ int b = input.ReadByte();
+ if (b == -1)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ if ((b & 0x80) == 0)
+ {
+ return (uint) result;
+ }
+ }
+ throw InvalidProtocolBufferException.MalformedVarint();
+ }
+
+ /// <summary>
+ /// Decode a 32-bit value with ZigZag encoding.
+ /// </summary>
+ /// <remarks>
+ /// ZigZag encodes signed integers into values that can be efficiently
+ /// encoded with varint. (Otherwise, negative values must be
+ /// sign-extended to 32 bits to be varint encoded, thus always taking
+ /// 5 bytes on the wire.)
+ /// </remarks>
+ public static int DecodeZigZag32(uint n)
+ {
+ return (int)(n >> 1) ^ -(int)(n & 1);
+ }
+
+ /// <summary>
+ /// Decode a 64-bit value with ZigZag encoding.
+ /// </summary>
+ /// <remarks>
+ /// 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.)
+ /// </remarks>
+ public static long DecodeZigZag64(ulong n)
+ {
+ return (long)(n >> 1) ^ -(long)(n & 1);
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/ParsingPrimitivesMessages.cs b/csharp/src/Google.Protobuf/ParsingPrimitivesMessages.cs
new file mode 100644
index 0000000..b7097a2
--- /dev/null
+++ b/csharp/src/Google.Protobuf/ParsingPrimitivesMessages.cs
@@ -0,0 +1,229 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Buffers;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Security;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Reading and skipping messages / groups
+ /// </summary>
+ [SecuritySafeCritical]
+ internal static class ParsingPrimitivesMessages
+ {
+ public static void SkipLastField(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ if (state.lastTag == 0)
+ {
+ throw new InvalidOperationException("SkipLastField cannot be called at the end of a stream");
+ }
+ switch (WireFormat.GetTagWireType(state.lastTag))
+ {
+ case WireFormat.WireType.StartGroup:
+ SkipGroup(ref buffer, ref state, state.lastTag);
+ break;
+ case WireFormat.WireType.EndGroup:
+ throw new InvalidProtocolBufferException(
+ "SkipLastField called on an end-group tag, indicating that the corresponding start-group was missing");
+ case WireFormat.WireType.Fixed32:
+ ParsingPrimitives.ParseRawLittleEndian32(ref buffer, ref state);
+ break;
+ case WireFormat.WireType.Fixed64:
+ ParsingPrimitives.ParseRawLittleEndian64(ref buffer, ref state);
+ break;
+ case WireFormat.WireType.LengthDelimited:
+ var length = ParsingPrimitives.ParseLength(ref buffer, ref state);
+ ParsingPrimitives.SkipRawBytes(ref buffer, ref state, length);
+ break;
+ case WireFormat.WireType.Varint:
+ ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ break;
+ }
+ }
+
+ /// <summary>
+ /// Skip a group.
+ /// </summary>
+ public static void SkipGroup(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, uint startGroupTag)
+ {
+ // Note: Currently we expect this to be the way that groups are read. We could put the recursion
+ // depth changes into the ReadTag method instead, potentially...
+ state.recursionDepth++;
+ if (state.recursionDepth >= state.recursionLimit)
+ {
+ throw InvalidProtocolBufferException.RecursionLimitExceeded();
+ }
+ uint tag;
+ while (true)
+ {
+ tag = ParsingPrimitives.ParseTag(ref buffer, ref state);
+ if (tag == 0)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ // Can't call SkipLastField for this case- that would throw.
+ if (WireFormat.GetTagWireType(tag) == WireFormat.WireType.EndGroup)
+ {
+ break;
+ }
+ // This recursion will allow us to handle nested groups.
+ SkipLastField(ref buffer, ref state);
+ }
+ int startField = WireFormat.GetTagFieldNumber(startGroupTag);
+ int endField = WireFormat.GetTagFieldNumber(tag);
+ if (startField != endField)
+ {
+ throw new InvalidProtocolBufferException(
+ $"Mismatched end-group tag. Started with field {startField}; ended with field {endField}");
+ }
+ state.recursionDepth--;
+ }
+
+ public static void ReadMessage(ref ParseContext ctx, IMessage message)
+ {
+ int length = ParsingPrimitives.ParseLength(ref ctx.buffer, ref ctx.state);
+ if (ctx.state.recursionDepth >= ctx.state.recursionLimit)
+ {
+ throw InvalidProtocolBufferException.RecursionLimitExceeded();
+ }
+ int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length);
+ ++ctx.state.recursionDepth;
+
+ ReadRawMessage(ref ctx, message);
+
+ CheckReadEndOfStreamTag(ref ctx.state);
+ // Check that we've read exactly as much data as expected.
+ if (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state))
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ --ctx.state.recursionDepth;
+ SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit);
+ }
+
+ public static void ReadGroup(ref ParseContext ctx, IMessage message)
+ {
+ if (ctx.state.recursionDepth >= ctx.state.recursionLimit)
+ {
+ throw InvalidProtocolBufferException.RecursionLimitExceeded();
+ }
+ ++ctx.state.recursionDepth;
+
+ uint tag = ctx.state.lastTag;
+ int fieldNumber = WireFormat.GetTagFieldNumber(tag);
+ ReadRawMessage(ref ctx, message);
+ CheckLastTagWas(ref ctx.state, WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup));
+
+ --ctx.state.recursionDepth;
+ }
+
+ public static void ReadGroup(ref ParseContext ctx, int fieldNumber, UnknownFieldSet set)
+ {
+ if (ctx.state.recursionDepth >= ctx.state.recursionLimit)
+ {
+ throw InvalidProtocolBufferException.RecursionLimitExceeded();
+ }
+ ++ctx.state.recursionDepth;
+
+ set.MergeGroupFrom(ref ctx);
+ CheckLastTagWas(ref ctx.state, WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup));
+
+ --ctx.state.recursionDepth;
+ }
+
+ public static void ReadRawMessage(ref ParseContext ctx, IMessage message)
+ {
+ if (message is IBufferMessage bufferMessage)
+ {
+ bufferMessage.InternalMergeFrom(ref ctx);
+ }
+ else
+ {
+ // If we reached here, it means we've ran into a nested message with older generated code
+ // which doesn't provide the InternalMergeFrom method that takes a ParseContext.
+ // With a slight performance overhead, we can still parse this message just fine,
+ // but we need to find the original CodedInputStream instance that initiated this
+ // parsing process and make sure its internal state is up to date.
+ // Note that this performance overhead is not very high (basically copying contents of a struct)
+ // and it will only be incurred in case the application mixes older and newer generated code.
+ // Regenerating the code from .proto files will remove this overhead because it will
+ // generate the InternalMergeFrom method we need.
+
+ if (ctx.state.CodedInputStream == null)
+ {
+ // This can only happen when the parsing started without providing a CodedInputStream instance
+ // (e.g. ParseContext was created directly from a ReadOnlySequence).
+ // That also means that one of the new parsing APIs was used at the top level
+ // and in such case it is reasonable to require that all the nested message provide
+ // up-to-date generated code with ParseContext support (and fail otherwise).
+ throw new InvalidProtocolBufferException($"Message {message.GetType().Name} doesn't provide the generated method that enables ParseContext-based parsing. You might need to regenerate the generated protobuf code.");
+ }
+
+ ctx.CopyStateTo(ctx.state.CodedInputStream);
+ try
+ {
+ // fallback parse using the CodedInputStream that started current parsing tree
+ message.MergeFrom(ctx.state.CodedInputStream);
+ }
+ finally
+ {
+ ctx.LoadStateFrom(ctx.state.CodedInputStream);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Verifies that the last call to ReadTag() returned tag 0 - in other words,
+ /// we've reached the end of the stream when we expected to.
+ /// </summary>
+ /// <exception cref="InvalidProtocolBufferException">The
+ /// tag read was not the one specified</exception>
+ public static void CheckReadEndOfStreamTag(ref ParserInternalState state)
+ {
+ if (state.lastTag != 0)
+ {
+ throw InvalidProtocolBufferException.MoreDataAvailable();
+ }
+ }
+
+ private static void CheckLastTagWas(ref ParserInternalState state, uint expectedTag)
+ {
+ if (state.lastTag != expectedTag) {
+ throw InvalidProtocolBufferException.InvalidEndTag();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/ParsingPrimitivesWrappers.cs b/csharp/src/Google.Protobuf/ParsingPrimitivesWrappers.cs
new file mode 100644
index 0000000..1263064
--- /dev/null
+++ b/csharp/src/Google.Protobuf/ParsingPrimitivesWrappers.cs
@@ -0,0 +1,353 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Buffers;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+using Google.Protobuf.Collections;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Fast parsing primitives for wrapper types
+ /// </summary>
+ [SecuritySafeCritical]
+ internal static class ParsingPrimitivesWrappers
+ {
+ internal static float? ReadFloatWrapperLittleEndian(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ // length:1 + tag:1 + value:4 = 6 bytes
+ if (state.bufferPos + 6 <= state.bufferSize)
+ {
+ // The entire wrapper message is already contained in `buffer`.
+ int length = buffer[state.bufferPos];
+ if (length == 0)
+ {
+ state.bufferPos++;
+ return 0F;
+ }
+ // tag:1 + value:4 = length of 5 bytes
+ // field=1, type=32-bit = tag of 13
+ if (length != 5 || buffer[state.bufferPos + 1] != 13)
+ {
+ return ReadFloatWrapperSlow(ref buffer, ref state);
+ }
+ state.bufferPos += 2;
+ return ParsingPrimitives.ParseFloat(ref buffer, ref state);
+ }
+ else
+ {
+ return ReadFloatWrapperSlow(ref buffer, ref state);
+ }
+ }
+
+ internal static float? ReadFloatWrapperSlow(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
+ if (length == 0)
+ {
+ return 0F;
+ }
+ int finalBufferPos = state.totalBytesRetired + state.bufferPos + length;
+ float result = 0F;
+ do
+ {
+ // field=1, type=32-bit = tag of 13
+ if (ParsingPrimitives.ParseTag(ref buffer, ref state) == 13)
+ {
+ result = ParsingPrimitives.ParseFloat(ref buffer, ref state);
+ }
+ else
+ {
+ ParsingPrimitivesMessages.SkipLastField(ref buffer, ref state);
+ }
+ }
+ while (state.totalBytesRetired + state.bufferPos < finalBufferPos);
+ return result;
+ }
+
+ internal static double? ReadDoubleWrapperLittleEndian(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ // length:1 + tag:1 + value:8 = 10 bytes
+ if (state.bufferPos + 10 <= state.bufferSize)
+ {
+ // The entire wrapper message is already contained in `buffer`.
+ int length = buffer[state.bufferPos];
+ if (length == 0)
+ {
+ state.bufferPos++;
+ return 0D;
+ }
+ // tag:1 + value:8 = length of 9 bytes
+ // field=1, type=64-bit = tag of 9
+ if (length != 9 || buffer[state.bufferPos + 1] != 9)
+ {
+ return ReadDoubleWrapperSlow(ref buffer, ref state);
+ }
+ state.bufferPos += 2;
+ return ParsingPrimitives.ParseDouble(ref buffer, ref state);
+ }
+ else
+ {
+ return ReadDoubleWrapperSlow(ref buffer, ref state);
+ }
+ }
+
+ internal static double? ReadDoubleWrapperSlow(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
+ if (length == 0)
+ {
+ return 0D;
+ }
+ int finalBufferPos = state.totalBytesRetired + state.bufferPos + length;
+ double result = 0D;
+ do
+ {
+ // field=1, type=64-bit = tag of 9
+ if (ParsingPrimitives.ParseTag(ref buffer, ref state) == 9)
+ {
+ result = ParsingPrimitives.ParseDouble(ref buffer, ref state);
+ }
+ else
+ {
+ ParsingPrimitivesMessages.SkipLastField(ref buffer, ref state);
+ }
+ }
+ while (state.totalBytesRetired + state.bufferPos < finalBufferPos);
+ return result;
+ }
+
+ internal static bool? ReadBoolWrapper(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ return ReadUInt64Wrapper(ref buffer, ref state) != 0;
+ }
+
+ internal static uint? ReadUInt32Wrapper(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ // length:1 + tag:1 + value:5(varint32-max) = 7 bytes
+ if (state.bufferPos + 7 <= state.bufferSize)
+ {
+ // The entire wrapper message is already contained in `buffer`.
+ int pos0 = state.bufferPos;
+ int length = buffer[state.bufferPos++];
+ if (length == 0)
+ {
+ return 0;
+ }
+ // Length will always fit in a single byte.
+ if (length >= 128)
+ {
+ state.bufferPos = pos0;
+ return ReadUInt32WrapperSlow(ref buffer, ref state);
+ }
+ int finalBufferPos = state.bufferPos + length;
+ // field=1, type=varint = tag of 8
+ if (buffer[state.bufferPos++] != 8)
+ {
+ state.bufferPos = pos0;
+ return ReadUInt32WrapperSlow(ref buffer, ref state);
+ }
+ var result = ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ // Verify this message only contained a single field.
+ if (state.bufferPos != finalBufferPos)
+ {
+ state.bufferPos = pos0;
+ return ReadUInt32WrapperSlow(ref buffer, ref state);
+ }
+ return result;
+ }
+ else
+ {
+ return ReadUInt32WrapperSlow(ref buffer, ref state);
+ }
+ }
+
+ internal static uint? ReadUInt32WrapperSlow(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
+ if (length == 0)
+ {
+ return 0;
+ }
+ int finalBufferPos = state.totalBytesRetired + state.bufferPos + length;
+ uint result = 0;
+ do
+ {
+ // field=1, type=varint = tag of 8
+ if (ParsingPrimitives.ParseTag(ref buffer, ref state) == 8)
+ {
+ result = ParsingPrimitives.ParseRawVarint32(ref buffer, ref state);
+ }
+ else
+ {
+ ParsingPrimitivesMessages.SkipLastField(ref buffer, ref state);
+ }
+ }
+ while (state.totalBytesRetired + state.bufferPos < finalBufferPos);
+ return result;
+ }
+
+ internal static int? ReadInt32Wrapper(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ return (int?)ReadUInt32Wrapper(ref buffer, ref state);
+ }
+
+ internal static ulong? ReadUInt64Wrapper(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ // field=1, type=varint = tag of 8
+ const int expectedTag = 8;
+ // length:1 + tag:1 + value:10(varint64-max) = 12 bytes
+ if (state.bufferPos + 12 <= state.bufferSize)
+ {
+ // The entire wrapper message is already contained in `buffer`.
+ int pos0 = state.bufferPos;
+ int length = buffer[state.bufferPos++];
+ if (length == 0)
+ {
+ return 0L;
+ }
+ // Length will always fit in a single byte.
+ if (length >= 128)
+ {
+ state.bufferPos = pos0;
+ return ReadUInt64WrapperSlow(ref buffer, ref state);
+ }
+ int finalBufferPos = state.bufferPos + length;
+ if (buffer[state.bufferPos++] != expectedTag)
+ {
+ state.bufferPos = pos0;
+ return ReadUInt64WrapperSlow(ref buffer, ref state);
+ }
+ var result = ParsingPrimitives.ParseRawVarint64(ref buffer, ref state);
+ // Verify this message only contained a single field.
+ if (state.bufferPos != finalBufferPos)
+ {
+ state.bufferPos = pos0;
+ return ReadUInt64WrapperSlow(ref buffer, ref state);
+ }
+ return result;
+ }
+ else
+ {
+ return ReadUInt64WrapperSlow(ref buffer, ref state);
+ }
+ }
+
+ internal static ulong? ReadUInt64WrapperSlow(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ // field=1, type=varint = tag of 8
+ const int expectedTag = 8;
+ int length = ParsingPrimitives.ParseLength(ref buffer, ref state);
+ if (length == 0)
+ {
+ return 0L;
+ }
+ int finalBufferPos = state.totalBytesRetired + state.bufferPos + length;
+ ulong result = 0L;
+ do
+ {
+ if (ParsingPrimitives.ParseTag(ref buffer, ref state) == expectedTag)
+ {
+ result = ParsingPrimitives.ParseRawVarint64(ref buffer, ref state);
+ }
+ else
+ {
+ ParsingPrimitivesMessages.SkipLastField(ref buffer, ref state);
+ }
+ }
+ while (state.totalBytesRetired + state.bufferPos < finalBufferPos);
+ return result;
+ }
+
+ internal static long? ReadInt64Wrapper(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ return (long?)ReadUInt64Wrapper(ref buffer, ref state);
+ }
+
+ internal static float? ReadFloatWrapperLittleEndian(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadFloatWrapperLittleEndian(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static float? ReadFloatWrapperSlow(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadFloatWrapperSlow(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static double? ReadDoubleWrapperLittleEndian(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadDoubleWrapperLittleEndian(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static double? ReadDoubleWrapperSlow(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadDoubleWrapperSlow(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static bool? ReadBoolWrapper(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadBoolWrapper(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static uint? ReadUInt32Wrapper(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadUInt32Wrapper(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static int? ReadInt32Wrapper(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadInt32Wrapper(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static ulong? ReadUInt64Wrapper(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadUInt64Wrapper(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static ulong? ReadUInt64WrapperSlow(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadUInt64WrapperSlow(ref ctx.buffer, ref ctx.state);
+ }
+
+ internal static long? ReadInt64Wrapper(ref ParseContext ctx)
+ {
+ return ParsingPrimitivesWrappers.ReadInt64Wrapper(ref ctx.buffer, ref ctx.state);
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs b/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs
index 9b179bd..130bcf0 100644
--- a/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs
+++ b/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs
@@ -47,3 +47,10 @@
"981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" +
"b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" +
"c5ae9cb6")]
+
+[assembly: InternalsVisibleTo("Google.Protobuf.Benchmarks, PublicKey=" +
+ "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" +
+ "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" +
+ "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" +
+ "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" +
+ "c5ae9cb6")]
diff --git a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
index 59c2600..3c6e82b 100644
--- a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
@@ -54,7 +54,7 @@
"b2J1Zi5FeHRlbnNpb25SYW5nZU9wdGlvbnMaKwoNUmVzZXJ2ZWRSYW5nZRIN",
"CgVzdGFydBgBIAEoBRILCgNlbmQYAiABKAUiZwoVRXh0ZW5zaW9uUmFuZ2VP",
"cHRpb25zEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2ds",
- "ZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIivAUK",
+ "ZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi1QUK",
"FEZpZWxkRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSDgoGbnVtYmVy",
"GAMgASgFEjoKBWxhYmVsGAQgASgOMisuZ29vZ2xlLnByb3RvYnVmLkZpZWxk",
"RGVzY3JpcHRvclByb3RvLkxhYmVsEjgKBHR5cGUYBSABKA4yKi5nb29nbGUu",
@@ -62,102 +62,103 @@
"bWUYBiABKAkSEAoIZXh0ZW5kZWUYAiABKAkSFQoNZGVmYXVsdF92YWx1ZRgH",
"IAEoCRITCgtvbmVvZl9pbmRleBgJIAEoBRIRCglqc29uX25hbWUYCiABKAkS",
"LgoHb3B0aW9ucxgIIAEoCzIdLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlv",
- "bnMitgIKBFR5cGUSDwoLVFlQRV9ET1VCTEUQARIOCgpUWVBFX0ZMT0FUEAIS",
- "DgoKVFlQRV9JTlQ2NBADEg8KC1RZUEVfVUlOVDY0EAQSDgoKVFlQRV9JTlQz",
- "MhAFEhAKDFRZUEVfRklYRUQ2NBAGEhAKDFRZUEVfRklYRUQzMhAHEg0KCVRZ",
- "UEVfQk9PTBAIEg8KC1RZUEVfU1RSSU5HEAkSDgoKVFlQRV9HUk9VUBAKEhAK",
- "DFRZUEVfTUVTU0FHRRALEg4KClRZUEVfQllURVMQDBIPCgtUWVBFX1VJTlQz",
- "MhANEg0KCVRZUEVfRU5VTRAOEhEKDVRZUEVfU0ZJWEVEMzIQDxIRCg1UWVBF",
- "X1NGSVhFRDY0EBASDwoLVFlQRV9TSU5UMzIQERIPCgtUWVBFX1NJTlQ2NBAS",
- "IkMKBUxhYmVsEhIKDkxBQkVMX09QVElPTkFMEAESEgoOTEFCRUxfUkVRVUlS",
- "RUQQAhISCg5MQUJFTF9SRVBFQVRFRBADIlQKFE9uZW9mRGVzY3JpcHRvclBy",
- "b3RvEgwKBG5hbWUYASABKAkSLgoHb3B0aW9ucxgCIAEoCzIdLmdvb2dsZS5w",
- "cm90b2J1Zi5PbmVvZk9wdGlvbnMipAIKE0VudW1EZXNjcmlwdG9yUHJvdG8S",
- "DAoEbmFtZRgBIAEoCRI4CgV2YWx1ZRgCIAMoCzIpLmdvb2dsZS5wcm90b2J1",
- "Zi5FbnVtVmFsdWVEZXNjcmlwdG9yUHJvdG8SLQoHb3B0aW9ucxgDIAEoCzIc",
- "Lmdvb2dsZS5wcm90b2J1Zi5FbnVtT3B0aW9ucxJOCg5yZXNlcnZlZF9yYW5n",
- "ZRgEIAMoCzI2Lmdvb2dsZS5wcm90b2J1Zi5FbnVtRGVzY3JpcHRvclByb3Rv",
- "LkVudW1SZXNlcnZlZFJhbmdlEhUKDXJlc2VydmVkX25hbWUYBSADKAkaLwoR",
- "RW51bVJlc2VydmVkUmFuZ2USDQoFc3RhcnQYASABKAUSCwoDZW5kGAIgASgF",
- "ImwKGEVudW1WYWx1ZURlc2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJEg4K",
- "Bm51bWJlchgCIAEoBRIyCgdvcHRpb25zGAMgASgLMiEuZ29vZ2xlLnByb3Rv",
- "YnVmLkVudW1WYWx1ZU9wdGlvbnMikAEKFlNlcnZpY2VEZXNjcmlwdG9yUHJv",
- "dG8SDAoEbmFtZRgBIAEoCRI2CgZtZXRob2QYAiADKAsyJi5nb29nbGUucHJv",
- "dG9idWYuTWV0aG9kRGVzY3JpcHRvclByb3RvEjAKB29wdGlvbnMYAyABKAsy",
- "Hy5nb29nbGUucHJvdG9idWYuU2VydmljZU9wdGlvbnMiwQEKFU1ldGhvZERl",
- "c2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJEhIKCmlucHV0X3R5cGUYAiAB",
- "KAkSEwoLb3V0cHV0X3R5cGUYAyABKAkSLwoHb3B0aW9ucxgEIAEoCzIeLmdv",
- "b2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zEh8KEGNsaWVudF9zdHJlYW1p",
- "bmcYBSABKAg6BWZhbHNlEh8KEHNlcnZlcl9zdHJlYW1pbmcYBiABKAg6BWZh",
- "bHNlIqYGCgtGaWxlT3B0aW9ucxIUCgxqYXZhX3BhY2thZ2UYASABKAkSHAoU",
- "amF2YV9vdXRlcl9jbGFzc25hbWUYCCABKAkSIgoTamF2YV9tdWx0aXBsZV9m",
- "aWxlcxgKIAEoCDoFZmFsc2USKQodamF2YV9nZW5lcmF0ZV9lcXVhbHNfYW5k",
- "X2hhc2gYFCABKAhCAhgBEiUKFmphdmFfc3RyaW5nX2NoZWNrX3V0ZjgYGyAB",
- "KAg6BWZhbHNlEkYKDG9wdGltaXplX2ZvchgJIAEoDjIpLmdvb2dsZS5wcm90",
- "b2J1Zi5GaWxlT3B0aW9ucy5PcHRpbWl6ZU1vZGU6BVNQRUVEEhIKCmdvX3Bh",
- "Y2thZ2UYCyABKAkSIgoTY2NfZ2VuZXJpY19zZXJ2aWNlcxgQIAEoCDoFZmFs",
- "c2USJAoVamF2YV9nZW5lcmljX3NlcnZpY2VzGBEgASgIOgVmYWxzZRIiChNw",
- "eV9nZW5lcmljX3NlcnZpY2VzGBIgASgIOgVmYWxzZRIjChRwaHBfZ2VuZXJp",
- "Y19zZXJ2aWNlcxgqIAEoCDoFZmFsc2USGQoKZGVwcmVjYXRlZBgXIAEoCDoF",
- "ZmFsc2USHwoQY2NfZW5hYmxlX2FyZW5hcxgfIAEoCDoFZmFsc2USGQoRb2Jq",
- "Y19jbGFzc19wcmVmaXgYJCABKAkSGAoQY3NoYXJwX25hbWVzcGFjZRglIAEo",
- "CRIUCgxzd2lmdF9wcmVmaXgYJyABKAkSGAoQcGhwX2NsYXNzX3ByZWZpeBgo",
- "IAEoCRIVCg1waHBfbmFtZXNwYWNlGCkgASgJEh4KFnBocF9tZXRhZGF0YV9u",
- "YW1lc3BhY2UYLCABKAkSFAoMcnVieV9wYWNrYWdlGC0gASgJEkMKFHVuaW50",
- "ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5Vbmlu",
- "dGVycHJldGVkT3B0aW9uIjoKDE9wdGltaXplTW9kZRIJCgVTUEVFRBABEg0K",
- "CUNPREVfU0laRRACEhAKDExJVEVfUlVOVElNRRADKgkI6AcQgICAgAJKBAgm",
- "ECci8gEKDk1lc3NhZ2VPcHRpb25zEiYKF21lc3NhZ2Vfc2V0X3dpcmVfZm9y",
- "bWF0GAEgASgIOgVmYWxzZRIuCh9ub19zdGFuZGFyZF9kZXNjcmlwdG9yX2Fj",
- "Y2Vzc29yGAIgASgIOgVmYWxzZRIZCgpkZXByZWNhdGVkGAMgASgIOgVmYWxz",
- "ZRIRCgltYXBfZW50cnkYByABKAgSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y",
- "5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24q",
- "CQjoBxCAgICAAkoECAgQCUoECAkQCiKeAwoMRmllbGRPcHRpb25zEjoKBWN0",
- "eXBlGAEgASgOMiMuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlw",
- "ZToGU1RSSU5HEg4KBnBhY2tlZBgCIAEoCBI/CgZqc3R5cGUYBiABKA4yJC5n",
- "b29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zLkpTVHlwZToJSlNfTk9STUFM",
- "EhMKBGxhenkYBSABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZh",
- "bHNlEhMKBHdlYWsYCiABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0",
- "aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0",
- "aW9uIi8KBUNUeXBlEgoKBlNUUklORxAAEggKBENPUkQQARIQCgxTVFJJTkdf",
- "UElFQ0UQAiI1CgZKU1R5cGUSDQoJSlNfTk9STUFMEAASDQoJSlNfU1RSSU5H",
- "EAESDQoJSlNfTlVNQkVSEAIqCQjoBxCAgICAAkoECAQQBSJeCgxPbmVvZk9w",
- "dGlvbnMSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xl",
- "LnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoL",
- "RW51bU9wdGlvbnMSEwoLYWxsb3dfYWxpYXMYAiABKAgSGQoKZGVwcmVjYXRl",
- "ZBgDIAEoCDoFZmFsc2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygL",
- "MiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCA",
- "gICAAkoECAUQBiJ9ChBFbnVtVmFsdWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQY",
- "ASABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIk",
- "Lmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICA",
- "gAIiewoOU2VydmljZU9wdGlvbnMSGQoKZGVwcmVjYXRlZBghIAEoCDoFZmFs",
- "c2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnBy",
- "b3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKtAgoNTWV0",
- "aG9kT3B0aW9ucxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJfChFpZGVt",
- "cG90ZW5jeV9sZXZlbBgiIAEoDjIvLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RP",
- "cHRpb25zLklkZW1wb3RlbmN5TGV2ZWw6E0lERU1QT1RFTkNZX1VOS05PV04S",
+ "bnMSFwoPcHJvdG8zX29wdGlvbmFsGBEgASgIIrYCCgRUeXBlEg8KC1RZUEVf",
+ "RE9VQkxFEAESDgoKVFlQRV9GTE9BVBACEg4KClRZUEVfSU5UNjQQAxIPCgtU",
+ "WVBFX1VJTlQ2NBAEEg4KClRZUEVfSU5UMzIQBRIQCgxUWVBFX0ZJWEVENjQQ",
+ "BhIQCgxUWVBFX0ZJWEVEMzIQBxINCglUWVBFX0JPT0wQCBIPCgtUWVBFX1NU",
+ "UklORxAJEg4KClRZUEVfR1JPVVAQChIQCgxUWVBFX01FU1NBR0UQCxIOCgpU",
+ "WVBFX0JZVEVTEAwSDwoLVFlQRV9VSU5UMzIQDRINCglUWVBFX0VOVU0QDhIR",
+ "Cg1UWVBFX1NGSVhFRDMyEA8SEQoNVFlQRV9TRklYRUQ2NBAQEg8KC1RZUEVf",
+ "U0lOVDMyEBESDwoLVFlQRV9TSU5UNjQQEiJDCgVMYWJlbBISCg5MQUJFTF9P",
+ "UFRJT05BTBABEhIKDkxBQkVMX1JFUVVJUkVEEAISEgoOTEFCRUxfUkVQRUFU",
+ "RUQQAyJUChRPbmVvZkRlc2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJEi4K",
+ "B29wdGlvbnMYAiABKAsyHS5nb29nbGUucHJvdG9idWYuT25lb2ZPcHRpb25z",
+ "IqQCChNFbnVtRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSOAoFdmFs",
+ "dWUYAiADKAsyKS5nb29nbGUucHJvdG9idWYuRW51bVZhbHVlRGVzY3JpcHRv",
+ "clByb3RvEi0KB29wdGlvbnMYAyABKAsyHC5nb29nbGUucHJvdG9idWYuRW51",
+ "bU9wdGlvbnMSTgoOcmVzZXJ2ZWRfcmFuZ2UYBCADKAsyNi5nb29nbGUucHJv",
+ "dG9idWYuRW51bURlc2NyaXB0b3JQcm90by5FbnVtUmVzZXJ2ZWRSYW5nZRIV",
+ "Cg1yZXNlcnZlZF9uYW1lGAUgAygJGi8KEUVudW1SZXNlcnZlZFJhbmdlEg0K",
+ "BXN0YXJ0GAEgASgFEgsKA2VuZBgCIAEoBSJsChhFbnVtVmFsdWVEZXNjcmlw",
+ "dG9yUHJvdG8SDAoEbmFtZRgBIAEoCRIOCgZudW1iZXIYAiABKAUSMgoHb3B0",
+ "aW9ucxgDIAEoCzIhLmdvb2dsZS5wcm90b2J1Zi5FbnVtVmFsdWVPcHRpb25z",
+ "IpABChZTZXJ2aWNlRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSNgoG",
+ "bWV0aG9kGAIgAygLMiYuZ29vZ2xlLnByb3RvYnVmLk1ldGhvZERlc2NyaXB0",
+ "b3JQcm90bxIwCgdvcHRpb25zGAMgASgLMh8uZ29vZ2xlLnByb3RvYnVmLlNl",
+ "cnZpY2VPcHRpb25zIsEBChVNZXRob2REZXNjcmlwdG9yUHJvdG8SDAoEbmFt",
+ "ZRgBIAEoCRISCgppbnB1dF90eXBlGAIgASgJEhMKC291dHB1dF90eXBlGAMg",
+ "ASgJEi8KB29wdGlvbnMYBCABKAsyHi5nb29nbGUucHJvdG9idWYuTWV0aG9k",
+ "T3B0aW9ucxIfChBjbGllbnRfc3RyZWFtaW5nGAUgASgIOgVmYWxzZRIfChBz",
+ "ZXJ2ZXJfc3RyZWFtaW5nGAYgASgIOgVmYWxzZSKlBgoLRmlsZU9wdGlvbnMS",
+ "FAoMamF2YV9wYWNrYWdlGAEgASgJEhwKFGphdmFfb3V0ZXJfY2xhc3NuYW1l",
+ "GAggASgJEiIKE2phdmFfbXVsdGlwbGVfZmlsZXMYCiABKAg6BWZhbHNlEikK",
+ "HWphdmFfZ2VuZXJhdGVfZXF1YWxzX2FuZF9oYXNoGBQgASgIQgIYARIlChZq",
+ "YXZhX3N0cmluZ19jaGVja191dGY4GBsgASgIOgVmYWxzZRJGCgxvcHRpbWl6",
+ "ZV9mb3IYCSABKA4yKS5nb29nbGUucHJvdG9idWYuRmlsZU9wdGlvbnMuT3B0",
+ "aW1pemVNb2RlOgVTUEVFRBISCgpnb19wYWNrYWdlGAsgASgJEiIKE2NjX2dl",
+ "bmVyaWNfc2VydmljZXMYECABKAg6BWZhbHNlEiQKFWphdmFfZ2VuZXJpY19z",
+ "ZXJ2aWNlcxgRIAEoCDoFZmFsc2USIgoTcHlfZ2VuZXJpY19zZXJ2aWNlcxgS",
+ "IAEoCDoFZmFsc2USIwoUcGhwX2dlbmVyaWNfc2VydmljZXMYKiABKAg6BWZh",
+ "bHNlEhkKCmRlcHJlY2F0ZWQYFyABKAg6BWZhbHNlEh4KEGNjX2VuYWJsZV9h",
+ "cmVuYXMYHyABKAg6BHRydWUSGQoRb2JqY19jbGFzc19wcmVmaXgYJCABKAkS",
+ "GAoQY3NoYXJwX25hbWVzcGFjZRglIAEoCRIUCgxzd2lmdF9wcmVmaXgYJyAB",
+ "KAkSGAoQcGhwX2NsYXNzX3ByZWZpeBgoIAEoCRIVCg1waHBfbmFtZXNwYWNl",
+ "GCkgASgJEh4KFnBocF9tZXRhZGF0YV9uYW1lc3BhY2UYLCABKAkSFAoMcnVi",
+ "eV9wYWNrYWdlGC0gASgJEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMo",
+ "CzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uIjoKDE9w",
+ "dGltaXplTW9kZRIJCgVTUEVFRBABEg0KCUNPREVfU0laRRACEhAKDExJVEVf",
+ "UlVOVElNRRADKgkI6AcQgICAgAJKBAgmECci8gEKDk1lc3NhZ2VPcHRpb25z",
+ "EiYKF21lc3NhZ2Vfc2V0X3dpcmVfZm9ybWF0GAEgASgIOgVmYWxzZRIuCh9u",
+ "b19zdGFuZGFyZF9kZXNjcmlwdG9yX2FjY2Vzc29yGAIgASgIOgVmYWxzZRIZ",
+ "CgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRIRCgltYXBfZW50cnkYByABKAgS",
"QwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3Rv",
- "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24iUAoQSWRlbXBvdGVuY3lMZXZlbBIX",
- "ChNJREVNUE9URU5DWV9VTktOT1dOEAASEwoPTk9fU0lERV9FRkZFQ1RTEAES",
- "DgoKSURFTVBPVEVOVBACKgkI6AcQgICAgAIingIKE1VuaW50ZXJwcmV0ZWRP",
- "cHRpb24SOwoEbmFtZRgCIAMoCzItLmdvb2dsZS5wcm90b2J1Zi5VbmludGVy",
- "cHJldGVkT3B0aW9uLk5hbWVQYXJ0EhgKEGlkZW50aWZpZXJfdmFsdWUYAyAB",
- "KAkSGgoScG9zaXRpdmVfaW50X3ZhbHVlGAQgASgEEhoKEm5lZ2F0aXZlX2lu",
- "dF92YWx1ZRgFIAEoAxIUCgxkb3VibGVfdmFsdWUYBiABKAESFAoMc3RyaW5n",
- "X3ZhbHVlGAcgASgMEhcKD2FnZ3JlZ2F0ZV92YWx1ZRgIIAEoCRozCghOYW1l",
- "UGFydBIRCgluYW1lX3BhcnQYASACKAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigI",
- "ItUBCg5Tb3VyY2VDb2RlSW5mbxI6Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2ds",
- "ZS5wcm90b2J1Zi5Tb3VyY2VDb2RlSW5mby5Mb2NhdGlvbhqGAQoITG9jYXRp",
- "b24SEAoEcGF0aBgBIAMoBUICEAESEAoEc3BhbhgCIAMoBUICEAESGAoQbGVh",
- "ZGluZ19jb21tZW50cxgDIAEoCRIZChF0cmFpbGluZ19jb21tZW50cxgEIAEo",
- "CRIhChlsZWFkaW5nX2RldGFjaGVkX2NvbW1lbnRzGAYgAygJIqcBChFHZW5l",
- "cmF0ZWRDb2RlSW5mbxJBCgphbm5vdGF0aW9uGAEgAygLMi0uZ29vZ2xlLnBy",
- "b3RvYnVmLkdlbmVyYXRlZENvZGVJbmZvLkFubm90YXRpb24aTwoKQW5ub3Rh",
- "dGlvbhIQCgRwYXRoGAEgAygFQgIQARITCgtzb3VyY2VfZmlsZRgCIAEoCRIN",
- "CgViZWdpbhgDIAEoBRILCgNlbmQYBCABKAVCjwEKE2NvbS5nb29nbGUucHJv",
- "dG9idWZCEERlc2NyaXB0b3JQcm90b3NIAVo+Z2l0aHViLmNvbS9nb2xhbmcv",
- "cHJvdG9idWYvcHJvdG9jLWdlbi1nby9kZXNjcmlwdG9yO2Rlc2NyaXB0b3L4",
- "AQGiAgNHUEKqAhpHb29nbGUuUHJvdG9idWYuUmVmbGVjdGlvbg=="));
+ "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAgQCUoECAkQ",
+ "CiKeAwoMRmllbGRPcHRpb25zEjoKBWN0eXBlGAEgASgOMiMuZ29vZ2xlLnBy",
+ "b3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlwZToGU1RSSU5HEg4KBnBhY2tlZBgC",
+ "IAEoCBI/CgZqc3R5cGUYBiABKA4yJC5nb29nbGUucHJvdG9idWYuRmllbGRP",
+ "cHRpb25zLkpTVHlwZToJSlNfTk9STUFMEhMKBGxhenkYBSABKAg6BWZhbHNl",
+ "EhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlEhMKBHdlYWsYCiABKAg6BWZh",
+ "bHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5w",
+ "cm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uIi8KBUNUeXBlEgoKBlNUUklO",
+ "RxAAEggKBENPUkQQARIQCgxTVFJJTkdfUElFQ0UQAiI1CgZKU1R5cGUSDQoJ",
+ "SlNfTk9STUFMEAASDQoJSlNfU1RSSU5HEAESDQoJSlNfTlVNQkVSEAIqCQjo",
+ "BxCAgICAAkoECAQQBSJeCgxPbmVvZk9wdGlvbnMSQwoUdW5pbnRlcnByZXRl",
+ "ZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0",
+ "ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoLRW51bU9wdGlvbnMSEwoLYWxsb3df",
+ "YWxpYXMYAiABKAgSGQoKZGVwcmVjYXRlZBgDIAEoCDoFZmFsc2USQwoUdW5p",
+ "bnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVu",
+ "aW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAUQBiJ9ChBFbnVtVmFs",
+ "dWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQYASABKAg6BWZhbHNlEkMKFHVuaW50",
+ "ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5Vbmlu",
+ "dGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIiewoOU2VydmljZU9wdGlvbnMS",
+ "GQoKZGVwcmVjYXRlZBghIAEoCDoFZmFsc2USQwoUdW5pbnRlcnByZXRlZF9v",
+ "cHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRP",
+ "cHRpb24qCQjoBxCAgICAAiKtAgoNTWV0aG9kT3B0aW9ucxIZCgpkZXByZWNh",
+ "dGVkGCEgASgIOgVmYWxzZRJfChFpZGVtcG90ZW5jeV9sZXZlbBgiIAEoDjIv",
+ "Lmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRpb25zLklkZW1wb3RlbmN5TGV2",
+ "ZWw6E0lERU1QT1RFTkNZX1VOS05PV04SQwoUdW5pbnRlcnByZXRlZF9vcHRp",
+ "b24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRp",
+ "b24iUAoQSWRlbXBvdGVuY3lMZXZlbBIXChNJREVNUE9URU5DWV9VTktOT1dO",
+ "EAASEwoPTk9fU0lERV9FRkZFQ1RTEAESDgoKSURFTVBPVEVOVBACKgkI6AcQ",
+ "gICAgAIingIKE1VuaW50ZXJwcmV0ZWRPcHRpb24SOwoEbmFtZRgCIAMoCzIt",
+ "Lmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uLk5hbWVQYXJ0",
+ "EhgKEGlkZW50aWZpZXJfdmFsdWUYAyABKAkSGgoScG9zaXRpdmVfaW50X3Zh",
+ "bHVlGAQgASgEEhoKEm5lZ2F0aXZlX2ludF92YWx1ZRgFIAEoAxIUCgxkb3Vi",
+ "bGVfdmFsdWUYBiABKAESFAoMc3RyaW5nX3ZhbHVlGAcgASgMEhcKD2FnZ3Jl",
+ "Z2F0ZV92YWx1ZRgIIAEoCRozCghOYW1lUGFydBIRCgluYW1lX3BhcnQYASAC",
+ "KAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigIItUBCg5Tb3VyY2VDb2RlSW5mbxI6",
+ "Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb2Rl",
+ "SW5mby5Mb2NhdGlvbhqGAQoITG9jYXRpb24SEAoEcGF0aBgBIAMoBUICEAES",
+ "EAoEc3BhbhgCIAMoBUICEAESGAoQbGVhZGluZ19jb21tZW50cxgDIAEoCRIZ",
+ "ChF0cmFpbGluZ19jb21tZW50cxgEIAEoCRIhChlsZWFkaW5nX2RldGFjaGVk",
+ "X2NvbW1lbnRzGAYgAygJIqcBChFHZW5lcmF0ZWRDb2RlSW5mbxJBCgphbm5v",
+ "dGF0aW9uGAEgAygLMi0uZ29vZ2xlLnByb3RvYnVmLkdlbmVyYXRlZENvZGVJ",
+ "bmZvLkFubm90YXRpb24aTwoKQW5ub3RhdGlvbhIQCgRwYXRoGAEgAygFQgIQ",
+ "ARITCgtzb3VyY2VfZmlsZRgCIAEoCRINCgViZWdpbhgDIAEoBRILCgNlbmQY",
+ "BCABKAVCjwEKE2NvbS5nb29nbGUucHJvdG9idWZCEERlc2NyaXB0b3JQcm90",
+ "b3NIAVo+Z2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYvcHJvdG9jLWdlbi1n",
+ "by9kZXNjcmlwdG9yO2Rlc2NyaXB0b3L4AQGiAgNHUEKqAhpHb29nbGUuUHJv",
+ "dG9idWYuUmVmbGVjdGlvbg=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
@@ -166,7 +167,7 @@
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto), global::Google.Protobuf.Reflection.DescriptorProto.Parser, new[]{ "Name", "Field", "Extension", "NestedType", "EnumType", "ExtensionRange", "OneofDecl", "Options", "ReservedRange", "ReservedName" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange), global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange.Parser, new[]{ "Start", "End", "Options" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange), global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange.Parser, new[]{ "Start", "End" }, null, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.ExtensionRangeOptions), global::Google.Protobuf.Reflection.ExtensionRangeOptions.Parser, new[]{ "UninterpretedOption" }, null, null, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto), global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser, new[]{ "Name", "Number", "Label", "Type", "TypeName", "Extendee", "DefaultValue", "OneofIndex", "JsonName", "Options" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type), typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) }, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto), global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser, new[]{ "Name", "Number", "Label", "Type", "TypeName", "Extendee", "DefaultValue", "OneofIndex", "JsonName", "Options", "Proto3Optional" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type), typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.OneofDescriptorProto), global::Google.Protobuf.Reflection.OneofDescriptorProto.Parser, new[]{ "Name", "Options" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto), global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser, new[]{ "Name", "Value", "Options", "ReservedRange", "ReservedName" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange), global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange.Parser, new[]{ "Start", "End" }, null, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueDescriptorProto), global::Google.Protobuf.Reflection.EnumValueDescriptorProto.Parser, new[]{ "Name", "Number", "Options" }, null, null, null, null),
@@ -193,7 +194,7 @@
/// The protocol compiler can output a FileDescriptorSet containing the .proto
/// files it parses.
/// </summary>
- public sealed partial class FileDescriptorSet : pb::IMessage<FileDescriptorSet> {
+ public sealed partial class FileDescriptorSet : pb::IMessage<FileDescriptorSet>, pb::IBufferMessage {
private static readonly pb::MessageParser<FileDescriptorSet> _parser = new pb::MessageParser<FileDescriptorSet>(() => new FileDescriptorSet());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -298,14 +299,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- file_.AddEntriesFrom(input, _repeated_file_codec);
+ file_.AddEntriesFrom(ref input, _repeated_file_codec);
break;
}
}
@@ -317,7 +323,7 @@
/// <summary>
/// Describes a complete .proto file.
/// </summary>
- public sealed partial class FileDescriptorProto : pb::IMessage<FileDescriptorProto> {
+ public sealed partial class FileDescriptorProto : pb::IMessage<FileDescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<FileDescriptorProto> _parser = new pb::MessageParser<FileDescriptorProto>(() => new FileDescriptorProto());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -351,8 +357,8 @@
enumType_ = other.enumType_.Clone();
service_ = other.service_.Clone();
extension_ = other.extension_.Clone();
- options_ = other.HasOptions ? other.options_.Clone() : null;
- sourceCodeInfo_ = other.HasSourceCodeInfo ? other.sourceCodeInfo_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
+ sourceCodeInfo_ = other.sourceCodeInfo_ != null ? other.sourceCodeInfo_.Clone() : null;
syntax_ = other.syntax_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -507,16 +513,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
/// <summary>Field number for the "source_code_info" field.</summary>
public const int SourceCodeInfoFieldNumber = 9;
@@ -534,16 +530,6 @@
sourceCodeInfo_ = value;
}
}
- /// <summary>Gets whether the source_code_info field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasSourceCodeInfo {
- get { return sourceCodeInfo_ != null; }
- }
- /// <summary>Clears the value of the source_code_info field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearSourceCodeInfo() {
- sourceCodeInfo_ = null;
- }
/// <summary>Field number for the "syntax" field.</summary>
public const int SyntaxFieldNumber = 12;
@@ -612,8 +598,8 @@
hash ^= enumType_.GetHashCode();
hash ^= service_.GetHashCode();
hash ^= extension_.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
- if (HasSourceCodeInfo) hash ^= SourceCodeInfo.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
+ if (sourceCodeInfo_ != null) hash ^= SourceCodeInfo.GetHashCode();
if (HasSyntax) hash ^= Syntax.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -641,11 +627,11 @@
enumType_.WriteTo(output, _repeated_enumType_codec);
service_.WriteTo(output, _repeated_service_codec);
extension_.WriteTo(output, _repeated_extension_codec);
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(66);
output.WriteMessage(Options);
}
- if (HasSourceCodeInfo) {
+ if (sourceCodeInfo_ != null) {
output.WriteRawTag(74);
output.WriteMessage(SourceCodeInfo);
}
@@ -676,10 +662,10 @@
size += enumType_.CalculateSize(_repeated_enumType_codec);
size += service_.CalculateSize(_repeated_service_codec);
size += extension_.CalculateSize(_repeated_extension_codec);
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
- if (HasSourceCodeInfo) {
+ if (sourceCodeInfo_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceCodeInfo);
}
if (HasSyntax) {
@@ -709,14 +695,14 @@
enumType_.Add(other.enumType_);
service_.Add(other.service_);
extension_.Add(other.extension_);
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.FileOptions();
}
Options.MergeFrom(other.Options);
}
- if (other.HasSourceCodeInfo) {
- if (!HasSourceCodeInfo) {
+ if (other.sourceCodeInfo_ != null) {
+ if (sourceCodeInfo_ == null) {
SourceCodeInfo = new global::Google.Protobuf.Reflection.SourceCodeInfo();
}
SourceCodeInfo.MergeFrom(other.SourceCodeInfo);
@@ -729,11 +715,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -744,34 +735,34 @@
break;
}
case 26: {
- dependency_.AddEntriesFrom(input, _repeated_dependency_codec);
+ dependency_.AddEntriesFrom(ref input, _repeated_dependency_codec);
break;
}
case 34: {
- messageType_.AddEntriesFrom(input, _repeated_messageType_codec);
+ messageType_.AddEntriesFrom(ref input, _repeated_messageType_codec);
break;
}
case 42: {
- enumType_.AddEntriesFrom(input, _repeated_enumType_codec);
+ enumType_.AddEntriesFrom(ref input, _repeated_enumType_codec);
break;
}
case 50: {
- service_.AddEntriesFrom(input, _repeated_service_codec);
+ service_.AddEntriesFrom(ref input, _repeated_service_codec);
break;
}
case 58: {
- extension_.AddEntriesFrom(input, _repeated_extension_codec);
+ extension_.AddEntriesFrom(ref input, _repeated_extension_codec);
break;
}
case 66: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.FileOptions();
}
input.ReadMessage(Options);
break;
}
case 74: {
- if (!HasSourceCodeInfo) {
+ if (sourceCodeInfo_ == null) {
SourceCodeInfo = new global::Google.Protobuf.Reflection.SourceCodeInfo();
}
input.ReadMessage(SourceCodeInfo);
@@ -779,12 +770,12 @@
}
case 82:
case 80: {
- publicDependency_.AddEntriesFrom(input, _repeated_publicDependency_codec);
+ publicDependency_.AddEntriesFrom(ref input, _repeated_publicDependency_codec);
break;
}
case 90:
case 88: {
- weakDependency_.AddEntriesFrom(input, _repeated_weakDependency_codec);
+ weakDependency_.AddEntriesFrom(ref input, _repeated_weakDependency_codec);
break;
}
case 98: {
@@ -800,7 +791,7 @@
/// <summary>
/// Describes a message type.
/// </summary>
- public sealed partial class DescriptorProto : pb::IMessage<DescriptorProto> {
+ public sealed partial class DescriptorProto : pb::IMessage<DescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<DescriptorProto> _parser = new pb::MessageParser<DescriptorProto>(() => new DescriptorProto());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -832,7 +823,7 @@
enumType_ = other.enumType_.Clone();
extensionRange_ = other.extensionRange_.Clone();
oneofDecl_ = other.oneofDecl_.Clone();
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
reservedRange_ = other.reservedRange_.Clone();
reservedName_ = other.reservedName_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -936,16 +927,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
/// <summary>Field number for the "reserved_range" field.</summary>
public const int ReservedRangeFieldNumber = 9;
@@ -1007,7 +988,7 @@
hash ^= enumType_.GetHashCode();
hash ^= extensionRange_.GetHashCode();
hash ^= oneofDecl_.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
hash ^= reservedRange_.GetHashCode();
hash ^= reservedName_.GetHashCode();
if (_unknownFields != null) {
@@ -1032,7 +1013,7 @@
enumType_.WriteTo(output, _repeated_enumType_codec);
extensionRange_.WriteTo(output, _repeated_extensionRange_codec);
extension_.WriteTo(output, _repeated_extension_codec);
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(58);
output.WriteMessage(Options);
}
@@ -1056,7 +1037,7 @@
size += enumType_.CalculateSize(_repeated_enumType_codec);
size += extensionRange_.CalculateSize(_repeated_extensionRange_codec);
size += oneofDecl_.CalculateSize(_repeated_oneofDecl_codec);
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
size += reservedRange_.CalculateSize(_repeated_reservedRange_codec);
@@ -1081,8 +1062,8 @@
enumType_.Add(other.enumType_);
extensionRange_.Add(other.extensionRange_);
oneofDecl_.Add(other.oneofDecl_);
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.MessageOptions();
}
Options.MergeFrom(other.Options);
@@ -1094,53 +1075,58 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
- field_.AddEntriesFrom(input, _repeated_field_codec);
+ field_.AddEntriesFrom(ref input, _repeated_field_codec);
break;
}
case 26: {
- nestedType_.AddEntriesFrom(input, _repeated_nestedType_codec);
+ nestedType_.AddEntriesFrom(ref input, _repeated_nestedType_codec);
break;
}
case 34: {
- enumType_.AddEntriesFrom(input, _repeated_enumType_codec);
+ enumType_.AddEntriesFrom(ref input, _repeated_enumType_codec);
break;
}
case 42: {
- extensionRange_.AddEntriesFrom(input, _repeated_extensionRange_codec);
+ extensionRange_.AddEntriesFrom(ref input, _repeated_extensionRange_codec);
break;
}
case 50: {
- extension_.AddEntriesFrom(input, _repeated_extension_codec);
+ extension_.AddEntriesFrom(ref input, _repeated_extension_codec);
break;
}
case 58: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.MessageOptions();
}
input.ReadMessage(Options);
break;
}
case 66: {
- oneofDecl_.AddEntriesFrom(input, _repeated_oneofDecl_codec);
+ oneofDecl_.AddEntriesFrom(ref input, _repeated_oneofDecl_codec);
break;
}
case 74: {
- reservedRange_.AddEntriesFrom(input, _repeated_reservedRange_codec);
+ reservedRange_.AddEntriesFrom(ref input, _repeated_reservedRange_codec);
break;
}
case 82: {
- reservedName_.AddEntriesFrom(input, _repeated_reservedName_codec);
+ reservedName_.AddEntriesFrom(ref input, _repeated_reservedName_codec);
break;
}
}
@@ -1151,7 +1137,7 @@
/// <summary>Container for nested types declared in the DescriptorProto message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class ExtensionRange : pb::IMessage<ExtensionRange> {
+ public sealed partial class ExtensionRange : pb::IMessage<ExtensionRange>, pb::IBufferMessage {
private static readonly pb::MessageParser<ExtensionRange> _parser = new pb::MessageParser<ExtensionRange>(() => new ExtensionRange());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -1180,7 +1166,7 @@
_hasBits0 = other._hasBits0;
start_ = other.start_;
end_ = other.end_;
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -1253,16 +1239,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -1288,7 +1264,7 @@
int hash = 1;
if (HasStart) hash ^= Start.GetHashCode();
if (HasEnd) hash ^= End.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -1310,7 +1286,7 @@
output.WriteRawTag(16);
output.WriteInt32(End);
}
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Options);
}
@@ -1328,7 +1304,7 @@
if (HasEnd) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(End);
}
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
if (_unknownFields != null) {
@@ -1348,8 +1324,8 @@
if (other.HasEnd) {
End = other.End;
}
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.ExtensionRangeOptions();
}
Options.MergeFrom(other.Options);
@@ -1359,11 +1335,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Start = input.ReadInt32();
@@ -1374,7 +1355,7 @@
break;
}
case 26: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.ExtensionRangeOptions();
}
input.ReadMessage(Options);
@@ -1391,7 +1372,7 @@
/// fields or extension ranges in the same message. Reserved ranges may
/// not overlap.
/// </summary>
- public sealed partial class ReservedRange : pb::IMessage<ReservedRange> {
+ public sealed partial class ReservedRange : pb::IMessage<ReservedRange>, pb::IBufferMessage {
private static readonly pb::MessageParser<ReservedRange> _parser = new pb::MessageParser<ReservedRange>(() => new ReservedRange());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -1562,11 +1543,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Start = input.ReadInt32();
@@ -1587,7 +1573,7 @@
}
- public sealed partial class ExtensionRangeOptions : pb::IExtendableMessage<ExtensionRangeOptions> {
+ public sealed partial class ExtensionRangeOptions : pb::IExtendableMessage<ExtensionRangeOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<ExtensionRangeOptions> _parser = new pb::MessageParser<ExtensionRangeOptions>(() => new ExtensionRangeOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<ExtensionRangeOptions> _extensions;
@@ -1711,16 +1697,21 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -1754,7 +1745,7 @@
/// <summary>
/// Describes a field within a message.
/// </summary>
- public sealed partial class FieldDescriptorProto : pb::IMessage<FieldDescriptorProto> {
+ public sealed partial class FieldDescriptorProto : pb::IMessage<FieldDescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<FieldDescriptorProto> _parser = new pb::MessageParser<FieldDescriptorProto>(() => new FieldDescriptorProto());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -1790,7 +1781,8 @@
defaultValue_ = other.defaultValue_;
oneofIndex_ = other.oneofIndex_;
jsonName_ = other.jsonName_;
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
+ proto3Optional_ = other.proto3Optional_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2052,15 +2044,52 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
+
+ /// <summary>Field number for the "proto3_optional" field.</summary>
+ public const int Proto3OptionalFieldNumber = 17;
+ private readonly static bool Proto3OptionalDefaultValue = false;
+
+ private bool proto3Optional_;
+ /// <summary>
+ /// If true, this is a proto3 "optional". When a proto3 field is optional, it
+ /// tracks presence regardless of field type.
+ ///
+ /// When proto3_optional is true, this field must be belong to a oneof to
+ /// signal to old proto3 clients that presence is tracked for this field. This
+ /// oneof is known as a "synthetic" oneof, and this field must be its sole
+ /// member (each proto3 optional field gets its own synthetic oneof). Synthetic
+ /// oneofs exist in the descriptor only, and do not generate any API. Synthetic
+ /// oneofs must be ordered after all "real" oneofs.
+ ///
+ /// For message fields, proto3_optional doesn't create any semantic change,
+ /// since non-repeated message fields always track presence. However it still
+ /// indicates the semantic detail of whether the user wrote "optional" or not.
+ /// This can be useful for round-tripping the .proto file. For consistency we
+ /// give message fields a synthetic oneof also, even though it is not required
+ /// to track presence. This is especially important because the parser can't
+ /// tell if a field is a message or an enum, so it must always create a
+ /// synthetic oneof.
+ ///
+ /// Proto2 optional fields do not set this flag, because they already indicate
+ /// optional with `LABEL_OPTIONAL`.
+ /// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
+ public bool Proto3Optional {
+ get { if ((_hasBits0 & 16) != 0) { return proto3Optional_; } else { return Proto3OptionalDefaultValue; } }
+ set {
+ _hasBits0 |= 16;
+ proto3Optional_ = value;
+ }
}
- /// <summary>Clears the value of the options field</summary>
+ /// <summary>Gets whether the "proto3_optional" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
+ public bool HasProto3Optional {
+ get { return (_hasBits0 & 16) != 0; }
+ }
+ /// <summary>Clears the value of the "proto3_optional" field</summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public void ClearProto3Optional() {
+ _hasBits0 &= ~16;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2086,6 +2115,7 @@
if (OneofIndex != other.OneofIndex) return false;
if (JsonName != other.JsonName) return false;
if (!object.Equals(Options, other.Options)) return false;
+ if (Proto3Optional != other.Proto3Optional) return false;
return Equals(_unknownFields, other._unknownFields);
}
@@ -2101,7 +2131,8 @@
if (HasDefaultValue) hash ^= DefaultValue.GetHashCode();
if (HasOneofIndex) hash ^= OneofIndex.GetHashCode();
if (HasJsonName) hash ^= JsonName.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
+ if (HasProto3Optional) hash ^= Proto3Optional.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -2143,7 +2174,7 @@
output.WriteRawTag(58);
output.WriteString(DefaultValue);
}
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(66);
output.WriteMessage(Options);
}
@@ -2155,6 +2186,10 @@
output.WriteRawTag(82);
output.WriteString(JsonName);
}
+ if (HasProto3Optional) {
+ output.WriteRawTag(136, 1);
+ output.WriteBool(Proto3Optional);
+ }
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
@@ -2190,9 +2225,12 @@
if (HasJsonName) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonName);
}
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
+ if (HasProto3Optional) {
+ size += 2 + 1;
+ }
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
@@ -2231,22 +2269,30 @@
if (other.HasJsonName) {
JsonName = other.JsonName;
}
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.FieldOptions();
}
Options.MergeFrom(other.Options);
}
+ if (other.HasProto3Optional) {
+ Proto3Optional = other.Proto3Optional;
+ }
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -2277,7 +2323,7 @@
break;
}
case 66: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.FieldOptions();
}
input.ReadMessage(Options);
@@ -2291,6 +2337,10 @@
JsonName = input.ReadString();
break;
}
+ case 136: {
+ Proto3Optional = input.ReadBool();
+ break;
+ }
}
}
}
@@ -2367,7 +2417,7 @@
/// <summary>
/// Describes a oneof.
/// </summary>
- public sealed partial class OneofDescriptorProto : pb::IMessage<OneofDescriptorProto> {
+ public sealed partial class OneofDescriptorProto : pb::IMessage<OneofDescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneofDescriptorProto> _parser = new pb::MessageParser<OneofDescriptorProto>(() => new OneofDescriptorProto());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2393,7 +2443,7 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OneofDescriptorProto(OneofDescriptorProto other) : this() {
name_ = other.name_;
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -2435,16 +2485,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -2468,7 +2508,7 @@
public override int GetHashCode() {
int hash = 1;
if (HasName) hash ^= Name.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -2486,7 +2526,7 @@
output.WriteRawTag(10);
output.WriteString(Name);
}
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Options);
}
@@ -2501,7 +2541,7 @@
if (HasName) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
if (_unknownFields != null) {
@@ -2518,8 +2558,8 @@
if (other.HasName) {
Name = other.Name;
}
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.OneofOptions();
}
Options.MergeFrom(other.Options);
@@ -2529,18 +2569,23 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.OneofOptions();
}
input.ReadMessage(Options);
@@ -2555,7 +2600,7 @@
/// <summary>
/// Describes an enum type.
/// </summary>
- public sealed partial class EnumDescriptorProto : pb::IMessage<EnumDescriptorProto> {
+ public sealed partial class EnumDescriptorProto : pb::IMessage<EnumDescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<EnumDescriptorProto> _parser = new pb::MessageParser<EnumDescriptorProto>(() => new EnumDescriptorProto());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2582,7 +2627,7 @@
public EnumDescriptorProto(EnumDescriptorProto other) : this() {
name_ = other.name_;
value_ = other.value_.Clone();
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
reservedRange_ = other.reservedRange_.Clone();
reservedName_ = other.reservedName_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -2636,16 +2681,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
/// <summary>Field number for the "reserved_range" field.</summary>
public const int ReservedRangeFieldNumber = 4;
@@ -2702,7 +2737,7 @@
int hash = 1;
if (HasName) hash ^= Name.GetHashCode();
hash ^= value_.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
hash ^= reservedRange_.GetHashCode();
hash ^= reservedName_.GetHashCode();
if (_unknownFields != null) {
@@ -2723,7 +2758,7 @@
output.WriteString(Name);
}
value_.WriteTo(output, _repeated_value_codec);
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Options);
}
@@ -2741,7 +2776,7 @@
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
size += value_.CalculateSize(_repeated_value_codec);
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
size += reservedRange_.CalculateSize(_repeated_reservedRange_codec);
@@ -2761,8 +2796,8 @@
Name = other.Name;
}
value_.Add(other.value_);
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.EnumOptions();
}
Options.MergeFrom(other.Options);
@@ -2774,33 +2809,38 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
- value_.AddEntriesFrom(input, _repeated_value_codec);
+ value_.AddEntriesFrom(ref input, _repeated_value_codec);
break;
}
case 26: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.EnumOptions();
}
input.ReadMessage(Options);
break;
}
case 34: {
- reservedRange_.AddEntriesFrom(input, _repeated_reservedRange_codec);
+ reservedRange_.AddEntriesFrom(ref input, _repeated_reservedRange_codec);
break;
}
case 42: {
- reservedName_.AddEntriesFrom(input, _repeated_reservedName_codec);
+ reservedName_.AddEntriesFrom(ref input, _repeated_reservedName_codec);
break;
}
}
@@ -2819,7 +2859,7 @@
/// is inclusive such that it can appropriately represent the entire int32
/// domain.
/// </summary>
- public sealed partial class EnumReservedRange : pb::IMessage<EnumReservedRange> {
+ public sealed partial class EnumReservedRange : pb::IMessage<EnumReservedRange>, pb::IBufferMessage {
private static readonly pb::MessageParser<EnumReservedRange> _parser = new pb::MessageParser<EnumReservedRange>(() => new EnumReservedRange());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -2990,11 +3030,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Start = input.ReadInt32();
@@ -3018,7 +3063,7 @@
/// <summary>
/// Describes a value within an enum.
/// </summary>
- public sealed partial class EnumValueDescriptorProto : pb::IMessage<EnumValueDescriptorProto> {
+ public sealed partial class EnumValueDescriptorProto : pb::IMessage<EnumValueDescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<EnumValueDescriptorProto> _parser = new pb::MessageParser<EnumValueDescriptorProto>(() => new EnumValueDescriptorProto());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -3047,7 +3092,7 @@
_hasBits0 = other._hasBits0;
name_ = other.name_;
number_ = other.number_;
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -3113,16 +3158,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -3148,7 +3183,7 @@
int hash = 1;
if (HasName) hash ^= Name.GetHashCode();
if (HasNumber) hash ^= Number.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -3170,7 +3205,7 @@
output.WriteRawTag(16);
output.WriteInt32(Number);
}
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Options);
}
@@ -3188,7 +3223,7 @@
if (HasNumber) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number);
}
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
if (_unknownFields != null) {
@@ -3208,8 +3243,8 @@
if (other.HasNumber) {
Number = other.Number;
}
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.EnumValueOptions();
}
Options.MergeFrom(other.Options);
@@ -3219,11 +3254,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -3234,7 +3274,7 @@
break;
}
case 26: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.EnumValueOptions();
}
input.ReadMessage(Options);
@@ -3249,7 +3289,7 @@
/// <summary>
/// Describes a service.
/// </summary>
- public sealed partial class ServiceDescriptorProto : pb::IMessage<ServiceDescriptorProto> {
+ public sealed partial class ServiceDescriptorProto : pb::IMessage<ServiceDescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<ServiceDescriptorProto> _parser = new pb::MessageParser<ServiceDescriptorProto>(() => new ServiceDescriptorProto());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -3276,7 +3316,7 @@
public ServiceDescriptorProto(ServiceDescriptorProto other) : this() {
name_ = other.name_;
method_ = other.method_.Clone();
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
@@ -3328,16 +3368,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
@@ -3363,7 +3393,7 @@
int hash = 1;
if (HasName) hash ^= Name.GetHashCode();
hash ^= method_.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@@ -3382,7 +3412,7 @@
output.WriteString(Name);
}
method_.WriteTo(output, _repeated_method_codec);
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Options);
}
@@ -3398,7 +3428,7 @@
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
size += method_.CalculateSize(_repeated_method_codec);
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
if (_unknownFields != null) {
@@ -3416,8 +3446,8 @@
Name = other.Name;
}
method_.Add(other.method_);
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.ServiceOptions();
}
Options.MergeFrom(other.Options);
@@ -3427,22 +3457,27 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
- method_.AddEntriesFrom(input, _repeated_method_codec);
+ method_.AddEntriesFrom(ref input, _repeated_method_codec);
break;
}
case 26: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.ServiceOptions();
}
input.ReadMessage(Options);
@@ -3457,7 +3492,7 @@
/// <summary>
/// Describes a method of a service.
/// </summary>
- public sealed partial class MethodDescriptorProto : pb::IMessage<MethodDescriptorProto> {
+ public sealed partial class MethodDescriptorProto : pb::IMessage<MethodDescriptorProto>, pb::IBufferMessage {
private static readonly pb::MessageParser<MethodDescriptorProto> _parser = new pb::MessageParser<MethodDescriptorProto>(() => new MethodDescriptorProto());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -3487,7 +3522,7 @@
name_ = other.name_;
inputType_ = other.inputType_;
outputType_ = other.outputType_;
- options_ = other.HasOptions ? other.options_.Clone() : null;
+ options_ = other.options_ != null ? other.options_.Clone() : null;
clientStreaming_ = other.clientStreaming_;
serverStreaming_ = other.serverStreaming_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
@@ -3581,16 +3616,6 @@
options_ = value;
}
}
- /// <summary>Gets whether the options field is set</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public bool HasOptions {
- get { return options_ != null; }
- }
- /// <summary>Clears the value of the options field</summary>
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
- public void ClearOptions() {
- options_ = null;
- }
/// <summary>Field number for the "client_streaming" field.</summary>
public const int ClientStreamingFieldNumber = 5;
@@ -3674,7 +3699,7 @@
if (HasName) hash ^= Name.GetHashCode();
if (HasInputType) hash ^= InputType.GetHashCode();
if (HasOutputType) hash ^= OutputType.GetHashCode();
- if (HasOptions) hash ^= Options.GetHashCode();
+ if (options_ != null) hash ^= Options.GetHashCode();
if (HasClientStreaming) hash ^= ClientStreaming.GetHashCode();
if (HasServerStreaming) hash ^= ServerStreaming.GetHashCode();
if (_unknownFields != null) {
@@ -3702,7 +3727,7 @@
output.WriteRawTag(26);
output.WriteString(OutputType);
}
- if (HasOptions) {
+ if (options_ != null) {
output.WriteRawTag(34);
output.WriteMessage(Options);
}
@@ -3731,7 +3756,7 @@
if (HasOutputType) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(OutputType);
}
- if (HasOptions) {
+ if (options_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options);
}
if (HasClientStreaming) {
@@ -3760,8 +3785,8 @@
if (other.HasOutputType) {
OutputType = other.OutputType;
}
- if (other.HasOptions) {
- if (!HasOptions) {
+ if (other.options_ != null) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.MethodOptions();
}
Options.MergeFrom(other.Options);
@@ -3777,11 +3802,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -3796,7 +3826,7 @@
break;
}
case 34: {
- if (!HasOptions) {
+ if (options_ == null) {
Options = new global::Google.Protobuf.Reflection.MethodOptions();
}
input.ReadMessage(Options);
@@ -3816,7 +3846,7 @@
}
- public sealed partial class FileOptions : pb::IExtendableMessage<FileOptions> {
+ public sealed partial class FileOptions : pb::IExtendableMessage<FileOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<FileOptions> _parser = new pb::MessageParser<FileOptions>(() => new FileOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<FileOptions> _extensions;
@@ -4222,7 +4252,7 @@
/// <summary>Field number for the "cc_enable_arenas" field.</summary>
public const int CcEnableArenasFieldNumber = 31;
- private readonly static bool CcEnableArenasDefaultValue = false;
+ private readonly static bool CcEnableArenasDefaultValue = true;
private bool ccEnableArenas_;
/// <summary>
@@ -4769,12 +4799,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 10: {
@@ -4858,7 +4893,7 @@
break;
}
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -4914,7 +4949,7 @@
}
- public sealed partial class MessageOptions : pb::IExtendableMessage<MessageOptions> {
+ public sealed partial class MessageOptions : pb::IExtendableMessage<MessageOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<MessageOptions> _parser = new pb::MessageParser<MessageOptions>(() => new MessageOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<MessageOptions> _extensions;
@@ -5242,12 +5277,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 8: {
@@ -5267,7 +5307,7 @@
break;
}
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -5298,7 +5338,7 @@
}
- public sealed partial class FieldOptions : pb::IExtendableMessage<FieldOptions> {
+ public sealed partial class FieldOptions : pb::IExtendableMessage<FieldOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<FieldOptions> _parser = new pb::MessageParser<FieldOptions>(() => new FieldOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<FieldOptions> _extensions;
@@ -5710,12 +5750,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 8: {
@@ -5743,7 +5788,7 @@
break;
}
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -5805,7 +5850,7 @@
}
- public sealed partial class OneofOptions : pb::IExtendableMessage<OneofOptions> {
+ public sealed partial class OneofOptions : pb::IExtendableMessage<OneofOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<OneofOptions> _parser = new pb::MessageParser<OneofOptions>(() => new OneofOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<OneofOptions> _extensions;
@@ -5929,16 +5974,21 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -5969,7 +6019,7 @@
}
- public sealed partial class EnumOptions : pb::IExtendableMessage<EnumOptions> {
+ public sealed partial class EnumOptions : pb::IExtendableMessage<EnumOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<EnumOptions> _parser = new pb::MessageParser<EnumOptions>(() => new EnumOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<EnumOptions> _extensions;
@@ -6179,12 +6229,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 16: {
@@ -6196,7 +6251,7 @@
break;
}
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -6227,7 +6282,7 @@
}
- public sealed partial class EnumValueOptions : pb::IExtendableMessage<EnumValueOptions> {
+ public sealed partial class EnumValueOptions : pb::IExtendableMessage<EnumValueOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<EnumValueOptions> _parser = new pb::MessageParser<EnumValueOptions>(() => new EnumValueOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<EnumValueOptions> _extensions;
@@ -6396,12 +6451,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 8: {
@@ -6409,7 +6469,7 @@
break;
}
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -6440,7 +6500,7 @@
}
- public sealed partial class ServiceOptions : pb::IExtendableMessage<ServiceOptions> {
+ public sealed partial class ServiceOptions : pb::IExtendableMessage<ServiceOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<ServiceOptions> _parser = new pb::MessageParser<ServiceOptions>(() => new ServiceOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<ServiceOptions> _extensions;
@@ -6609,12 +6669,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 264: {
@@ -6622,7 +6687,7 @@
break;
}
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -6653,7 +6718,7 @@
}
- public sealed partial class MethodOptions : pb::IExtendableMessage<MethodOptions> {
+ public sealed partial class MethodOptions : pb::IExtendableMessage<MethodOptions>, pb::IBufferMessage {
private static readonly pb::MessageParser<MethodOptions> _parser = new pb::MessageParser<MethodOptions>(() => new MethodOptions());
private pb::UnknownFieldSet _unknownFields;
internal pb::ExtensionSet<MethodOptions> _extensions;
@@ -6859,12 +6924,17 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
}
break;
case 264: {
@@ -6876,7 +6946,7 @@
break;
}
case 7994: {
- uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
+ uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;
}
}
@@ -6939,7 +7009,7 @@
/// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
/// in them.
/// </summary>
- public sealed partial class UninterpretedOption : pb::IMessage<UninterpretedOption> {
+ public sealed partial class UninterpretedOption : pb::IMessage<UninterpretedOption>, pb::IBufferMessage {
private static readonly pb::MessageParser<UninterpretedOption> _parser = new pb::MessageParser<UninterpretedOption>(() => new UninterpretedOption());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -7269,14 +7339,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 18: {
- name_.AddEntriesFrom(input, _repeated_name_codec);
+ name_.AddEntriesFrom(ref input, _repeated_name_codec);
break;
}
case 26: {
@@ -7318,7 +7393,7 @@
/// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
/// "foo.(bar.baz).qux".
/// </summary>
- public sealed partial class NamePart : pb::IMessage<NamePart> {
+ public sealed partial class NamePart : pb::IMessage<NamePart>, pb::IBufferMessage {
private static readonly pb::MessageParser<NamePart> _parser = new pb::MessageParser<NamePart>(() => new NamePart());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -7482,11 +7557,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
NamePart_ = input.ReadString();
@@ -7511,7 +7591,7 @@
/// Encapsulates information about the original source file from which a
/// FileDescriptorProto was generated.
/// </summary>
- public sealed partial class SourceCodeInfo : pb::IMessage<SourceCodeInfo> {
+ public sealed partial class SourceCodeInfo : pb::IMessage<SourceCodeInfo>, pb::IBufferMessage {
private static readonly pb::MessageParser<SourceCodeInfo> _parser = new pb::MessageParser<SourceCodeInfo>(() => new SourceCodeInfo());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7661,14 +7741,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- location_.AddEntriesFrom(input, _repeated_location_codec);
+ location_.AddEntriesFrom(ref input, _repeated_location_codec);
break;
}
}
@@ -7679,7 +7764,7 @@
/// <summary>Container for nested types declared in the SourceCodeInfo message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class Location : pb::IMessage<Location> {
+ public sealed partial class Location : pb::IMessage<Location>, pb::IBufferMessage {
private static readonly pb::MessageParser<Location> _parser = new pb::MessageParser<Location>(() => new Location());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -7969,20 +8054,25 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10:
case 8: {
- path_.AddEntriesFrom(input, _repeated_path_codec);
+ path_.AddEntriesFrom(ref input, _repeated_path_codec);
break;
}
case 18:
case 16: {
- span_.AddEntriesFrom(input, _repeated_span_codec);
+ span_.AddEntriesFrom(ref input, _repeated_span_codec);
break;
}
case 26: {
@@ -7994,7 +8084,7 @@
break;
}
case 50: {
- leadingDetachedComments_.AddEntriesFrom(input, _repeated_leadingDetachedComments_codec);
+ leadingDetachedComments_.AddEntriesFrom(ref input, _repeated_leadingDetachedComments_codec);
break;
}
}
@@ -8013,7 +8103,7 @@
/// file. A GeneratedCodeInfo message is associated with only one generated
/// source file, but may contain references to different source .proto files.
/// </summary>
- public sealed partial class GeneratedCodeInfo : pb::IMessage<GeneratedCodeInfo> {
+ public sealed partial class GeneratedCodeInfo : pb::IMessage<GeneratedCodeInfo>, pb::IBufferMessage {
private static readonly pb::MessageParser<GeneratedCodeInfo> _parser = new pb::MessageParser<GeneratedCodeInfo>(() => new GeneratedCodeInfo());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -8122,14 +8212,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- annotation_.AddEntriesFrom(input, _repeated_annotation_codec);
+ annotation_.AddEntriesFrom(ref input, _repeated_annotation_codec);
break;
}
}
@@ -8140,7 +8235,7 @@
/// <summary>Container for nested types declared in the GeneratedCodeInfo message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
- public sealed partial class Annotation : pb::IMessage<Annotation> {
+ public sealed partial class Annotation : pb::IMessage<Annotation>, pb::IBufferMessage {
private static readonly pb::MessageParser<Annotation> _parser = new pb::MessageParser<Annotation>(() => new Annotation());
private pb::UnknownFieldSet _unknownFields;
private int _hasBits0;
@@ -8373,15 +8468,20 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10:
case 8: {
- path_.AddEntriesFrom(input, _repeated_path_codec);
+ path_.AddEntriesFrom(ref input, _repeated_path_codec);
break;
}
case 18: {
diff --git a/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs
index 264a88a..f7e8b5b 100644
--- a/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs
@@ -128,12 +128,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this enum.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>EnumOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public EnumOptions GetOptions() => Proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value enum option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<EnumOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
@@ -143,6 +152,7 @@
/// <summary>
/// Gets a repeated value enum option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<EnumOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
diff --git a/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs
index 3933820..05097bd 100644
--- a/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs
@@ -73,12 +73,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this enum value.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>EnumValueOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public EnumValueOptions GetOptions() => Proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value enum value option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<EnumValueOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
@@ -88,6 +97,7 @@
/// <summary>
/// Gets a repeated value enum value option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<EnumValueOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
diff --git a/csharp/src/Google.Protobuf/Reflection/ExtensionCollection.cs b/csharp/src/Google.Protobuf/Reflection/ExtensionCollection.cs
index 38e33d7..9664559 100644
--- a/csharp/src/Google.Protobuf/Reflection/ExtensionCollection.cs
+++ b/csharp/src/Google.Protobuf/Reflection/ExtensionCollection.cs
@@ -107,13 +107,14 @@
{
descriptor.CrossLink();
- IList<FieldDescriptor> _;
- if (!declarationOrder.TryGetValue(descriptor.ExtendeeType, out _))
+ IList<FieldDescriptor> list;
+ if (!declarationOrder.TryGetValue(descriptor.ExtendeeType, out list))
{
- declarationOrder.Add(descriptor.ExtendeeType, new List<FieldDescriptor>());
+ list = new List<FieldDescriptor>();
+ declarationOrder.Add(descriptor.ExtendeeType, list);
}
- declarationOrder[descriptor.ExtendeeType].Add(descriptor);
+ list.Add(descriptor);
}
extensionsByTypeInDeclarationOrder = declarationOrder
diff --git a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
index ddd671a..7324e3d 100644
--- a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
@@ -59,11 +59,32 @@
public OneofDescriptor ContainingOneof { get; }
/// <summary>
+ /// Returns the oneof containing this field if it's a "real" oneof, or <c>null</c> if either this
+ /// field is not part of a oneof, or the oneof is synthetic.
+ /// </summary>
+ public OneofDescriptor RealContainingOneof => ContainingOneof?.IsSynthetic == false ? ContainingOneof : null;
+
+ /// <summary>
/// The effective JSON name for this field. This is usually the lower-camel-cased form of the field name,
/// but can be overridden using the <c>json_name</c> option in the .proto file.
/// </summary>
public string JsonName { get; }
+ /// <summary>
+ /// Indicates whether this field supports presence, either implicitly (e.g. due to it being a message
+ /// type field) or explicitly via Has/Clear members. If this returns true, it is safe to call
+ /// <see cref="IFieldAccessor.Clear(IMessage)"/> and <see cref="IFieldAccessor.HasValue(IMessage)"/>
+ /// on this field's accessor with a suitable message.
+ /// </summary>
+ public bool HasPresence =>
+ Extension != null ? !Extension.IsRepeated
+ : IsRepeated ? false
+ : IsMap ? false
+ : FieldType == FieldType.Message ? true
+ // This covers "real oneof members" and "proto3 optional fields"
+ : ContainingOneof != null ? true
+ : File.Syntax == Syntax.Proto2;
+
internal FieldDescriptorProto Proto { get; }
/// <summary>
@@ -298,12 +319,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this field.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>FieldOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public FieldOptions GetOptions() => Proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value field option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<FieldOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
@@ -313,6 +343,7 @@
/// <summary>
/// Gets a repeated value field option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<FieldOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
@@ -388,7 +419,7 @@
File.DescriptorPool.AddFieldByNumber(this);
- if (ContainingType != null && ContainingType.Proto.HasOptions && ContainingType.Proto.Options.MessageSetWireFormat)
+ if (ContainingType != null && ContainingType.Proto.Options != null && ContainingType.Proto.Options.MessageSetWireFormat)
{
throw new DescriptorValidationException(this, "MessageSet format is not supported.");
}
diff --git a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
index 388a40b..88e4a9d 100644
--- a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
@@ -422,7 +422,8 @@
GeneratedClrTypeInfo generatedCodeInfo)
{
ExtensionRegistry registry = new ExtensionRegistry();
- AddAllExtensions(dependencies, generatedCodeInfo, registry);
+ registry.AddRange(GetAllExtensions(dependencies, generatedCodeInfo));
+
FileDescriptorProto proto;
try
{
@@ -445,9 +446,9 @@
}
}
- private static void AddAllExtensions(FileDescriptor[] dependencies, GeneratedClrTypeInfo generatedInfo, ExtensionRegistry registry)
+ private static IEnumerable<Extension> GetAllExtensions(FileDescriptor[] dependencies, GeneratedClrTypeInfo generatedInfo)
{
- registry.AddRange(dependencies.SelectMany(GetAllDependedExtensions).Concat(GetAllGeneratedExtensions(generatedInfo)).ToArray());
+ return dependencies.SelectMany(GetAllDependedExtensions).Distinct(ExtensionRegistry.ExtensionComparer.Instance).Concat(GetAllGeneratedExtensions(generatedInfo));
}
private static IEnumerable<Extension> GetAllGeneratedExtensions(GeneratedClrTypeInfo generated)
@@ -546,12 +547,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this file.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>FileOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public FileOptions GetOptions() => Proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value file option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<FileOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
@@ -561,6 +571,7 @@
/// <summary>
/// Gets a repeated value file option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<FileOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
diff --git a/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs b/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs
index b48c4f9..d73427b 100644
--- a/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs
@@ -59,7 +59,8 @@
object GetValue(IMessage message);
/// <summary>
- /// Indicates whether the field in the specified message is set. For proto3 fields, this throws an <see cref="InvalidOperationException"/>
+ /// Indicates whether the field in the specified message is set.
+ /// For proto3 fields that aren't explicitly optional, this throws an <see cref="InvalidOperationException"/>
/// </summary>
bool HasValue(IMessage message);
diff --git a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
index eda1965..7b5ab2f 100644
--- a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
@@ -80,6 +80,20 @@
(oneof, index) =>
new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index]));
+ int syntheticOneofCount = 0;
+ foreach (var oneof in Oneofs)
+ {
+ if (oneof.IsSynthetic)
+ {
+ syntheticOneofCount++;
+ }
+ else if (syntheticOneofCount != 0)
+ {
+ throw new ArgumentException("All synthetic oneofs should come after real oneofs");
+ }
+ }
+ RealOneofCount = Oneofs.Count - syntheticOneofCount;
+
NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(
proto.NestedType,
(type, index) =>
@@ -234,10 +248,20 @@
/// <value>
/// An unmodifiable list of the "oneof" field collections in this message type.
+ /// All "real" oneofs (where <see cref="OneofDescriptor.IsSynthetic"/> returns false)
+ /// come before synthetic ones.
/// </value>
public IList<OneofDescriptor> Oneofs { get; }
/// <summary>
+ /// The number of real "oneof" descriptors in this message type. Every element in <see cref="Oneofs"/>
+ /// with an index less than this will have a <see cref="OneofDescriptor.IsSynthetic"/> property value
+ /// of <c>false</c>; every element with an index greater than or equal to this will have a
+ /// <see cref="OneofDescriptor.IsSynthetic"/> property value of <c>true</c>.
+ /// </summary>
+ public int RealOneofCount { get; }
+
+ /// <summary>
/// Finds a field by field name.
/// </summary>
/// <param name="name">The unqualified name of the field (e.g. "foo").</param>
@@ -263,12 +287,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this message.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>MessageOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public MessageOptions GetOptions() => Proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value message option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<MessageOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
@@ -278,6 +311,7 @@
/// <summary>
/// Gets a repeated value message option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public Collections.RepeatedField<T> GetOption<T>(RepeatedExtension<MessageOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
diff --git a/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs
index 92250ba..8e15037 100644
--- a/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs
@@ -73,12 +73,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this method.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>MethodOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public MethodOptions GetOptions() => Proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value method option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<MethodOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
@@ -88,6 +97,7 @@
/// <summary>
/// Gets a repeated value method option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<MethodOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
diff --git a/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs
index f4bf628..4e040c1 100644
--- a/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs
@@ -43,19 +43,31 @@
{
private readonly Func<IMessage, int> caseDelegate;
private readonly Action<IMessage> clearDelegate;
- private OneofDescriptor descriptor;
- internal OneofAccessor(PropertyInfo caseProperty, MethodInfo clearMethod, OneofDescriptor descriptor)
+ private OneofAccessor(OneofDescriptor descriptor, Func<IMessage, int> caseDelegate, Action<IMessage> clearDelegate)
{
- if (!caseProperty.CanRead)
- {
- throw new ArgumentException("Cannot read from property");
- }
- this.descriptor = descriptor;
- caseDelegate = ReflectionUtil.CreateFuncIMessageInt32(caseProperty.GetGetMethod());
+ Descriptor = descriptor;
+ this.caseDelegate = caseDelegate;
+ this.clearDelegate = clearDelegate;
+ }
- this.descriptor = descriptor;
- clearDelegate = ReflectionUtil.CreateActionIMessage(clearMethod);
+ internal static OneofAccessor ForRegularOneof(
+ OneofDescriptor descriptor,
+ PropertyInfo caseProperty,
+ MethodInfo clearMethod) =>
+ new OneofAccessor(
+ descriptor,
+ ReflectionUtil.CreateFuncIMessageInt32(caseProperty.GetGetMethod()),
+ ReflectionUtil.CreateActionIMessage(clearMethod));
+
+ internal static OneofAccessor ForSyntheticOneof(OneofDescriptor descriptor)
+ {
+ // Note: descriptor.Fields will be null when this method is called, because we haven't
+ // cross-linked yet. But by the time the delgates are called by user code, all will be
+ // well. (That's why we capture the descriptor itself rather than a field.)
+ return new OneofAccessor(descriptor,
+ message => descriptor.Fields[0].Accessor.HasValue(message) ? descriptor.Fields[0].FieldNumber : 0,
+ message => descriptor.Fields[0].Accessor.Clear(message));
}
/// <summary>
@@ -64,15 +76,12 @@
/// <value>
/// The descriptor of the oneof.
/// </value>
- public OneofDescriptor Descriptor { get { return descriptor; } }
+ public OneofDescriptor Descriptor { get; }
/// <summary>
/// Clears the oneof in the specified message.
/// </summary>
- public void Clear(IMessage message)
- {
- clearDelegate(message);
- }
+ public void Clear(IMessage message) => clearDelegate(message);
/// <summary>
/// Indicates which field in the oneof is set for specified message
@@ -80,11 +89,9 @@
public FieldDescriptor GetCaseFieldDescriptor(IMessage message)
{
int fieldNumber = caseDelegate(message);
- if (fieldNumber > 0)
- {
- return descriptor.ContainingType.FindFieldByNumber(fieldNumber);
- }
- return null;
+ return fieldNumber > 0
+ ? Descriptor.ContainingType.FindFieldByNumber(fieldNumber)
+ : null;
}
}
}
diff --git a/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
index 1e30b92..0df4f53 100644
--- a/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
@@ -33,6 +33,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Linq;
using Google.Protobuf.Collections;
using Google.Protobuf.Compatibility;
@@ -54,8 +55,13 @@
{
this.proto = proto;
containingType = parent;
-
file.DescriptorPool.AddSymbol(this);
+
+ // It's useful to determine whether or not this is a synthetic oneof before cross-linking. That means
+ // diving into the proto directly rather than using FieldDescriptor, but that's okay.
+ var firstFieldInOneof = parent.Proto.Field.FirstOrDefault(fieldProto => fieldProto.OneofIndex == index);
+ IsSynthetic = firstFieldInOneof?.Proto3Optional ?? false;
+
accessor = CreateAccessor(clrName);
}
@@ -84,6 +90,12 @@
public IList<FieldDescriptor> Fields { get { return fields; } }
/// <summary>
+ /// Returns <c>true</c> if this oneof is a synthetic oneof containing a proto3 optional field;
+ /// <c>false</c> otherwise.
+ /// </summary>
+ public bool IsSynthetic { get; }
+
+ /// <summary>
/// Gets an accessor for reflective access to the values associated with the oneof
/// in a particular message.
/// </summary>
@@ -105,12 +117,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this oneof.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions method.")]
public CustomOptions CustomOptions => new CustomOptions(proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>OneofOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public OneofOptions GetOptions() => proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value oneof option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<OneofOptions, T> extension)
{
var value = proto.Options.GetExtension(extension);
@@ -120,6 +141,7 @@
/// <summary>
/// Gets a repeated value oneof option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<OneofOptions, T> extension)
{
return proto.Options.GetExtension(extension).Clone();
@@ -146,18 +168,28 @@
{
return null;
}
- var caseProperty = containingType.ClrType.GetProperty(clrName + "Case");
- if (caseProperty == null)
+ if (IsSynthetic)
{
- throw new DescriptorValidationException(this, $"Property {clrName}Case not found in {containingType.ClrType}");
+ return OneofAccessor.ForSyntheticOneof(this);
}
- var clearMethod = containingType.ClrType.GetMethod("Clear" + clrName);
- if (clearMethod == null)
+ else
{
- throw new DescriptorValidationException(this, $"Method Clear{clrName} not found in {containingType.ClrType}");
+ var caseProperty = containingType.ClrType.GetProperty(clrName + "Case");
+ if (caseProperty == null)
+ {
+ throw new DescriptorValidationException(this, $"Property {clrName}Case not found in {containingType.ClrType}");
+ }
+ if (!caseProperty.CanRead)
+ {
+ throw new ArgumentException($"Cannot read from property {clrName}Case in {containingType.ClrType}");
+ }
+ var clearMethod = containingType.ClrType.GetMethod("Clear" + clrName);
+ if (clearMethod == null)
+ {
+ throw new DescriptorValidationException(this, $"Method Clear{clrName} not found in {containingType.ClrType}");
+ }
+ return OneofAccessor.ForRegularOneof(this, caseProperty, clearMethod);
}
-
- return new OneofAccessor(caseProperty, clearMethod, this);
}
}
}
diff --git a/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs
index ba310ad..dab348b 100644
--- a/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs
@@ -85,7 +85,7 @@
/// Finds a method by name.
/// </summary>
/// <param name="name">The unqualified name of the method (e.g. "Foo").</param>
- /// <returns>The method's decsriptor, or null if not found.</returns>
+ /// <returns>The method's descriptor, or null if not found.</returns>
public MethodDescriptor FindMethodByName(String name)
{
return File.DescriptorPool.FindSymbol<MethodDescriptor>(FullName + "." + name);
@@ -94,12 +94,21 @@
/// <summary>
/// The (possibly empty) set of custom options for this service.
/// </summary>
- [Obsolete("CustomOptions are obsolete. Use GetOption")]
+ [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
+ /// The <c>ServiceOptions</c>, defined in <c>descriptor.proto</c>.
+ /// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
+ /// Custom options can be retrieved as extensions of the returned message.
+ /// NOTE: A defensive copy is created each time this property is retrieved.
+ /// </summary>
+ public ServiceOptions GetOptions() => Proto.Options?.Clone();
+
+ /// <summary>
/// Gets a single value service option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<ServiceOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
@@ -109,6 +118,7 @@
/// <summary>
/// Gets a repeated value service option for this descriptor
/// </summary>
+ [Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<ServiceOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
diff --git a/csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs b/csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs
index de10226..07d84d7 100644
--- a/csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs
@@ -57,49 +57,68 @@
throw new ArgumentException("Not all required properties/methods available");
}
setValueDelegate = ReflectionUtil.CreateActionIMessageObject(property.GetSetMethod());
- if (descriptor.File.Syntax == Syntax.Proto3)
+
+ // Note: this looks worrying in that we access the containing oneof, which isn't valid until cross-linking
+ // is complete... but field accessors aren't created until after cross-linking.
+ // The oneof itself won't be cross-linked yet, but that's okay: the oneof accessor is created
+ // earlier.
+
+ // Message fields always support presence, via null checks.
+ if (descriptor.FieldType == FieldType.Message)
{
- hasDelegate = message => {
- throw new InvalidOperationException("HasValue is not implemented for proto3 fields");
+ hasDelegate = message => GetValue(message) != null;
+ clearDelegate = message => SetValue(message, null);
+ }
+ // Oneof fields always support presence, via case checks.
+ // Note that clearing the field is a no-op unless that specific field is the current "case".
+ else if (descriptor.RealContainingOneof != null)
+ {
+ var oneofAccessor = descriptor.RealContainingOneof.Accessor;
+ hasDelegate = message => oneofAccessor.GetCaseFieldDescriptor(message) == descriptor;
+ clearDelegate = message =>
+ {
+ // Clear on a field only affects the oneof itself if the current case is the field we're accessing.
+ if (oneofAccessor.GetCaseFieldDescriptor(message) == descriptor)
+ {
+ oneofAccessor.Clear(message);
+ }
};
+ }
+ // Primitive fields always support presence in proto2, and support presence in proto3 for optional fields.
+ else if (descriptor.File.Syntax == Syntax.Proto2 || descriptor.Proto.Proto3Optional)
+ {
+ MethodInfo hasMethod = property.DeclaringType.GetRuntimeProperty("Has" + property.Name).GetMethod;
+ if (hasMethod == null)
+ {
+ throw new ArgumentException("Not all required properties/methods are available");
+ }
+ hasDelegate = ReflectionUtil.CreateFuncIMessageBool(hasMethod);
+ MethodInfo clearMethod = property.DeclaringType.GetRuntimeMethod("Clear" + property.Name, ReflectionUtil.EmptyTypes);
+ if (clearMethod == null)
+ {
+ throw new ArgumentException("Not all required properties/methods are available");
+ }
+ clearDelegate = ReflectionUtil.CreateActionIMessage(clearMethod);
+ }
+ // What's left?
+ // Primitive proto3 fields without the optional keyword, which aren't in oneofs.
+ else
+ {
+ hasDelegate = message => { throw new InvalidOperationException("Presence is not implemented for this field"); };
+
+ // While presence isn't supported, clearing still is; it's just setting to a default value.
var clrType = property.PropertyType;
- // TODO: Validate that this is a reasonable single field? (Should be a value type, a message type, or string/ByteString.)
object defaultValue =
- descriptor.FieldType == FieldType.Message ? null
- : clrType == typeof(string) ? ""
+ clrType == typeof(string) ? ""
: clrType == typeof(ByteString) ? ByteString.Empty
: Activator.CreateInstance(clrType);
clearDelegate = message => SetValue(message, defaultValue);
}
- else
- {
- MethodInfo hasMethod = property.DeclaringType.GetRuntimeProperty("Has" + property.Name).GetMethod;
- if (hasMethod == null) {
- throw new ArgumentException("Not all required properties/methods are available");
- }
- hasDelegate = ReflectionUtil.CreateFuncIMessageBool(hasMethod);
- MethodInfo clearMethod = property.DeclaringType.GetRuntimeMethod("Clear" + property.Name, ReflectionUtil.EmptyTypes);
- if (clearMethod == null) {
- throw new ArgumentException("Not all required properties/methods are available");
- }
- clearDelegate = ReflectionUtil.CreateActionIMessage(clearMethod);
- }
}
- public override void Clear(IMessage message)
- {
- clearDelegate(message);
- }
-
- public override bool HasValue(IMessage message)
- {
- return hasDelegate(message);
- }
-
- public override void SetValue(IMessage message, object value)
- {
- setValueDelegate(message, value);
- }
+ public override void Clear(IMessage message) => clearDelegate(message);
+ public override bool HasValue(IMessage message) => hasDelegate(message);
+ public override void SetValue(IMessage message, object value) => setValueDelegate(message, value);
}
}
diff --git a/csharp/src/Google.Protobuf/SegmentedBufferHelper.cs b/csharp/src/Google.Protobuf/SegmentedBufferHelper.cs
new file mode 100644
index 0000000..b5441d3
--- /dev/null
+++ b/csharp/src/Google.Protobuf/SegmentedBufferHelper.cs
@@ -0,0 +1,296 @@
+#region Copyright notice and license
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#endregion
+
+using System;
+using System.Buffers;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Security;
+
+namespace Google.Protobuf
+{
+ /// <summary>
+ /// Abstraction for reading from a stream / read only sequence.
+ /// Parsing from the buffer is a loop of reading from current buffer / refreshing the buffer once done.
+ /// </summary>
+ [SecuritySafeCritical]
+ internal struct SegmentedBufferHelper
+ {
+ private int? totalLength;
+ private ReadOnlySequence<byte>.Enumerator readOnlySequenceEnumerator;
+ private CodedInputStream codedInputStream;
+
+ /// <summary>
+ /// Initialize an instance with a coded input stream.
+ /// This approach is faster than using a constructor because the instance to initialize is passed by reference
+ /// and we can write directly into it without copying.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Initialize(CodedInputStream codedInputStream, out SegmentedBufferHelper instance)
+ {
+ instance.totalLength = codedInputStream.InternalInputStream == null ? (int?)codedInputStream.InternalBuffer.Length : null;
+ instance.readOnlySequenceEnumerator = default;
+ instance.codedInputStream = codedInputStream;
+ }
+
+ /// <summary>
+ /// Initialize an instance with a read only sequence.
+ /// This approach is faster than using a constructor because the instance to initialize is passed by reference
+ /// and we can write directly into it without copying.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void Initialize(ReadOnlySequence<byte> sequence, out SegmentedBufferHelper instance, out ReadOnlySpan<byte> firstSpan)
+ {
+ instance.codedInputStream = null;
+ if (sequence.IsSingleSegment)
+ {
+ firstSpan = sequence.First.Span;
+ instance.totalLength = firstSpan.Length;
+ instance.readOnlySequenceEnumerator = default;
+ }
+ else
+ {
+ instance.readOnlySequenceEnumerator = sequence.GetEnumerator();
+ instance.totalLength = (int) sequence.Length;
+
+ // set firstSpan to the first segment
+ instance.readOnlySequenceEnumerator.MoveNext();
+ firstSpan = instance.readOnlySequenceEnumerator.Current.Span;
+ }
+ }
+
+ public bool RefillBuffer(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, bool mustSucceed)
+ {
+ if (codedInputStream != null)
+ {
+ return RefillFromCodedInputStream(ref buffer, ref state, mustSucceed);
+ }
+ else
+ {
+ return RefillFromReadOnlySequence(ref buffer, ref state, mustSucceed);
+ }
+ }
+
+ public int? TotalLength => totalLength;
+
+ public CodedInputStream CodedInputStream => codedInputStream;
+
+ /// <summary>
+ /// Sets currentLimit to (current position) + byteLimit. This is called
+ /// when descending into a length-delimited embedded message. The previous
+ /// limit is returned.
+ /// </summary>
+ /// <returns>The old limit.</returns>
+ public static int PushLimit(ref ParserInternalState state, int byteLimit)
+ {
+ if (byteLimit < 0)
+ {
+ throw InvalidProtocolBufferException.NegativeSize();
+ }
+ byteLimit += state.totalBytesRetired + state.bufferPos;
+ int oldLimit = state.currentLimit;
+ if (byteLimit > oldLimit)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ state.currentLimit = byteLimit;
+
+ RecomputeBufferSizeAfterLimit(ref state);
+
+ return oldLimit;
+ }
+
+ /// <summary>
+ /// Discards the current limit, returning the previous limit.
+ /// </summary>
+ public static void PopLimit(ref ParserInternalState state, int oldLimit)
+ {
+ state.currentLimit = oldLimit;
+ RecomputeBufferSizeAfterLimit(ref state);
+ }
+
+ /// <summary>
+ /// Returns whether or not all the data before the limit has been read.
+ /// </summary>
+ /// <returns></returns>
+ public static bool IsReachedLimit(ref ParserInternalState state)
+ {
+ if (state.currentLimit == int.MaxValue)
+ {
+ return false;
+ }
+ int currentAbsolutePosition = state.totalBytesRetired + state.bufferPos;
+ return currentAbsolutePosition >= state.currentLimit;
+ }
+
+ /// <summary>
+ /// 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
+ /// the stream has reached a limit created using PushLimit.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool IsAtEnd(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
+ {
+ return state.bufferPos == state.bufferSize && !state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, false);
+ }
+
+ private bool RefillFromReadOnlySequence(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, bool mustSucceed)
+ {
+ CheckCurrentBufferIsEmpty(ref state);
+
+ if (state.totalBytesRetired + state.bufferSize == state.currentLimit)
+ {
+ // Oops, we hit a limit.
+ if (mustSucceed)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ state.totalBytesRetired += state.bufferSize;
+
+ state.bufferPos = 0;
+ state.bufferSize = 0;
+ while (readOnlySequenceEnumerator.MoveNext())
+ {
+ buffer = readOnlySequenceEnumerator.Current.Span;
+ state.bufferSize = buffer.Length;
+ if (buffer.Length != 0)
+ {
+ break;
+ }
+ }
+
+ if (state.bufferSize == 0)
+ {
+ if (mustSucceed)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else
+ {
+ RecomputeBufferSizeAfterLimit(ref state);
+ int totalBytesRead =
+ state.totalBytesRetired + state.bufferSize + state.bufferSizeAfterLimit;
+ if (totalBytesRead < 0 || totalBytesRead > state.sizeLimit)
+ {
+ throw InvalidProtocolBufferException.SizeLimitExceeded();
+ }
+ return true;
+ }
+ }
+
+ private bool RefillFromCodedInputStream(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state, bool mustSucceed)
+ {
+ CheckCurrentBufferIsEmpty(ref state);
+
+ if (state.totalBytesRetired + state.bufferSize == state.currentLimit)
+ {
+ // Oops, we hit a limit.
+ if (mustSucceed)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ Stream input = codedInputStream.InternalInputStream;
+
+ state.totalBytesRetired += state.bufferSize;
+
+ state.bufferPos = 0;
+ state.bufferSize = (input == null) ? 0 : input.Read(codedInputStream.InternalBuffer, 0, buffer.Length);
+ if (state.bufferSize < 0)
+ {
+ throw new InvalidOperationException("Stream.Read returned a negative count");
+ }
+ if (state.bufferSize == 0)
+ {
+ if (mustSucceed)
+ {
+ throw InvalidProtocolBufferException.TruncatedMessage();
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else
+ {
+ RecomputeBufferSizeAfterLimit(ref state);
+ int totalBytesRead =
+ state.totalBytesRetired + state.bufferSize + state.bufferSizeAfterLimit;
+ if (totalBytesRead < 0 || totalBytesRead > state.sizeLimit)
+ {
+ throw InvalidProtocolBufferException.SizeLimitExceeded();
+ }
+ return true;
+ }
+ }
+
+ private static void RecomputeBufferSizeAfterLimit(ref ParserInternalState state)
+ {
+ state.bufferSize += state.bufferSizeAfterLimit;
+ int bufferEnd = state.totalBytesRetired + state.bufferSize;
+ if (bufferEnd > state.currentLimit)
+ {
+ // Limit is in current buffer.
+ state.bufferSizeAfterLimit = bufferEnd - state.currentLimit;
+ state.bufferSize -= state.bufferSizeAfterLimit;
+ }
+ else
+ {
+ state.bufferSizeAfterLimit = 0;
+ }
+ }
+
+ private static void CheckCurrentBufferIsEmpty(ref ParserInternalState state)
+ {
+ if (state.bufferPos < state.bufferSize)
+ {
+ throw new InvalidOperationException("RefillBuffer() called when buffer wasn't empty.");
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/UnknownFieldSet.cs b/csharp/src/Google.Protobuf/UnknownFieldSet.cs
index d136cf1..9ebe704 100644
--- a/csharp/src/Google.Protobuf/UnknownFieldSet.cs
+++ b/csharp/src/Google.Protobuf/UnknownFieldSet.cs
@@ -33,6 +33,7 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Security;
using Google.Protobuf.Reflection;
namespace Google.Protobuf
@@ -176,51 +177,47 @@
fields[number] = field;
return this;
}
-
+
/// <summary>
- /// Parse a single field from <paramref name="input"/> and merge it
+ /// Parse a single field from <paramref name="ctx"/> and merge it
/// into this set.
/// </summary>
- /// <param name="input">The coded input stream containing the field</param>
+ /// <param name="ctx">The parse context from which to read the field</param>
/// <returns>false if the tag is an "end group" tag, true otherwise</returns>
- private bool MergeFieldFrom(CodedInputStream input)
+ private bool MergeFieldFrom(ref ParseContext ctx)
{
- uint tag = input.LastTag;
+ uint tag = ctx.LastTag;
int number = WireFormat.GetTagFieldNumber(tag);
switch (WireFormat.GetTagWireType(tag))
{
case WireFormat.WireType.Varint:
{
- ulong uint64 = input.ReadUInt64();
+ ulong uint64 = ctx.ReadUInt64();
GetOrAddField(number).AddVarint(uint64);
return true;
}
case WireFormat.WireType.Fixed32:
{
- uint uint32 = input.ReadFixed32();
+ uint uint32 = ctx.ReadFixed32();
GetOrAddField(number).AddFixed32(uint32);
return true;
}
case WireFormat.WireType.Fixed64:
{
- ulong uint64 = input.ReadFixed64();
+ ulong uint64 = ctx.ReadFixed64();
GetOrAddField(number).AddFixed64(uint64);
return true;
}
case WireFormat.WireType.LengthDelimited:
{
- ByteString bytes = input.ReadBytes();
+ ByteString bytes = ctx.ReadBytes();
GetOrAddField(number).AddLengthDelimited(bytes);
return true;
}
case WireFormat.WireType.StartGroup:
{
- uint endTag = WireFormat.MakeTag(number, WireFormat.WireType.EndGroup);
UnknownFieldSet set = new UnknownFieldSet();
- while (input.ReadTag() != endTag)
- {
- set.MergeFieldFrom(input);
- }
+ ParsingPrimitivesMessages.ReadGroup(ref ctx, number, set);
GetOrAddField(number).AddGroup(set);
return true;
}
@@ -233,6 +230,22 @@
}
}
+ internal void MergeGroupFrom(ref ParseContext ctx)
+ {
+ while (true)
+ {
+ uint tag = ctx.ReadTag();
+ if (tag == 0)
+ {
+ break;
+ }
+ if (!MergeFieldFrom(ref ctx))
+ {
+ break;
+ }
+ }
+ }
+
/// <summary>
/// Create a new UnknownFieldSet if unknownFields is null.
/// Parse a single field from <paramref name="input"/> and merge it
@@ -245,21 +258,45 @@
public static UnknownFieldSet MergeFieldFrom(UnknownFieldSet unknownFields,
CodedInputStream input)
{
- if (input.DiscardUnknownFields)
+ ParseContext.Initialize(input, out ParseContext ctx);
+ try
{
- input.SkipLastField();
+ return MergeFieldFrom(unknownFields, ref ctx);
+ }
+ finally
+ {
+ ctx.CopyStateTo(input);
+ }
+ }
+
+ /// <summary>
+ /// Create a new UnknownFieldSet if unknownFields is null.
+ /// Parse a single field from <paramref name="ctx"/> and merge it
+ /// into unknownFields. If <paramref name="ctx"/> is configured to discard unknown fields,
+ /// <paramref name="unknownFields"/> will be returned as-is and the field will be skipped.
+ /// </summary>
+ /// <param name="unknownFields">The UnknownFieldSet which need to be merged</param>
+ /// <param name="ctx">The parse context from which to read the field</param>
+ /// <returns>The merged UnknownFieldSet</returns>
+ [SecuritySafeCritical]
+ public static UnknownFieldSet MergeFieldFrom(UnknownFieldSet unknownFields,
+ ref ParseContext ctx)
+ {
+ if (ctx.DiscardUnknownFields)
+ {
+ ParsingPrimitivesMessages.SkipLastField(ref ctx.buffer, ref ctx.state);
return unknownFields;
}
if (unknownFields == null)
{
unknownFields = new UnknownFieldSet();
}
- if (!unknownFields.MergeFieldFrom(input))
- {
- throw new InvalidProtocolBufferException("Merge an unknown field of end-group tag, indicating that the corresponding start-group was missing."); // match the old code-gen
+ if (!unknownFields.MergeFieldFrom(ref ctx))
+ {
+ throw new InvalidProtocolBufferException("Merge an unknown field of end-group tag, indicating that the corresponding start-group was missing."); // match the old code-gen
}
return unknownFields;
- }
+ }
/// <summary>
/// Merges the fields from <paramref name="other"/> into this set.
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
index 09e0e29..c4e7447 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
@@ -119,7 +119,7 @@
/// "value": "1.212s"
/// }
/// </summary>
- public sealed partial class Any : pb::IMessage<Any> {
+ public sealed partial class Any : pb::IMessage<Any>, pb::IBufferMessage {
private static readonly pb::MessageParser<Any> _parser = new pb::MessageParser<Any>(() => new Any());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -288,11 +288,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
TypeUrl = input.ReadString();
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
index 06a9905..1f29224 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
@@ -64,7 +64,7 @@
/// this message itself. See https://cloud.google.com/apis/design/glossary for
/// detailed terminology.
/// </summary>
- public sealed partial class Api : pb::IMessage<Api> {
+ public sealed partial class Api : pb::IMessage<Api>, pb::IBufferMessage {
private static readonly pb::MessageParser<Api> _parser = new pb::MessageParser<Api>(() => new Api());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -341,22 +341,27 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
- methods_.AddEntriesFrom(input, _repeated_methods_codec);
+ methods_.AddEntriesFrom(ref input, _repeated_methods_codec);
break;
}
case 26: {
- options_.AddEntriesFrom(input, _repeated_options_codec);
+ options_.AddEntriesFrom(ref input, _repeated_options_codec);
break;
}
case 34: {
@@ -371,7 +376,7 @@
break;
}
case 50: {
- mixins_.AddEntriesFrom(input, _repeated_mixins_codec);
+ mixins_.AddEntriesFrom(ref input, _repeated_mixins_codec);
break;
}
case 56: {
@@ -387,7 +392,7 @@
/// <summary>
/// Method represents a method of an API interface.
/// </summary>
- public sealed partial class Method : pb::IMessage<Method> {
+ public sealed partial class Method : pb::IMessage<Method>, pb::IBufferMessage {
private static readonly pb::MessageParser<Method> _parser = new pb::MessageParser<Method>(() => new Method());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -657,11 +662,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -684,7 +694,7 @@
break;
}
case 50: {
- options_.AddEntriesFrom(input, _repeated_options_codec);
+ options_.AddEntriesFrom(ref input, _repeated_options_codec);
break;
}
case 56: {
@@ -777,7 +787,7 @@
/// ...
/// }
/// </summary>
- public sealed partial class Mixin : pb::IMessage<Mixin> {
+ public sealed partial class Mixin : pb::IMessage<Mixin>, pb::IBufferMessage {
private static readonly pb::MessageParser<Mixin> _parser = new pb::MessageParser<Mixin>(() => new Mixin());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -921,11 +931,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
index f0078c4..804b82f 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
@@ -100,7 +100,7 @@
/// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
/// microsecond should be expressed in JSON format as "3.000001s".
/// </summary>
- public sealed partial class Duration : pb::IMessage<Duration> {
+ public sealed partial class Duration : pb::IMessage<Duration>, pb::IBufferMessage {
private static readonly pb::MessageParser<Duration> _parser = new pb::MessageParser<Duration>(() => new Duration());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -250,11 +250,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Seconds = input.ReadInt64();
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs
index fa435cd..f73c345 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs
@@ -50,7 +50,7 @@
///
/// The JSON representation for `Empty` is empty JSON object `{}`.
/// </summary>
- public sealed partial class Empty : pb::IMessage<Empty> {
+ public sealed partial class Empty : pb::IMessage<Empty>, pb::IBufferMessage {
private static readonly pb::MessageParser<Empty> _parser = new pb::MessageParser<Empty>(() => new Empty());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -139,11 +139,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
index 00e1e9f..25a2f05 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
@@ -240,7 +240,7 @@
/// request should verify the included field paths, and return an
/// `INVALID_ARGUMENT` error if any path is unmappable.
/// </summary>
- public sealed partial class FieldMask : pb::IMessage<FieldMask> {
+ public sealed partial class FieldMask : pb::IMessage<FieldMask>, pb::IBufferMessage {
private static readonly pb::MessageParser<FieldMask> _parser = new pb::MessageParser<FieldMask>(() => new FieldMask());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -348,14 +348,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- paths_.AddEntriesFrom(input, _repeated_paths_codec);
+ paths_.AddEntriesFrom(ref input, _repeated_paths_codec);
break;
}
}
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs b/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs
index d707619..99d40a5 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs
@@ -44,7 +44,7 @@
/// `SourceContext` represents information about the source of a
/// protobuf element, like the file in which it is defined.
/// </summary>
- public sealed partial class SourceContext : pb::IMessage<SourceContext> {
+ public sealed partial class SourceContext : pb::IMessage<SourceContext>, pb::IBufferMessage {
private static readonly pb::MessageParser<SourceContext> _parser = new pb::MessageParser<SourceContext>(() => new SourceContext());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -161,11 +161,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
FileName = input.ReadString();
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
index b1dbe23..8405742 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
@@ -77,7 +77,7 @@
///
/// The JSON representation for `Struct` is JSON object.
/// </summary>
- public sealed partial class Struct : pb::IMessage<Struct> {
+ public sealed partial class Struct : pb::IMessage<Struct>, pb::IBufferMessage {
private static readonly pb::MessageParser<Struct> _parser = new pb::MessageParser<Struct>(() => new Struct());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -185,14 +185,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- fields_.AddEntriesFrom(input, _map_fields_codec);
+ fields_.AddEntriesFrom(ref input, _map_fields_codec);
break;
}
}
@@ -209,7 +214,7 @@
///
/// The JSON representation for `Value` is JSON value.
/// </summary>
- public sealed partial class Value : pb::IMessage<Value> {
+ public sealed partial class Value : pb::IMessage<Value>, pb::IBufferMessage {
private static readonly pb::MessageParser<Value> _parser = new pb::MessageParser<Value>(() => new Value());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -509,11 +514,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
kind_ = input.ReadEnum();
@@ -561,7 +571,7 @@
///
/// The JSON representation for `ListValue` is JSON array.
/// </summary>
- public sealed partial class ListValue : pb::IMessage<ListValue> {
+ public sealed partial class ListValue : pb::IMessage<ListValue>, pb::IBufferMessage {
private static readonly pb::MessageParser<ListValue> _parser = new pb::MessageParser<ListValue>(() => new ListValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -669,14 +679,19 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
- values_.AddEntriesFrom(input, _repeated_values_codec);
+ values_.AddEntriesFrom(ref input, _repeated_values_codec);
break;
}
}
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
index 12f4812..31cbe95 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
@@ -123,7 +123,7 @@
/// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
/// ) to obtain a formatter capable of generating timestamps in this format.
/// </summary>
- public sealed partial class Timestamp : pb::IMessage<Timestamp> {
+ public sealed partial class Timestamp : pb::IMessage<Timestamp>, pb::IBufferMessage {
private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -271,11 +271,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Seconds = input.ReadInt64();
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
index bfd4b8e..3c074f8 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
@@ -94,7 +94,7 @@
/// <summary>
/// A protocol buffer message type.
/// </summary>
- public sealed partial class Type : pb::IMessage<Type> {
+ public sealed partial class Type : pb::IMessage<Type>, pb::IBufferMessage {
private static readonly pb::MessageParser<Type> _parser = new pb::MessageParser<Type>(() => new Type());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -324,26 +324,31 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
- fields_.AddEntriesFrom(input, _repeated_fields_codec);
+ fields_.AddEntriesFrom(ref input, _repeated_fields_codec);
break;
}
case 26: {
- oneofs_.AddEntriesFrom(input, _repeated_oneofs_codec);
+ oneofs_.AddEntriesFrom(ref input, _repeated_oneofs_codec);
break;
}
case 34: {
- options_.AddEntriesFrom(input, _repeated_options_codec);
+ options_.AddEntriesFrom(ref input, _repeated_options_codec);
break;
}
case 42: {
@@ -366,7 +371,7 @@
/// <summary>
/// A single field of a message type.
/// </summary>
- public sealed partial class Field : pb::IMessage<Field> {
+ public sealed partial class Field : pb::IMessage<Field>, pb::IBufferMessage {
private static readonly pb::MessageParser<Field> _parser = new pb::MessageParser<Field>(() => new Field());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -719,11 +724,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Kind = (global::Google.Protobuf.WellKnownTypes.Field.Types.Kind) input.ReadEnum();
@@ -754,7 +764,7 @@
break;
}
case 74: {
- options_.AddEntriesFrom(input, _repeated_options_codec);
+ options_.AddEntriesFrom(ref input, _repeated_options_codec);
break;
}
case 82: {
@@ -885,7 +895,7 @@
/// <summary>
/// Enum type definition.
/// </summary>
- public sealed partial class Enum : pb::IMessage<Enum> {
+ public sealed partial class Enum : pb::IMessage<Enum>, pb::IBufferMessage {
private static readonly pb::MessageParser<Enum> _parser = new pb::MessageParser<Enum>(() => new Enum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1096,22 +1106,27 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
- enumvalue_.AddEntriesFrom(input, _repeated_enumvalue_codec);
+ enumvalue_.AddEntriesFrom(ref input, _repeated_enumvalue_codec);
break;
}
case 26: {
- options_.AddEntriesFrom(input, _repeated_options_codec);
+ options_.AddEntriesFrom(ref input, _repeated_options_codec);
break;
}
case 34: {
@@ -1134,7 +1149,7 @@
/// <summary>
/// Enum value definition.
/// </summary>
- public sealed partial class EnumValue : pb::IMessage<EnumValue> {
+ public sealed partial class EnumValue : pb::IMessage<EnumValue>, pb::IBufferMessage {
private static readonly pb::MessageParser<EnumValue> _parser = new pb::MessageParser<EnumValue>(() => new EnumValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1296,11 +1311,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
@@ -1311,7 +1331,7 @@
break;
}
case 26: {
- options_.AddEntriesFrom(input, _repeated_options_codec);
+ options_.AddEntriesFrom(ref input, _repeated_options_codec);
break;
}
}
@@ -1324,7 +1344,7 @@
/// A protocol buffer option, which can be attached to a message, field,
/// enumeration, etc.
/// </summary>
- public sealed partial class Option : pb::IMessage<Option> {
+ public sealed partial class Option : pb::IMessage<Option>, pb::IBufferMessage {
private static readonly pb::MessageParser<Option> _parser = new pb::MessageParser<Option>(() => new Option());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1476,11 +1496,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs
index 556af3c..41313fc 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs
@@ -57,7 +57,7 @@
///
/// The JSON representation for `DoubleValue` is JSON number.
/// </summary>
- public sealed partial class DoubleValue : pb::IMessage<DoubleValue> {
+ public sealed partial class DoubleValue : pb::IMessage<DoubleValue>, pb::IBufferMessage {
private static readonly pb::MessageParser<DoubleValue> _parser = new pb::MessageParser<DoubleValue>(() => new DoubleValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -173,11 +173,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 9: {
Value = input.ReadDouble();
@@ -194,7 +199,7 @@
///
/// The JSON representation for `FloatValue` is JSON number.
/// </summary>
- public sealed partial class FloatValue : pb::IMessage<FloatValue> {
+ public sealed partial class FloatValue : pb::IMessage<FloatValue>, pb::IBufferMessage {
private static readonly pb::MessageParser<FloatValue> _parser = new pb::MessageParser<FloatValue>(() => new FloatValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -310,11 +315,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 13: {
Value = input.ReadFloat();
@@ -331,7 +341,7 @@
///
/// The JSON representation for `Int64Value` is JSON string.
/// </summary>
- public sealed partial class Int64Value : pb::IMessage<Int64Value> {
+ public sealed partial class Int64Value : pb::IMessage<Int64Value>, pb::IBufferMessage {
private static readonly pb::MessageParser<Int64Value> _parser = new pb::MessageParser<Int64Value>(() => new Int64Value());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -447,11 +457,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Value = input.ReadInt64();
@@ -468,7 +483,7 @@
///
/// The JSON representation for `UInt64Value` is JSON string.
/// </summary>
- public sealed partial class UInt64Value : pb::IMessage<UInt64Value> {
+ public sealed partial class UInt64Value : pb::IMessage<UInt64Value>, pb::IBufferMessage {
private static readonly pb::MessageParser<UInt64Value> _parser = new pb::MessageParser<UInt64Value>(() => new UInt64Value());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -584,11 +599,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Value = input.ReadUInt64();
@@ -605,7 +625,7 @@
///
/// The JSON representation for `Int32Value` is JSON number.
/// </summary>
- public sealed partial class Int32Value : pb::IMessage<Int32Value> {
+ public sealed partial class Int32Value : pb::IMessage<Int32Value>, pb::IBufferMessage {
private static readonly pb::MessageParser<Int32Value> _parser = new pb::MessageParser<Int32Value>(() => new Int32Value());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -721,11 +741,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Value = input.ReadInt32();
@@ -742,7 +767,7 @@
///
/// The JSON representation for `UInt32Value` is JSON number.
/// </summary>
- public sealed partial class UInt32Value : pb::IMessage<UInt32Value> {
+ public sealed partial class UInt32Value : pb::IMessage<UInt32Value>, pb::IBufferMessage {
private static readonly pb::MessageParser<UInt32Value> _parser = new pb::MessageParser<UInt32Value>(() => new UInt32Value());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -858,11 +883,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Value = input.ReadUInt32();
@@ -879,7 +909,7 @@
///
/// The JSON representation for `BoolValue` is JSON `true` and `false`.
/// </summary>
- public sealed partial class BoolValue : pb::IMessage<BoolValue> {
+ public sealed partial class BoolValue : pb::IMessage<BoolValue>, pb::IBufferMessage {
private static readonly pb::MessageParser<BoolValue> _parser = new pb::MessageParser<BoolValue>(() => new BoolValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -995,11 +1025,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Value = input.ReadBool();
@@ -1016,7 +1051,7 @@
///
/// The JSON representation for `StringValue` is JSON string.
/// </summary>
- public sealed partial class StringValue : pb::IMessage<StringValue> {
+ public sealed partial class StringValue : pb::IMessage<StringValue>, pb::IBufferMessage {
private static readonly pb::MessageParser<StringValue> _parser = new pb::MessageParser<StringValue>(() => new StringValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1132,11 +1167,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Value = input.ReadString();
@@ -1153,7 +1193,7 @@
///
/// The JSON representation for `BytesValue` is JSON string.
/// </summary>
- public sealed partial class BytesValue : pb::IMessage<BytesValue> {
+ public sealed partial class BytesValue : pb::IMessage<BytesValue>, pb::IBufferMessage {
private static readonly pb::MessageParser<BytesValue> _parser = new pb::MessageParser<BytesValue>(() => new BytesValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -1269,11 +1309,16 @@
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
+ input.ReadRawMessage(this);
+ }
+
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
- _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
+ _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Value = input.ReadBytes();
diff --git a/docs/field_presence.md b/docs/field_presence.md
new file mode 100644
index 0000000..4ce7785
--- /dev/null
+++ b/docs/field_presence.md
@@ -0,0 +1,476 @@
+# Application note: Field presence
+
+This application note explains the various presence tracking disciplines for protobuf fields. It also explains how to enable experimental support for explicit presence tracking for singular proto3 fields with basic types.
+
+## Background
+
+_Field presence_ is the notion of whether a protobuf field has a value. There are two different manifestations of presence for protobufs: _no presence_, where the generated message API stores field values (only), and _explicit presence_, where the API also stores whether or not a field has been set.
+
+Historically, proto2 has mostly followed _explicit presence_, while proto3 exposes only _no presence_ semantics. Singular proto3 fields of basic types (numeric, string, bytes, and enums) which are defined with the `optional` label have _explicit presence_, like proto2 (this is an experimental feature added as of release 3.12, and must be enabled by passing a flag to `protoc`).
+
+### Presence disciplines
+
+_Presence disciplines_ define the semantics for translating between the _API representation_ and the _serialized representation_. The _no presence_ discipline relies upon the field value itself to make decisions at (de)serialization time, while the _explicit presence_ discipline relies upon the explicit tracking state instead.
+
+### Presence in _tag-value stream_ (wire format) serialization
+
+The wire format is a stream of tagged, _self-delimiting_ values. By definition, the wire format represents a sequence of _present_ values. In other words, every value found within a serialization represents a _present_ field; furthermore, the serialization contains no information about not-present values.
+
+The generated API for a proto message includes (de)serialization definitions which translate between API types and a stream of definitionally _present_ (tag, value) pairs. This translation is designed to be forward- and backward-compatibile across changes to the message definition; however, this compatibility introduces some (perhaps surprising) considerations when deserializing wire-formatted messages:
+
+- When serializing, fields with _no presence_ are not serialized if they contain their default value.
+ - For numeric types, the default is 0.
+ - For enums, the default is the zero-valued enumerator.
+ - For strings, bytes, and repeated fields, the default is the zero-length value.
+ - For messages, the default is the language-specific null value.
+- "Empty" length-delimited values (such as empty strings) can be validly represented in serialized values: the field is "present," in the sense that it appears in the wire format. However, if the generated API does not track presence, then these values may not be re-serialized; i.e., the empty field may be "not present" after a serialization round-trip.
+- When deserializing, duplicate field values may be handled in different ways depending on the field definition.
+ - Duplicate `repeated` fields are typically appended to the field's API representation. (Note that serializing a _packed_ repeated field produces only one, length-delimited value in the tag stream.)
+ - Duplicate `optional` field values follow the rule that "the last one wins."
+- `oneof` fields expose the API-level invariant that only one field is set at a time. However, the wire format may include multiple (tag, value) pairs which notionally belong to the `oneof`. Similar to `optional` fields, the generated API follows the "last one wins" rule.
+- Out-of-range values are not returned for enum fields in generated proto2 APIs. However, out-of-range values may be stored as _unknown fields_ in the API, even though the wire-format tag was recognized.
+
+### Presence in _named-field mapping_ formats
+
+Protobufs can be represented in human-readable, textual forms. Two notable formats are TextFormat (the output format produced by generated message `DebugString` methods) and JSON.
+
+These formats have correctness requirements of their own, and are generally stricter than _tagged-value stream_ formats. However, TextFormat more closely mimics the semantics of the wire format, and does, in certain cases, provide similar semantics (for example, appending repeated name-value mappings to a repeated field). In particular, similar to the wire format, TextFormat only includes fields which are present.
+
+JSON is a much stricter format, however, and cannot validly represent some semantics of the wire format or TextFormat.
+
+- Notably, JSON _elements_ are semantically unordered, and each member must have a unique name. This is different from TextFormat rules for repeated fields.
+- JSON may include fields that are "not present," unlike the _no presence_ discipline for other formats:
+ - JSON defines a `null` value, which may be used to represent a _defined but not-present field_.
+ - Repeated field values may be included in the formatted output, even if they are equal to the default (an empty list).
+- Because JSON elements are unordered, there is no way to unambiguously interpret the "last one wins" rule.
+ - In most cases, this is fine: JSON elements must have unique names: repeated field values are not valid JSON, so they do not need to be resolved as they are for TextFormat.
+ - However, this means that it may not be possible to interpret `oneof` fields unambiguously: if multiple cases are present, they are unordered.
+
+In theory, JSON _can_ represent presence in a semantic-preserving fashion. In practice, however, presence correctness can vary depending upon implementation choices, especially if JSON was chosen as a means to interoperate with clients not using protobufs.
+
+### Presence in proto2 APIs
+
+This table outlines whether presence is tracked for fields in proto2 APIs (both for generated APIs and using dynamic reflection):
+
+Field type | Explicit Presence
+-------------------------------------------- | -----------------
+Singular numeric (integer or floating point) | ✔️
+Singular enum | ✔️
+Singular string or bytes | ✔️
+Singular message | ✔️
+Repeated |
+Oneofs | ✔️
+Maps |
+
+Singular fields (of all types) track presence explicitly in the generated API. The generated message interface includes methods to query presence of fields. For example, the field `foo` has a corresponding `has_foo` method. (The specific name follows the same language-specific naming convention as the field accessors.) These methods are sometimes referred to as "hazzers" within the protobuf implementation.
+
+Similar to singular fields, `oneof` fields explicitly track which one of the members, if any, contains a value. For example, consider this example `oneof`:
+
+```
+oneof foo {
+ int32 a = 1;
+ float b = 2;
+}
+```
+
+Depending on the target language, the generated API would generally include several methods:
+
+- A hazzer for the oneof: `has_foo`
+- A _oneof case_ method: `foo`
+- Hazzers for the members: `has_a`, `has_b`
+- Getters for the members: `a`, `b`
+
+Repeated fields and maps do not track presence: there is no distinction between an _empty_ and a _not-present_ repeated field.
+
+### Presence in proto3 APIs
+
+This table outlines whether presence is tracked for fields in proto3 APIs (both for generated APIs and using dynamic reflection):
+
+Field type | `optional` | Explicit Presence
+-------------------------------------------- | ---------- | -----------------
+Singular numeric (integer or floating point) | No |
+Singular enum | No |
+Singular string or bytes | No |
+Singular numeric (integer or floating point) | Yes | ✔️
+Singular enum | Yes | ✔️
+Singular string or bytes | Yes | ✔️
+Singular message | Yes | ✔️
+Singular message | No | ✔️
+Repeated | N/A |
+Oneofs | N/A | ✔️
+Maps | N/A |
+
+Similar to proto2 APIs, proto3 does not track presence explicitly for repeated fields. Without the `optional` label, proto3 APIs do not track presence for basic types (numeric, string, bytes, and enums), either. (Note that `optional` for proto3 fields is only experimentally available as of release 3.12.) Oneof fields affirmatively expose presence, although the same set of hazzer methods may not generated as in proto2 APIs.
+
+Under the _no presence_ discipline, the default value is synonymous with "not present" for purposes of serialization. To notionally "clear" a field (so it won't be serialized), an API user would set it to the default value.
+
+The default value for enum-typed fields under _no presence_ is the corresponding 0-valued enumerator. Under proto3 syntax rules, all enum types are required to have an enumerator value which maps to 0. By convention, this is an `UNKNOWN` or similarly-named enumerator. If the zero value is notionally outside the domain of valid values for the application, this behavior can be thought of as tantamount to _explicit presence_.
+
+## Semantic differences
+
+The _no presence_ serialization discipline results in visible differences from the _explicit presence_ tracking discipline, when the default value is set. For a singular field with numeric, enum, or string type:
+
+- _No presence_ discipline:
+ - Default values are not serialized.
+ - Default values are _not_ merged-from.
+ - To "clear" a field, it is set to its default value.
+ - The default value may mean:
+ - the field was explicitly set to its default value, which is valid in the application-specific domain of values;
+ - the field was notionally "cleared" by setting its default; or
+ - the field was never set.
+- _Explicit presence_ discipline:
+ - Explicitly set values are always serialized, including default values.
+ - Un-set fields are never merged-from.
+ - Explicitly set fields -- including default values -- _are_ merged-from.
+ - A generated `has_foo` method indicates whether or not the field `foo` has been set (and not cleared).
+ - A generated `clear_foo` method must be used to clear (i.e., un-set) the value.
+
+### Considerations for merging
+
+Under the _no presence_ rules, it is effectively impossible for a target field to merge-from its default value (using the protobuf's API merging functions). This is because default values are skipped, simliar to the _no presence_ serialization discipline. Merging only updates the target (merged-to) message using the non-skipped values from the update (merged-from) message.
+
+The difference in merging behavior has further implications for protocols which rely on partial "patch" updates. If field presence is not tracked, then an update patch alone cannot represent an update to the default value, because only non-default values are merged-from.
+
+Updating to set a default value in this case requires some external mechanism, such as `FieldMask`. However, if presence _is_ tracked, then all explicitly-set values -- even default values -- will be merged into the target.
+
+### Considerations for change-compatibility
+
+Changing a field between _explicit presence_ and _no presence_ is a binary-compatible change for serialized values in wire format. However, the serialized representation of the message may differ, depending on which version of the message definition was used for serialization. Specifically, when a "sender" explicitly sets a field to its default value:
+
+- The serialized value following _no presence_ discipline does not contain the default value, even though it was explicitly set.
+- The serialized value following _explicit presence_ discipline contains every "present" field, even if it contains the default value.
+
+This change may or may not be safe, depending on the application's semantics. For example, consider two clients with different versions of a message definition.
+
+Client A uses this definition of the message, which follows the _explicit presence_ serialization discipline for field `foo`:
+
+```
+syntax = "proto3";
+message Msg {
+ optional int32 foo = 1;
+}
+```
+
+Client B uses a definition of the same message, except that it follows the _no presence_ discipline:
+
+```
+syntax = "proto3";
+message Msg {
+ int32 foo = 1;
+}
+```
+
+Now, consider a scenario where client A observes `foo`'s presence as the clients repeatedly exchange the "same" message by deserializing and reserializing:
+
+```
+// Client A:
+Msg m_a;
+m_a.set_foo(1); // non-default value
+assert(m_a.has_foo()); // OK
+Send(m_a.SerializeAsString()); // to client B
+
+// Client B:
+Msg m_b;
+m_b.ParseFromString(Receive()); // from client A
+assert(m_b.foo() == 1); // OK
+Send(m_b.SerializeAsString()); // to client A
+
+// Client A:
+m_a.ParseFromString(Receive()); // from client B
+assert(m_a.foo() == 1); // OK
+assert(m_a.has_foo()); // OK
+m_a.set_foo(0); // default value
+Send(m_a.SerializeAsString()); // to client B
+
+// Client B:
+Msg m_b;
+m_b.ParseFromString(Receive()); // from client A
+assert(m_b.foo() == 0); // OK
+Send(m_b.SerializeAsString()); // to client A
+
+// Client A:
+m_a.ParseFromString(Receive()); // from client B
+assert(m_a.foo() == 0); // OK
+assert(m_a.has_foo()); // FAIL
+```
+
+If client A depends on _explicit presence_ for `foo`, then a "round trip" through client B will be lossy from the perspective of client A. In the example, this is not a safe change: client A requires (by `assert`) that the field is present; even without any modifications through the API, that requirement fails in a value- and peer-dependent case.
+
+## How to enable _explicit presence_ in proto3
+
+These are the general steps to use the experimental field tracking support for proto3:
+
+1. Add an `optional` field to a `.proto` file.
+1. Run `protoc` (from release 3.12 or later) with an extra flag to recognize `optional` (i.e,. explicit presence) in proto3 files.
+1. Use the generated "hazzer" methods and "clear" methods in application code, instead of comparing or setting default values.
+
+### `.proto` file changes
+
+This is an example of a proto3 message with fields which follow both _no presence_ and _explicit presence_ semantics:
+
+```
+syntax = "proto3";
+package example;
+
+message MyMessage {
+ // No presence:
+ int32 not_tracked = 1;
+
+ // Explicit presence:
+ optional int32 tracked = 2;
+}
+```
+
+### `protoc` invocation
+
+To enable presence tracking for proto3 messages, pass the `--experimental_allow_proto3_optional` flag to protoc. Without this flag, the `optional` label is an error in files using proto3 syntax. This flag is available in protobuf release 3.12 or later (or at HEAD, if you are reading this application note from Git).
+
+### Using the generated code
+
+The generated code for proto3 fields with _explicit presence_ (the `optional` label) will be the same as it would be in a proto2 file.
+
+This is the definition used in the "no presence" examples below:
+
+```
+syntax = "proto3";
+package example;
+message Msg {
+ int32 foo = 1;
+}
+```
+
+This is the definition used in the "explicit presence" examples below:
+
+```
+syntax = "proto3";
+package example;
+message Msg {
+ optional int32 foo = 1;
+}
+```
+
+In the examples, a function `GetProto` constructs and returns a message of type `Msg` with unspecified contents.
+
+#### C++ example
+
+No presence:
+
+```
+Msg m = GetProto();
+if (m.foo() != 0) {
+ // "Clear" the field:
+ m.set_foo(0);
+} else {
+ // Default value: field may not have been present.
+ m.set_foo(1);
+}
+```
+
+Explicit presence:
+
+```
+Msg m = GetProto();
+if (m.has_foo()) {
+ // Clear the field:
+ m.clear_foo();
+} else {
+ // Field is not present, so set it.
+ m.set_foo(1);
+}
+```
+
+#### C# example
+
+No presence:
+
+```
+var m = GetProto();
+if (m.Foo != 0) {
+ // "Clear" the field:
+ m.Foo = 0;
+} else {
+ // Default value: field may not have been present.
+ m.Foo = 1;
+}
+```
+
+Explicit presence:
+
+```
+var m = GetProto();
+if (m.HasFoo) {
+ // Clear the field:
+ m.ClearFoo();
+} else {
+ // Field is not present, so set it.
+ m.Foo = 1;
+}
+```
+
+#### Go example
+
+No presence:
+
+```
+m := GetProto()
+if (m.GetFoo() != 0) {
+ // "Clear" the field:
+ m.Foo = 0;
+} else {
+ // Default value: field may not have been present.
+ m.Foo = 1;
+}
+```
+
+Explicit presence:
+
+```
+m := GetProto()
+if (m.HasFoo()) {
+ // Clear the field:
+ m.Foo = nil
+} else {
+ // Field is not present, so set it.
+ m.Foo = proto.Int32(1);
+}
+```
+
+#### Java example
+
+These examples use a `Builder` to demonstrate clearing. Simply checking presence and getting values from a `Builder` follows the same API as the message type.
+
+No presence:
+
+```
+Msg.Builder m = GetProto().toBuilder();
+if (m.getFoo() != 0) {
+ // "Clear" the field:
+ m.setFoo(0);
+} else {
+ // Default value: field may not have been present.
+ m.setFoo(1);
+}
+```
+
+Explicit presence:
+
+```
+Msg.Builder m = GetProto().toBuilder();
+if (m.hasFoo()) {
+ // Clear the field:
+ m.clearFoo()
+} else {
+ // Field is not present, so set it.
+ m.setFoo(1);
+}
+```
+
+#### Python example
+
+No presence:
+
+```
+m = example.Msg()
+if m.foo != 0:
+ // "Clear" the field:
+ m.foo = 0
+else:
+ // Default value: field may not have been present.
+ m.foo = 1
+```
+
+Explicit presence:
+
+```
+m = example.Msg()
+if m.HasField('foo'):
+ // Clear the field:
+ m.ClearField('foo')
+else:
+ // Field is not present, so set it.
+ m.foo = 1
+```
+
+#### Ruby example
+
+No presence:
+
+```
+m = Msg.new
+if m.foo != 0
+ // "Clear" the field:
+ m.foo = 0
+else
+ // Default value: field may not have been present.
+ m.foo = 1
+end
+```
+
+Explicit presence:
+
+```
+m = Msg.new
+if m.has_foo?
+ // Clear the field:
+ m.clear_foo
+else
+ // Field is not present, so set it.
+ m.foo = 1
+end
+```
+
+#### Javascript example
+
+No presence:
+
+```
+var m = new Msg();
+if (m.getFoo() != 0) {
+ // "Clear" the field:
+ m.setFoo(0);
+} else {
+ // Default value: field may not have been present.
+ m.setFoo(1);
+}
+```
+
+Explicit presence:
+
+```
+var m = new Msg();
+if (m.hasFoo()) {
+ // Clear the field:
+ m.clearFoo()
+} else {
+ // Field is not present, so set it.
+ m.setFoo(1);
+}
+```
+
+#### Objective C example
+
+No presence:
+
+```
+Msg *m = [[Msg alloc] init];
+if (m.foo != 0) {
+ // "Clear" the field:
+ m.foo = 0;
+} else {
+ // Default value: field may not have been present.
+ m.foo = 1;
+}
+```
+
+Explicit presence:
+
+```
+Msg *m = [[Msg alloc] init];
+if (m.hasFoo()) {
+ // Clear the field:
+ [m clearFoo];
+} else {
+ // Field is not present, so set it.
+ [m setFoo:1];
+}
+```
diff --git a/docs/implementing_proto3_presence.md b/docs/implementing_proto3_presence.md
new file mode 100644
index 0000000..08f9c51
--- /dev/null
+++ b/docs/implementing_proto3_presence.md
@@ -0,0 +1,350 @@
+# How To Implement Field Presence for Proto3
+
+Protobuf release 3.12 adds experimental support for `optional` fields in
+proto3. Proto3 optional fields track presence like in proto2. For background
+information about what presence tracking means, please see
+[docs/field_presence](field_presence.md).
+
+This document is targeted at developers who own or maintain protobuf code
+generators. All code generators will need to be updated to support proto3
+optional fields. First-party code generators developed by Google are being
+updated already. However third-party code generators will need to be updated
+independently by their authors. This includes:
+
+- implementations of Protocol Buffers for other languges.
+- alternate implementations of Protocol Buffers that target specialized use
+ cases.
+- code generators that implement some utility code on top of protobuf generated
+ classes.
+
+While this document speaks in terms of "code generators", these same principles
+apply to implementations that dynamically generate a protocol buffer API "on the
+fly", directly from a descriptor, in languages that support this kind of usage.
+
+## Updating a Code Generator
+
+When a user adds an `optional` field to proto3, this is internally rewritten as
+a one-field oneof, for backward-compatibility with reflection-based algorithms:
+
+```protobuf
+syntax = "proto3";
+
+message Foo {
+ // Experimental feature, not generally supported yet!
+ optional int32 foo = 1;
+
+ // Internally rewritten to:
+ // oneof _foo {
+ // int32 foo = 1 [proto3_optional=true];
+ // }
+ //
+ // We call _foo a "synthetic" oneof, since it was not created by the user.
+}
+```
+
+As a result, the main two goals when updating a code generator are:
+
+1. Give `optional` fields like `foo` normal field presence, as described in
+ [docs/field_presence](field_presence.md) If your implementation already
+ supports proto2, a proto3 `optional` field should use exactly the same API
+ and internal implementation as proto2 `optional`.
+2. Avoid generating any oneof-based accessors for the synthetic oneof. Its only
+ purpose is to make reflection-based algorithms work properly if they are
+ not aware of proto3 presence. The synthetic oneof should not appear anywhere
+ in the generated API.
+
+### Satisfying the Experimental Check
+
+If you try to run `protoc` on a file with proto3 `optional` fields, you will get
+an error because the feature is still experimental:
+
+```
+$ cat test.proto
+syntax = "proto3";
+
+message Foo {
+ // Experimental feature, not generally supported yet!
+ optional int32 a = 1;
+}
+$ protoc --cpp_out=. test.proto
+test.proto: This file contains proto3 optional fields, but --experimental_allow_proto3_optional was not set.
+```
+
+There are two options for getting around this error:
+
+1. Pass `--experimental_allow_proto3_optional` to protoc.
+2. Make your filename (or a directory name) contain the string
+ `test_proto3_optional`. This indicates that the proto file is specifically
+ for testing proto3 optional support, so the check is suppressed.
+
+These options are demonstrated below:
+
+```
+# One option:
+$ ./src/protoc test.proto --cpp_out=. --experimental_allow_proto3_optional
+
+# Another option:
+$ cp test.proto test_proto3_optional.proto
+$ ./src/protoc test_proto3_optional.proto --cpp_out=.
+$
+```
+
+The experimental check will be removed in a future release, once we are ready
+to make this feature generally available. Ideally this will happen for the 3.13
+release of protobuf, sometime in mid-2020, but there is not a specific date set
+for this yet. Some of the timing will depend on feedback we get from the
+community, so if you have questions or concerns please get in touch via a
+GitHub issue.
+
+### Signaling That Your Code Generator Supports Proto3 Optional
+
+If you now try to invoke your own code generator with the test proto, you will
+run into a different error:
+
+```
+$ ./src/protoc test_proto3_optional.proto --my_codegen_out=.
+test_proto3_optional.proto: is a proto3 file that contains optional fields, but
+code generator --my_codegen_out hasn't been updated to support optional fields in
+proto3. Please ask the owner of this code generator to support proto3 optional.
+```
+
+This check exists to make sure that code generators get a chance to update
+before they are used with proto3 `optional` fields. Without this check an old
+code generator might emit obsolete generated APIs (like accessors for a
+synthetic oneof) and users could start depending on these. That would create
+a legacy migration burden once a code generator actually implements the feature.
+
+To signal that your code generator supports `optional` fields in proto3, you
+need to tell `protoc` what features you support. The method for doing this
+depends on whether you are using the C++
+`google::protobuf::compiler::CodeGenerator`
+framework or not.
+
+If you are using the CodeGenerator framework:
+
+```c++
+class MyCodeGenerator : public google::protobuf::compiler::CodeGenerator {
+ // Add this method.
+ uint64_t GetSupportedFeatures() const override {
+ // Indicate that this code generator supports proto3 optional fields.
+ // (Note: don't release your code generator with this flag set until you
+ // have actually added and tested your proto3 support!)
+ return FEATURE_PROTO3_OPTIONAL;
+ }
+}
+```
+
+If you are generating code using raw `CodeGeneratorRequest` and
+`CodeGeneratorResponse` messages from `plugin.proto`, the change will be very
+similar:
+
+```c++
+void GenerateResponse() {
+ CodeGeneratorResponse response;
+ response.set_supported_features(CodeGeneratorResponse::FEATURE_PROTO3_OPTIONAL);
+
+ // Generate code...
+}
+```
+
+Once you have added this, you should now be able to successfully use your code
+generator to generate a file containing proto3 optional fields:
+
+```
+$ ./src/protoc test_proto3_optional.proto --my_codegen_out=.
+```
+
+### Updating Your Code Generator
+
+Now to actually add support for proto3 optional to your code generator. The goal
+is to recognize proto3 optional fields as optional, and suppress any output from
+synthetic oneofs.
+
+If your code generator does not currently support proto2, you will need to
+design an API and implementation for supporting presence in scalar fields.
+Generally this means:
+
+- allocating a bit inside the generated class to represent whether a given field
+ is present or not.
+- exposing a `has_foo()` method for each field to return the value of this bit.
+- make the parser set this bit when a value is parsed from the wire.
+- make the serializer test this bit to decide whether to serialize.
+
+If your code generator already supports proto2, then most of your work is
+already done. All you need to do is make sure that proto3 optional fields have
+exactly the same API and behave in exactly the same way as proto2 optional
+fields.
+
+From experience updating several of Google's code generators, most of the
+updates that are required fall into one of several patterns. Here we will show
+the patterns in terms of the C++ CodeGenerator framework. If you are using
+`CodeGeneratorRequest` and `CodeGeneratorReply` directly, you can translate the
+C++ examples to your own language, referencing the C++ implementation of these
+methods where required.
+
+#### To test whether a field should have presence
+
+Old:
+
+```c++
+bool MessageHasPresence(const google::protobuf::Descriptor* message) {
+ return message->file()->syntax() ==
+ google::protobuf::FileDescriptor::SYNTAX_PROTO2;
+}
+```
+
+New:
+
+```c++
+// Presence is no longer a property of a message, it's a property of individual
+// fields.
+bool FieldHasPresence(const google::protobuf::FieldDescriptor* field) {
+ return field->has_presence();
+ // Note, the above will return true for fields in a oneof.
+ // If you want to filter out oneof fields, write this instead:
+ // return field->has_presence && !field->real_containing_oneof()
+}
+```
+
+#### To test whether a field is a member of a oneof
+
+Old:
+
+```c++
+bool FieldIsInOneof(const google::protobuf::FielDescriptor* field) {
+ return field->containing_oneof() != nullptr;
+}
+```
+
+New:
+
+```c++
+bool FieldIsInOneof(const google::protobuf::FielDescriptor* field) {
+ // real_containing_oneof() returns nullptr for synthetic oneofs.
+ return field->real_containing_oneof() != nullptr;
+}
+```
+
+#### To iterate over all oneofs
+
+Old:
+
+```c++
+bool IterateOverOneofs(const google::protobuf::Descriptor* message) {
+ for (int i = 0; i < message->oneof_decl_count(); i++) {
+ const google::protobuf::OneofDescriptor* oneof = message->oneof(i);
+ // ...
+ }
+}
+```
+
+New:
+
+```c++
+bool IterateOverOneofs(const google::protobuf::Descriptor* message) {
+ // Real oneofs are always first, and real_oneof_decl_count() will return the
+ // total number of oneofs, excluding synthetic oneofs.
+ for (int i = 0; i < message->real_oneof_decl_count(); i++) {
+ const google::protobuf::OneofDescriptor* oneof = message->oneof(i);
+ // ...
+ }
+}
+```
+
+## Updating Reflection
+
+If your implementation offers reflection, there are a few other changes to make:
+
+### API Changes
+
+The API for reflecting over fields and oneofs should make the following changes.
+These match the changes implemented in C++ reflection.
+
+1. Add a `FieldDescriptor::has_presence()` method returning `bool`
+ (adjusted to your language's naming convention). This should return true
+ for all fields that have explicit presence, as documented in
+ [docs/field_presence](field_presence.md). In particular, this includes
+ fields in a oneof, proto2 scalar fields, and proto3 `optional` fields.
+ This accessor will allow users to query what fields have presence without
+ thinking about the difference between proto2 and proto3.
+2. As a corollary of (1), please do *not* expose an accessor for the
+ `FieldDescriptorProto.proto3_optional` field. We want to avoid having
+ users implement any proto2/proto3-specific logic. Users should use the
+ `has_presence()` function instead.
+3. You may also wish to add a `FieldDescriptor::has_optional_keyword()` method
+ returning `bool`, which indicates whether the `optional` keyword is present.
+ Message fields will always return `true` for `has_presence()`, so this method
+ can allow a user to know whether the user wrote `optional` or not. It can
+ occasionally be useful to have this information, even though it does not
+ change the presence semantics of the field.
+4. If your reflection API may be used for a code generator, you may wish to
+ implement methods to help users tell the difference between real and
+ synthetic oneofs. In particular:
+ - `OneofDescriptor::is_synthetic()`: returns true if this is a synthetic
+ oneof.
+ - `FieldDescriptor::real_containing_oneof()`: like `containing_oneof()`,
+ but returns `nullptr` if the oneof is synthetic.
+ - `Descriptor::real_oneof_decl_count()`: like `oneof_decl_count()`, but
+ returns the number of real oneofs only.
+
+### Implementation Changes
+
+Proto3 `optional` fields and synthetic oneofs must work correctly when
+reflected on. Specifically:
+
+1. Reflection for synthetic oneofs should work properly. Even though synthetic
+ oneofs do not really exist in the message, you can still make reflection work
+ as if they did. In particular, you can make a method like
+ `Reflection::HasOneof()` or `Reflection::GetOneofFieldDescriptor()` look at
+ the hasbit to determine if the oneof is present or not.
+2. Reflection for proto3 optional fields should work properly. For example, a
+ method like `Reflection::HasField()` should know to look for the hasbit for a
+ proto3 `optional` field. It should not be fooled by the synthetic oneof into
+ thinking that there is a `case` member for the oneof.
+
+Once you have updated reflection to work properly with proto3 `optional` and
+synthetic oneofs, any code that *uses* your reflection interface should work
+properly with no changes. This is the benefit of using synthetic oneofs.
+
+In particular, if you have a reflection-based implementation of protobuf text
+format or JSON, it should properly support proto3 optional fields without any
+changes to the code. The fields will look like they all belong to a one-field
+oneof, and existing proto3 reflection code should know how to test presence for
+fields in a oneof.
+
+So the best way to test your reflection changes is to try round-tripping a
+message through text format, JSON, or some other reflection-based parser and
+serializer, if you have one.
+
+### Validating Descriptors
+
+If your reflection implementation supports loading descriptors at runtime,
+you must verify that all synthetic oneofs are ordered after all "real" oneofs.
+
+Here is the code that implements this validation step in C++, for inspiration:
+
+```c++
+ // Validation that runs for each message.
+ // Synthetic oneofs must be last.
+ int first_synthetic = -1;
+ for (int i = 0; i < message->oneof_decl_count(); i++) {
+ const OneofDescriptor* oneof = message->oneof_decl(i);
+ if (oneof->is_synthetic()) {
+ if (first_synthetic == -1) {
+ first_synthetic = i;
+ }
+ } else {
+ if (first_synthetic != -1) {
+ AddError(message->full_name(), proto.oneof_decl(i),
+ DescriptorPool::ErrorCollector::OTHER,
+ "Synthetic oneofs must be after all other oneofs");
+ }
+ }
+ }
+
+ if (first_synthetic == -1) {
+ message->real_oneof_decl_count_ = message->oneof_decl_count_;
+ } else {
+ message->real_oneof_decl_count_ = first_synthetic;
+ }
+```
diff --git a/docs/options.md b/docs/options.md
index 22a8bc9..df6b88c 100644
--- a/docs/options.md
+++ b/docs/options.md
@@ -216,3 +216,31 @@
1. Ocaml-protoc-plugin
* Website: https://github.com/issuu/ocaml-protoc-plugin
* Extensions: 1074
+
+1. Analyze Re Graphene
+ * Website: https://analyzere.com
+ * Extensions: 1075
+
+1. Wire since and until
+ * Website: https://square.github.io/wire/
+ * Extensions: 1076, 1077
+
+1. Bazel, Failure Details
+ * Website: https://github.com/bazelbuild/bazel
+ * Extensions: 1078
+
+1. grpc-graphql-gateway
+ * Website: https://github.com/ysugimoto/grpc-graphql-gateway
+ * Extensions: 1079
+
+1. Cloudstate
+ * Website: https://cloudstate.io
+ * Extensions: 1080-1084
+
+1. SummaFT protoc-plugins
+ * Website: https://summaft.com/
+ * Extensions: 1085
+
+1. ADLINK EdgeSDK
+ * Website: https://www.adlinktech.com/en/Edge-SDK-IoT
+ * Extensions: 1086
diff --git a/docs/third_party.md b/docs/third_party.md
index fcc5117..11a6efb 100644
--- a/docs/third_party.md
+++ b/docs/third_party.md
@@ -51,6 +51,7 @@
* Haxe: https://github.com/Atry/protoc-gen-haxe
* Java: https://github.com/google/protobuf (Google-official implementation)
* Java/Android: https://github.com/square/wire
+* Java: https://github.com/HebiRobotics/QuickBuffers/
* Java ME: http://code.google.com/p/protobuf-javame/
* Java ME: http://swingme.sourceforge.net/encode.shtml
* Java ME: http://code.google.com/p/protobuf-j2me/
@@ -81,6 +82,7 @@
* Prolog: http://www.swi-prolog.org/pldoc/package/protobufs.html
* Python: https://github.com/google/protobuf (Google-official implementation)
* Python: https://github.com/eigenein/protobuf
+* Python: https://github.com/danielgtaylor/python-betterproto
* R: http://cran.r-project.org/package=RProtoBuf
* Ruby: http://code.google.com/p/ruby-protobuf/
* Ruby: http://github.com/mozy/ruby-protocol-buffers
@@ -103,37 +105,40 @@
GRPC (http://www.grpc.io/) is Google's RPC implementation for Protocol Buffers. There are other third-party RPC implementations as well. Some of these actually work with Protocol Buffers service definitions (defined using the `service` keyword in `.proto` files) while others just use Protocol Buffers message objects.
* https://github.com/grpc/grpc (C++, Node.js, Python, Ruby, Objective-C, PHP, C#, Google-official implementation)
-* http://zeroc.com/ice.html (Multiple languages)
-* http://code.google.com/p/protobuf-net/ (C#/.NET/WCF/VB)
-* https://launchpad.net/txprotobuf/ (Python)
-* https://github.com/modeswitch/protobuf-rpc (Python)
-* http://code.google.com/p/protobuf-socket-rpc/ (Java, Python)
-* http://code.google.com/p/proto-streamer/ (Java)
-* http://code.google.com/p/server1/ (C++)
-* http://deltavsoft.com/RcfUserGuide/Protobufs (C++)
-* http://code.google.com/p/protobuf-mina-rpc/ (Python client, Java server)
-* http://code.google.com/p/casocklib/ (C++)
+* https://zeroc.com/products/ice (Multiple languages)
+* https://github.com/protobuf-net/protobuf-net (C#/.NET/WCF/VB)
+* http://www.deltavsoft.com/doc/_external_serialization.html#Protobufs (C++)
* https://protojure.github.io (Clojure)
-* http://code.google.com/p/cxf-protobuf/ (Java)
-* http://code.google.com/p/protobuf-remote/ (C++/C#)
-* http://code.google.com/p/protobuf-rpc-pro/ (Java)
-* https://code.google.com/p/eneter-protobuf-serializer/ (Java/.NET)
-* http://www.deltavsoft.com/RCFProto.html (C++/Java/Python/C#)
-* https://github.com/robbinfan/claire-protorpc (C++)
-* https://github.com/BaiduPS/sofa-pbrpc (C++)
-* https://github.com/ebencheung/arab (C++)
-* http://code.google.com/p/protobuf-csharp-rpc/ (C#)
-* https://github.com/thesamet/rpcz (C++/Python, based on ZeroMQ)
-* https://github.com/w359405949/libmaid (C++, Python)
+* https://code.google.com/p/protobuf-rpc-pro/ (Java)
+* https://github.com/baidu/sofa-pbrpc (C++)
+* https://github.com/madhon/protobuf-csharp-rpc (C#)
* https://github.com/madwyn/libpbrpc (C++)
* https://github.com/SeriousMa/grpc-protobuf-validation (Java)
-* https://github.com/tony612/grpc-elixir (Elixir)
+* https://github.com/elixir-grpc/grpc (Elixir)
* https://github.com/johanbrandhorst/protobuf (GopherJS)
* https://github.com/awakesecurity/gRPC-haskell (Haskell)
* https://github.com/Yeolar/raster (C++)
* https://github.com/jnordberg/wsrpc (JavaScript Node.js/Browser)
* https://github.com/ppissias/xsrpcj (Java)
+Inactive:
+
+* https://launchpad.net/txprotobuf/ (Python)
+* https://github.com/modeswitch/protobuf-rpc (Python)
+* https://github.com/sdeo/protobuf-socket-rpc (Java, Python)
+* https://code.google.com/p/proto-streamer/ (Java)
+* https://code.google.com/p/server1/ (C++)
+* https://code.google.com/p/protobuf-mina-rpc/ (Python client, Java server)
+* https://code.google.com/p/casocklib/ (C++)
+* https://code.google.com/p/cxf-protobuf/ (Java)
+* https://code.google.com/p/protobuf-remote/ (C++/C#)
+* https://code.google.com/p/eneter-protobuf-serializer/ (Java/.NET)
+* https://github.com/robbinfan/claire/tree/master/protorpc (C++)
+* https://github.com/ebencheung/arab (C++)
+* https://code.google.com/p/protobuf-csharp-rpc/ (C#)
+* https://github.com/thesamet/rpcz (C++/Python, based on ZeroMQ)
+* https://github.com/w359405949/libmaid (C++, Python)
+
## Other Utilities
There are miscellaneous other things you may find useful as a Protocol Buffers developer.
diff --git a/examples/.gitignore b/examples/.gitignore
new file mode 100644
index 0000000..229542d
--- /dev/null
+++ b/examples/.gitignore
@@ -0,0 +1,2 @@
+# Ignore the bazel symlinks
+/bazel-*
diff --git a/examples/Makefile b/examples/Makefile
index 4ad6056..e9f9635 100644
--- a/examples/Makefile
+++ b/examples/Makefile
@@ -41,11 +41,11 @@
add_person_cpp: add_person.cc protoc_middleman
pkg-config --cflags protobuf # fails if protobuf is not installed
- c++ add_person.cc addressbook.pb.cc -o add_person_cpp `pkg-config --cflags --libs protobuf`
+ c++ -std=c++11 add_person.cc addressbook.pb.cc -o add_person_cpp `pkg-config --cflags --libs protobuf`
list_people_cpp: list_people.cc protoc_middleman
pkg-config --cflags protobuf # fails if protobuf is not installed
- c++ list_people.cc addressbook.pb.cc -o list_people_cpp `pkg-config --cflags --libs protobuf`
+ c++ -std=c++11 list_people.cc addressbook.pb.cc -o list_people_cpp `pkg-config --cflags --libs protobuf`
add_person_dart: add_person.dart protoc_middleman_dart
diff --git a/examples/README.md b/examples/README.md
old mode 100755
new mode 100644
diff --git a/examples/WORKSPACE b/examples/WORKSPACE
index db86225..fb36639 100644
--- a/examples/WORKSPACE
+++ b/examples/WORKSPACE
@@ -19,12 +19,11 @@
)
# Similar to com_google_protobuf but for Java lite. If you are building
-# for Android, the lite version should be prefered because it has a much
+# for Android, the lite version should be preferred because it has a much
# smaller code size.
-http_archive(
+local_repository(
name = "com_google_protobuf_javalite",
- strip_prefix = "protobuf-javalite",
- urls = ["https://github.com/protocolbuffers/protobuf/archive/javalite.zip"],
+ path = "..",
)
load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
diff --git a/fix_permissions.sh b/fix_permissions.sh
new file mode 100755
index 0000000..f33c25c
--- /dev/null
+++ b/fix_permissions.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+for file in $(find . -type f); do
+ if [ "$(head -c 2 $file)" == "#!" ]; then
+ chmod u+x $file
+ else
+ chmod a-x $file
+ fi
+done
diff --git a/global.json b/global.json
index 0c7cc9f..1c02f07 100644
--- a/global.json
+++ b/global.json
@@ -1,5 +1,5 @@
{
"sdk": {
- "version": "2.1.504"
+ "version": "3.0.100"
}
}
diff --git a/java/README.md b/java/README.md
index a109494..c4e8e20 100644
--- a/java/README.md
+++ b/java/README.md
@@ -23,7 +23,7 @@
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
- <version>3.10.0</version>
+ <version>3.11.0</version>
</dependency>
```
@@ -37,7 +37,7 @@
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
- <version>3.10.0</version>
+ <version>3.11.0</version>
</dependency>
```
@@ -45,7 +45,7 @@
If you are using Gradle, add the following to your `build.gradle` file's dependencies:
```
- compile 'com.google.protobuf:protobuf-java:3.10.0'
+ compile 'com.google.protobuf:protobuf-java:3.11.0'
```
Again, be sure to check that the version number maches (or is newer than) the version number of protoc that you are using.
@@ -146,7 +146,7 @@
are guaranteed for minor version releases if the user follows the guideline
described in this section.
-* Protobuf major version releases may also be backwards-compatbile with the
+* Protobuf major version releases may also be backwards-compatible with the
last release of the previous major version. See the release notice for more
details.
diff --git a/java/bom/pom.xml b/java/bom/pom.xml
index 59f0846..04bd3f5 100644
--- a/java/bom/pom.xml
+++ b/java/bom/pom.xml
@@ -4,7 +4,7 @@
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-bom</artifactId>
- <version>3.11.0-rc-1</version>
+ <version>3.12.0-rc-2</version>
<packaging>pom</packaging>
<name>Protocol Buffers [BOM]</name>
diff --git a/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/descriptor.proto b/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/descriptor.proto
index a785f79..031433e 100644
--- a/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/descriptor.proto
+++ b/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/descriptor.proto
@@ -228,7 +228,7 @@
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
-// Object-C plugin) and your porject website (if available) -- there's no need
+// Object-C plugin) and your project website (if available) -- there's no need
// to explain how you intend to use them. Usually you only need one extension
// number. You can declare multiple options with only one extension number by
// putting them in a sub-message. See the Custom Options section of the docs
diff --git a/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_custom_options.proto b/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_custom_options.proto
index e591d29..2f4e3fd 100644
--- a/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_custom_options.proto
+++ b/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_custom_options.proto
@@ -321,7 +321,7 @@
}
// Allow Aggregate to be used as an option at all possible locations
-// in the .proto grammer.
+// in the .proto grammar.
extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
diff --git a/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import.proto b/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import.proto
index c115b11..ec36cca 100644
--- a/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import.proto
+++ b/java/compatibility_tests/v2.5.0/more_protos/src/proto/google/protobuf/unittest_import.proto
@@ -43,7 +43,7 @@
option optimize_for = SPEED;
-// Excercise the java_package option.
+// Exercise the java_package option.
option java_package = "com.google.protobuf.test";
// Do not set a java_outer_classname here to verify that Proto2 works without
diff --git a/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto b/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
index a785f79..031433e 100644
--- a/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
+++ b/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
@@ -228,7 +228,7 @@
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
-// Object-C plugin) and your porject website (if available) -- there's no need
+// Object-C plugin) and your project website (if available) -- there's no need
// to explain how you intend to use them. Usually you only need one extension
// number. You can declare multiple options with only one extension number by
// putting them in a sub-message. See the Custom Options section of the docs
diff --git a/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto b/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
index e591d29..2f4e3fd 100644
--- a/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
+++ b/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
@@ -321,7 +321,7 @@
}
// Allow Aggregate to be used as an option at all possible locations
-// in the .proto grammer.
+// in the .proto grammar.
extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
diff --git a/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto b/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
index c115b11..ec36cca 100644
--- a/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
+++ b/java/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
@@ -43,7 +43,7 @@
option optimize_for = SPEED;
-// Excercise the java_package option.
+// Exercise the java_package option.
option java_package = "com.google.protobuf.test";
// Do not set a java_outer_classname here to verify that Proto2 works without
diff --git a/java/compatibility_tests/v2.5.0/test.sh b/java/compatibility_tests/v2.5.0/test.sh
index f67dc76..65ea960 100755
--- a/java/compatibility_tests/v2.5.0/test.sh
+++ b/java/compatibility_tests/v2.5.0/test.sh
@@ -15,7 +15,7 @@
# The old version of protobuf that we are testing compatibility against. This
# is usually the same as TEST_VERSION (i.e., we use the tests extracted from
# that version to test compatibility of the newest runtime against it), but it
-# is also possible to use this same test set to test the compatibiilty of the
+# is also possible to use this same test set to test the compatibility of the
# latest version against other versions.
OLD_VERSION=$1
OLD_VERSION_PROTOC=https://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
diff --git a/java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/LiteralByteStringTest.java b/java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/LiteralByteStringTest.java
index 5902ea3..d2ce563 100644
--- a/java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/LiteralByteStringTest.java
+++ b/java/compatibility_tests/v2.5.0/tests/src/main/java/com/google/protobuf/test/LiteralByteStringTest.java
@@ -87,7 +87,7 @@
stillEqual = (iter.hasNext() && referenceBytes[i] == iter.nextByte());
}
assertTrue(classUnderTest + " must capture the right bytes", stillEqual);
- assertFalse(classUnderTest + " must have exhausted the itertor", iter.hasNext());
+ assertFalse(classUnderTest + " must have exhausted the iterator", iter.hasNext());
try {
iter.nextByte();
@@ -317,7 +317,7 @@
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
- assertEquals("InputStream.reset() succeded",
+ assertEquals("InputStream.reset() succeeded",
stringSize - skipped1, input.available());
assertEquals("InputStream.reset(), read()",
stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
diff --git a/java/core/BUILD b/java/core/BUILD
new file mode 100644
index 0000000..e7778f9
--- /dev/null
+++ b/java/core/BUILD
@@ -0,0 +1,127 @@
+load("@rules_java//java:defs.bzl", "java_library")
+load("@rules_proto//proto:defs.bzl", "proto_lang_toolchain")
+
+LITE_SRCS = [
+ # Keep in sync with `//java/lite:pom.xml`.
+ "src/main/java/com/google/protobuf/AbstractMessageLite.java",
+ "src/main/java/com/google/protobuf/AbstractParser.java",
+ "src/main/java/com/google/protobuf/AbstractProtobufList.java",
+ "src/main/java/com/google/protobuf/AllocatedBuffer.java",
+ "src/main/java/com/google/protobuf/Android.java",
+ "src/main/java/com/google/protobuf/ArrayDecoders.java",
+ "src/main/java/com/google/protobuf/BinaryReader.java",
+ "src/main/java/com/google/protobuf/BinaryWriter.java",
+ "src/main/java/com/google/protobuf/BooleanArrayList.java",
+ "src/main/java/com/google/protobuf/BufferAllocator.java",
+ "src/main/java/com/google/protobuf/ByteBufferWriter.java",
+ "src/main/java/com/google/protobuf/ByteOutput.java",
+ "src/main/java/com/google/protobuf/ByteString.java",
+ "src/main/java/com/google/protobuf/CodedInputStream.java",
+ "src/main/java/com/google/protobuf/CodedInputStreamReader.java",
+ "src/main/java/com/google/protobuf/CodedOutputStream.java",
+ "src/main/java/com/google/protobuf/CodedOutputStreamWriter.java",
+ "src/main/java/com/google/protobuf/DoubleArrayList.java",
+ "src/main/java/com/google/protobuf/ExperimentalApi.java",
+ "src/main/java/com/google/protobuf/ExtensionLite.java",
+ "src/main/java/com/google/protobuf/ExtensionRegistryFactory.java",
+ "src/main/java/com/google/protobuf/ExtensionRegistryLite.java",
+ "src/main/java/com/google/protobuf/ExtensionSchema.java",
+ "src/main/java/com/google/protobuf/ExtensionSchemaLite.java",
+ "src/main/java/com/google/protobuf/ExtensionSchemas.java",
+ "src/main/java/com/google/protobuf/FieldInfo.java",
+ "src/main/java/com/google/protobuf/FieldSet.java",
+ "src/main/java/com/google/protobuf/FieldType.java",
+ "src/main/java/com/google/protobuf/FloatArrayList.java",
+ "src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java",
+ "src/main/java/com/google/protobuf/GeneratedMessageLite.java",
+ "src/main/java/com/google/protobuf/IntArrayList.java",
+ "src/main/java/com/google/protobuf/Internal.java",
+ "src/main/java/com/google/protobuf/InvalidProtocolBufferException.java",
+ "src/main/java/com/google/protobuf/IterableByteBufferInputStream.java",
+ "src/main/java/com/google/protobuf/JavaType.java",
+ "src/main/java/com/google/protobuf/LazyField.java",
+ "src/main/java/com/google/protobuf/LazyFieldLite.java",
+ "src/main/java/com/google/protobuf/LazyStringArrayList.java",
+ "src/main/java/com/google/protobuf/LazyStringList.java",
+ "src/main/java/com/google/protobuf/ListFieldSchema.java",
+ "src/main/java/com/google/protobuf/LongArrayList.java",
+ "src/main/java/com/google/protobuf/ManifestSchemaFactory.java",
+ "src/main/java/com/google/protobuf/MapEntryLite.java",
+ "src/main/java/com/google/protobuf/MapFieldLite.java",
+ "src/main/java/com/google/protobuf/MapFieldSchema.java",
+ "src/main/java/com/google/protobuf/MapFieldSchemaLite.java",
+ "src/main/java/com/google/protobuf/MapFieldSchemas.java",
+ "src/main/java/com/google/protobuf/MessageInfo.java",
+ "src/main/java/com/google/protobuf/MessageInfoFactory.java",
+ "src/main/java/com/google/protobuf/MessageLite.java",
+ "src/main/java/com/google/protobuf/MessageLiteOrBuilder.java",
+ "src/main/java/com/google/protobuf/MessageLiteToString.java",
+ "src/main/java/com/google/protobuf/MessageSchema.java",
+ "src/main/java/com/google/protobuf/MessageSetSchema.java",
+ "src/main/java/com/google/protobuf/MutabilityOracle.java",
+ "src/main/java/com/google/protobuf/NewInstanceSchema.java",
+ "src/main/java/com/google/protobuf/NewInstanceSchemaLite.java",
+ "src/main/java/com/google/protobuf/NewInstanceSchemas.java",
+ "src/main/java/com/google/protobuf/NioByteString.java",
+ "src/main/java/com/google/protobuf/OneofInfo.java",
+ "src/main/java/com/google/protobuf/Parser.java",
+ "src/main/java/com/google/protobuf/PrimitiveNonBoxingCollection.java",
+ "src/main/java/com/google/protobuf/ProtoSyntax.java",
+ "src/main/java/com/google/protobuf/Protobuf.java",
+ "src/main/java/com/google/protobuf/ProtobufArrayList.java",
+ "src/main/java/com/google/protobuf/ProtobufLists.java",
+ "src/main/java/com/google/protobuf/ProtocolStringList.java",
+ "src/main/java/com/google/protobuf/RawMessageInfo.java",
+ "src/main/java/com/google/protobuf/Reader.java",
+ "src/main/java/com/google/protobuf/RopeByteString.java",
+ "src/main/java/com/google/protobuf/Schema.java",
+ "src/main/java/com/google/protobuf/SchemaFactory.java",
+ "src/main/java/com/google/protobuf/SchemaUtil.java",
+ "src/main/java/com/google/protobuf/SmallSortedMap.java",
+ "src/main/java/com/google/protobuf/StructuralMessageInfo.java",
+ "src/main/java/com/google/protobuf/TextFormatEscaper.java",
+ "src/main/java/com/google/protobuf/UninitializedMessageException.java",
+ "src/main/java/com/google/protobuf/UnknownFieldSchema.java",
+ "src/main/java/com/google/protobuf/UnknownFieldSetLite.java",
+ "src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java",
+ "src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java",
+ "src/main/java/com/google/protobuf/UnsafeUtil.java",
+ "src/main/java/com/google/protobuf/Utf8.java",
+ "src/main/java/com/google/protobuf/WireFormat.java",
+ "src/main/java/com/google/protobuf/Writer.java",
+]
+
+# Should be used as `//java/lite`.
+java_library(
+ name = "lite",
+ srcs = LITE_SRCS,
+ visibility = [
+ "//java/lite:__pkg__",
+ ],
+)
+
+java_library(
+ name = "core",
+ srcs = glob(
+ [
+ "src/main/java/com/google/protobuf/*.java",
+ ],
+ exclude = LITE_SRCS,
+ ) + [
+ "//:gen_well_known_protos_java",
+ ],
+ visibility = ["//visibility:public"],
+ exports = [
+ "//java/lite",
+ ],
+ deps = [
+ "//java/lite",
+ ],
+)
+
+proto_lang_toolchain(
+ name = "toolchain",
+ command_line = "--java_out=$(OUT)",
+ runtime = ":core",
+ visibility = ["//visibility:public"],
+)
diff --git a/java/core/generate-test-sources-build.xml b/java/core/generate-test-sources-build.xml
index 92c0b1c..71a88d0 100644
--- a/java/core/generate-test-sources-build.xml
+++ b/java/core/generate-test-sources-build.xml
@@ -17,6 +17,7 @@
<arg value="${protobuf.source.dir}/google/protobuf/unittest_no_generic_services.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_optimize_for.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_proto3.proto"/>
+ <arg value="${protobuf.source.dir}/google/protobuf/unittest_proto3_optional.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_well_known_types.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/any_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/cached_field_size_test.proto"/>
diff --git a/java/core/pom.xml b/java/core/pom.xml
index 737a9c1..5fb5045 100644
--- a/java/core/pom.xml
+++ b/java/core/pom.xml
@@ -4,7 +4,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.11.0-rc-1</version>
+ <version>3.12.0-rc-2</version>
</parent>
<artifactId>protobuf-java</artifactId>
diff --git a/java/core/src/main/java/com/google/protobuf/AllocatedBuffer.java b/java/core/src/main/java/com/google/protobuf/AllocatedBuffer.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/ArrayDecoders.java b/java/core/src/main/java/com/google/protobuf/ArrayDecoders.java
old mode 100755
new mode 100644
index a969c04..1e33c5a
--- a/java/core/src/main/java/com/google/protobuf/ArrayDecoders.java
+++ b/java/core/src/main/java/com/google/protobuf/ArrayDecoders.java
@@ -873,7 +873,7 @@
}
} else {
Object value = null;
- // Enum is a special case becasue unknown enum values will be put into UnknownFieldSetLite.
+ // Enum is a special case because unknown enum values will be put into UnknownFieldSetLite.
if (extension.getLiteType() == WireFormat.FieldType.ENUM) {
position = decodeVarint32(data, position, registers);
Object enumValue = extension.descriptor.getEnumType().findValueByNumber(registers.int1);
diff --git a/java/core/src/main/java/com/google/protobuf/BinaryReader.java b/java/core/src/main/java/com/google/protobuf/BinaryReader.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/BinaryWriter.java b/java/core/src/main/java/com/google/protobuf/BinaryWriter.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
index 65dcd53..f023baa 100644
--- a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
@@ -141,6 +141,26 @@
}
@Override
+ public int indexOf(Object element) {
+ if (!(element instanceof Boolean)) {
+ return -1;
+ }
+ boolean unboxedElement = (Boolean) element;
+ int numElems = size();
+ for (int i = 0; i < numElems; i++) {
+ if (array[i] == unboxedElement) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public boolean contains(Object element) {
+ return indexOf(element) != -1;
+ }
+
+ @Override
public int size() {
return size;
}
diff --git a/java/core/src/main/java/com/google/protobuf/BufferAllocator.java b/java/core/src/main/java/com/google/protobuf/BufferAllocator.java
old mode 100755
new mode 100644
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 f2c7cc4..e20a885 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
@@ -484,7 +484,7 @@
* 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)}. This function may get blocked when using StreamDecoder as it
- * invokes {@link #StreamDecoder.tryRefillBuffer(int)} in this function which will try to read
+ * invokes {@link StreamDecoder#tryRefillBuffer(int)} in this function which will try to read
* bytes from input.
*/
public abstract boolean isAtEnd() throws IOException;
diff --git a/java/core/src/main/java/com/google/protobuf/CodedInputStreamReader.java b/java/core/src/main/java/com/google/protobuf/CodedInputStreamReader.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java b/java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java b/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java
old mode 100755
new mode 100644
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 a20829e..6c09939 100644
--- a/java/core/src/main/java/com/google/protobuf/Descriptors.java
+++ b/java/core/src/main/java/com/google/protobuf/Descriptors.java
@@ -702,6 +702,11 @@
return Collections.unmodifiableList(Arrays.asList(oneofs));
}
+ /** Get a list of this message type's real oneofs. */
+ public List<OneofDescriptor> getRealOneofs() {
+ return Collections.unmodifiableList(Arrays.asList(oneofs).subList(0, realOneofCount));
+ }
+
/** Get a list of this message type's extensions. */
public List<FieldDescriptor> getExtensions() {
return Collections.unmodifiableList(Arrays.asList(extensions));
@@ -821,6 +826,7 @@
private final FieldDescriptor[] fields;
private final FieldDescriptor[] extensions;
private final OneofDescriptor[] oneofs;
+ private final int realOneofCount;
// Used to create a placeholder when the type cannot be found.
Descriptor(final String fullname) throws DescriptorValidationException {
@@ -846,6 +852,7 @@
this.fields = new FieldDescriptor[0];
this.extensions = new FieldDescriptor[0];
this.oneofs = new OneofDescriptor[0];
+ this.realOneofCount = 0;
// Create a placeholder FileDescriptor to hold this message.
this.file = new FileDescriptor(packageName, this);
@@ -899,6 +906,18 @@
}
}
+ int syntheticOneofCount = 0;
+ for (OneofDescriptor oneof : this.oneofs) {
+ if (oneof.isSynthetic()) {
+ syntheticOneofCount++;
+ } else {
+ if (syntheticOneofCount > 0) {
+ throw new DescriptorValidationException(this, "Synthetic oneofs must come last.");
+ }
+ }
+ }
+ this.realOneofCount = this.oneofs.length - syntheticOneofCount;
+
file.pool.addSymbol(this);
}
@@ -1125,6 +1144,40 @@
return containingOneof;
}
+ /** Get the field's containing oneof, only if non-synthetic. */
+ public OneofDescriptor getRealContainingOneof() {
+ return containingOneof != null && !containingOneof.isSynthetic() ? containingOneof : null;
+ }
+
+ /**
+ * Returns true if this field was syntactically written with "optional" in the .proto file.
+ * Excludes singular proto3 fields that do not have a label.
+ */
+ public boolean hasOptionalKeyword() {
+ return isProto3Optional
+ || (file.getSyntax() == Syntax.PROTO2 && isOptional() && getContainingOneof() == null);
+ }
+
+ /**
+ * Returns true if this field tracks presence, ie. does the field distinguish between "unset"
+ * and "present with default value."
+ *
+ * <p>This includes required, optional, and oneof fields. It excludes maps, repeated fields, and
+ * singular proto3 fields without "optional".
+ *
+ * <p>For fields where hasPresence() == true, the return value of msg.hasField() is semantically
+ * meaningful.
+ */
+ boolean hasPresence() {
+ if (isRepeated()) {
+ return false;
+ }
+ return getType() == Type.MESSAGE
+ || getType() == Type.GROUP
+ || getContainingOneof() != null
+ || file.getSyntax() == Syntax.PROTO2;
+ }
+
/**
* For extensions defined nested within message types, gets the outer type. Not valid for
* non-extension fields. For example, consider this {@code .proto} file:
@@ -1203,6 +1256,7 @@
private final String jsonName;
private final FileDescriptor file;
private final Descriptor extensionScope;
+ private final boolean isProto3Optional;
// Possibly initialized during cross-linking.
private Type type;
@@ -1327,6 +1381,8 @@
type = Type.valueOf(proto.getType());
}
+ isProto3Optional = proto.getProto3Optional();
+
if (getNumber() <= 0) {
throw new DescriptorValidationException(this, "Field numbers must be positive integers.");
}
@@ -2627,6 +2683,10 @@
return proto.getOptions();
}
+ public boolean isSynthetic() {
+ return fields.length == 1 && fields[0].isProto3Optional;
+ }
+
/** Get a list of this message type's fields. */
public List<FieldDescriptor> getFields() {
return Collections.unmodifiableList(Arrays.asList(fields));
diff --git a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
index ac14949..12824ab 100644
--- a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
@@ -141,6 +141,26 @@
}
@Override
+ public int indexOf(Object element) {
+ if (!(element instanceof Double)) {
+ return -1;
+ }
+ double unboxedElement = (Double) element;
+ int numElems = size();
+ for (int i = 0; i < numElems; i++) {
+ if (array[i] == unboxedElement) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public boolean contains(Object element) {
+ return indexOf(element) != -1;
+ }
+
+ @Override
public int size() {
return size;
}
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionSchema.java b/java/core/src/main/java/com/google/protobuf/ExtensionSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionSchemaFull.java b/java/core/src/main/java/com/google/protobuf/ExtensionSchemaFull.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java b/java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java
old mode 100755
new mode 100644
index 7f6846e..437cca2
--- a/java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java
+++ b/java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java
@@ -193,7 +193,7 @@
extensions.setField(extension.descriptor, value);
} else {
Object value = null;
- // Enum is a special case becasue unknown enum values will be put into UnknownFieldSetLite.
+ // Enum is a special case because unknown enum values will be put into UnknownFieldSetLite.
if (extension.getLiteType() == WireFormat.FieldType.ENUM) {
int number = reader.readInt32();
Object enumValue = extension.descriptor.getEnumType().findValueByNumber(number);
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionSchemas.java b/java/core/src/main/java/com/google/protobuf/ExtensionSchemas.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/FieldInfo.java b/java/core/src/main/java/com/google/protobuf/FieldInfo.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/FieldType.java b/java/core/src/main/java/com/google/protobuf/FieldType.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
index 9d2ab71..9589816 100644
--- a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
@@ -140,6 +140,26 @@
}
@Override
+ public int indexOf(Object element) {
+ if (!(element instanceof Float)) {
+ return -1;
+ }
+ float unboxedElement = (Float) element;
+ int numElems = size();
+ for (int i = 0; i < numElems; i++) {
+ if (array[i] == unboxedElement) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public boolean contains(Object element) {
+ return indexOf(element) != -1;
+ }
+
+ @Override
public int size() {
return size;
}
diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java
index 6713f43..de0ee11 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java
@@ -359,7 +359,7 @@
* TODO(xiaofeng): remove this after b/29368482 is fixed. We need to move this
* interface to AbstractMessage in order to versioning GeneratedMessage but
* this move breaks binary compatibility for AppEngine. After AppEngine is
- * fixed we can exlude this from google3.
+ * fixed we can exclude this from google3.
*/
protected interface BuilderParent extends AbstractMessage.BuilderParent {}
diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
index 1ee785d..8456713 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
@@ -121,7 +121,11 @@
return true;
}
- if (!getDefaultInstanceForType().getClass().isInstance(other)) {
+ if (other == null) {
+ return false;
+ }
+
+ if (this.getClass() != other.getClass()) {
return false;
}
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 5f7b387..86f88a0 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
@@ -515,7 +515,7 @@
* TODO(xiaofeng): remove this after b/29368482 is fixed. We need to move this
* interface to AbstractMessage in order to versioning GeneratedMessageV3 but
* this move breaks binary compatibility for AppEngine. After AppEngine is
- * fixed we can exlude this from google3.
+ * fixed we can exclude this from google3.
*/
protected interface BuilderParent extends AbstractMessage.BuilderParent {}
@@ -1987,9 +1987,9 @@
int oneofsSize = oneofs.length;
for (int i = 0; i < oneofsSize; i++) {
- oneofs[i] = new OneofAccessor(
- descriptor, camelCaseNames[i + fieldsSize],
- messageClass, builderClass);
+ oneofs[i] =
+ new OneofAccessor(
+ descriptor, i, camelCaseNames[i + fieldsSize], messageClass, builderClass);
}
initialized = true;
camelCaseNames = null;
@@ -2057,14 +2057,22 @@
/** OneofAccessor provides access to a single oneof. */
private static class OneofAccessor {
OneofAccessor(
- final Descriptor descriptor, final String camelCaseName,
+ final Descriptor descriptor,
+ final int oneofIndex,
+ final String camelCaseName,
final Class<? extends GeneratedMessageV3> messageClass,
final Class<? extends Builder> builderClass) {
this.descriptor = descriptor;
- caseMethod =
- getMethodOrDie(messageClass, "get" + camelCaseName + "Case");
- caseMethodBuilder =
- getMethodOrDie(builderClass, "get" + camelCaseName + "Case");
+ OneofDescriptor oneofDescriptor = descriptor.getOneofs().get(oneofIndex);
+ if (oneofDescriptor.isSynthetic()) {
+ caseMethod = null;
+ caseMethodBuilder = null;
+ fieldDescriptor = oneofDescriptor.getFields().get(0);
+ } else {
+ caseMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Case");
+ caseMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Case");
+ fieldDescriptor = null;
+ }
clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName);
}
@@ -2072,33 +2080,51 @@
private final Method caseMethod;
private final Method caseMethodBuilder;
private final Method clearMethod;
+ private final FieldDescriptor fieldDescriptor;
public boolean has(final GeneratedMessageV3 message) {
- if (((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber() == 0) {
- return false;
+ if (fieldDescriptor != null) {
+ return message.hasField(fieldDescriptor);
+ } else {
+ if (((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber() == 0) {
+ return false;
+ }
}
return true;
}
public boolean has(GeneratedMessageV3.Builder builder) {
- if (((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber() == 0) {
- return false;
+ if (fieldDescriptor != null) {
+ return builder.hasField(fieldDescriptor);
+ } else {
+ if (((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber() == 0) {
+ return false;
+ }
}
return true;
}
public FieldDescriptor get(final GeneratedMessageV3 message) {
- int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber();
- if (fieldNumber > 0) {
- return descriptor.findFieldByNumber(fieldNumber);
+ if (fieldDescriptor != null) {
+ return message.hasField(fieldDescriptor) ? fieldDescriptor : null;
+ } else {
+ int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber();
+ if (fieldNumber > 0) {
+ return descriptor.findFieldByNumber(fieldNumber);
+ }
}
return null;
}
public FieldDescriptor get(GeneratedMessageV3.Builder builder) {
- int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber();
- if (fieldNumber > 0) {
- return descriptor.findFieldByNumber(fieldNumber);
+ if (fieldDescriptor != null) {
+ return builder.hasField(fieldDescriptor) ? fieldDescriptor : null;
+ } else {
+ int fieldNumber =
+ ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber();
+ if (fieldNumber > 0) {
+ return descriptor.findFieldByNumber(fieldNumber);
+ }
}
return null;
}
@@ -2108,10 +2134,6 @@
}
}
- private static boolean supportFieldPresence(FileDescriptor file) {
- return file.getSyntax() == FileDescriptor.Syntax.PROTO2;
- }
-
// ---------------------------------------------------------------
private static class SingularFieldAccessor implements FieldAccessor {
@@ -2216,9 +2238,13 @@
final Class<? extends GeneratedMessageV3> messageClass,
final Class<? extends Builder> builderClass,
final String containingOneofCamelCaseName) {
- isOneofField = descriptor.getContainingOneof() != null;
- hasHasMethod = supportFieldPresence(descriptor.getFile())
- || (!isOneofField && descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE);
+ isOneofField =
+ descriptor.getContainingOneof() != null
+ && !descriptor.getContainingOneof().isSynthetic();
+ hasHasMethod =
+ descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO2
+ || descriptor.hasOptionalKeyword()
+ || (!isOneofField && descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE);
ReflectionInvoker reflectionInvoker =
new ReflectionInvoker(
descriptor,
@@ -3086,7 +3112,7 @@
serializeMapTo(out, m, defaultEntry, fieldNumber);
return;
}
- // Sorting the unboxed keys and then look up the values during serialziation is 2x faster
+ // Sorting the unboxed keys and then look up the values during serialization is 2x faster
// than sorting map entries with a custom comparator directly.
int[] keys = new int[m.size()];
int index = 0;
@@ -3142,7 +3168,7 @@
return;
}
- // Sorting the String keys and then look up the values during serialziation is 25% faster than
+ // Sorting the String keys and then look up the values during serialization is 25% faster than
// sorting map entries with a custom comparator directly.
String[] keys = new String[m.size()];
keys = m.keySet().toArray(keys);
diff --git a/java/core/src/main/java/com/google/protobuf/IntArrayList.java b/java/core/src/main/java/com/google/protobuf/IntArrayList.java
index 98f1f81..e9c3b1a 100644
--- a/java/core/src/main/java/com/google/protobuf/IntArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/IntArrayList.java
@@ -140,6 +140,26 @@
}
@Override
+ public int indexOf(Object element) {
+ if (!(element instanceof Integer)) {
+ return -1;
+ }
+ int unboxedElement = (Integer) element;
+ int numElems = size();
+ for (int i = 0; i < numElems; i++) {
+ if (array[i] == unboxedElement) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public boolean contains(Object element) {
+ return indexOf(element) != -1;
+ }
+
+ @Override
public int size() {
return size;
}
diff --git a/java/core/src/main/java/com/google/protobuf/JavaType.java b/java/core/src/main/java/com/google/protobuf/JavaType.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java b/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
index d6b594d..6fab26f 100644
--- a/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
+++ b/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
@@ -274,7 +274,7 @@
// At least one is parsed and both contain data. We won't drop any extensions here directly, but
// in the case that the extension registries are not the same then we might in the future if we
- // need to serialze and parse a message again.
+ // need to serialize and parse a message again.
if (this.value == null && other.value != null) {
setValue(mergeValueAndBytes(other.value, this.delayedBytes, this.extensionRegistry));
return;
diff --git a/java/core/src/main/java/com/google/protobuf/ListFieldSchema.java b/java/core/src/main/java/com/google/protobuf/ListFieldSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/LongArrayList.java b/java/core/src/main/java/com/google/protobuf/LongArrayList.java
index 2dd15b4..04f4475 100644
--- a/java/core/src/main/java/com/google/protobuf/LongArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/LongArrayList.java
@@ -140,6 +140,26 @@
}
@Override
+ public int indexOf(Object element) {
+ if (!(element instanceof Long)) {
+ return -1;
+ }
+ long unboxedElement = (Long) element;
+ int numElems = size();
+ for (int i = 0; i < numElems; i++) {
+ if (array[i] == unboxedElement) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public boolean contains(Object element) {
+ return indexOf(element) != -1;
+ }
+
+ @Override
public int size() {
return size;
}
diff --git a/java/core/src/main/java/com/google/protobuf/ManifestSchemaFactory.java b/java/core/src/main/java/com/google/protobuf/ManifestSchemaFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/MapFieldSchema.java b/java/core/src/main/java/com/google/protobuf/MapFieldSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/MapFieldSchemaFull.java b/java/core/src/main/java/com/google/protobuf/MapFieldSchemaFull.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java b/java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/MapFieldSchemas.java b/java/core/src/main/java/com/google/protobuf/MapFieldSchemas.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/MessageInfo.java b/java/core/src/main/java/com/google/protobuf/MessageInfo.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/MessageInfoFactory.java b/java/core/src/main/java/com/google/protobuf/MessageInfoFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/MessageSchema.java b/java/core/src/main/java/com/google/protobuf/MessageSchema.java
old mode 100755
new mode 100644
index 8f9ce73..139e55a
--- a/java/core/src/main/java/com/google/protobuf/MessageSchema.java
+++ b/java/core/src/main/java/com/google/protobuf/MessageSchema.java
@@ -89,6 +89,7 @@
private static final int FIELD_TYPE_MASK = 0x0FF00000;
private static final int REQUIRED_MASK = 0x10000000;
private static final int ENFORCE_UTF8_MASK = 0x20000000;
+ private static final int NO_PRESENCE_SENTINEL = -1 & OFFSET_MASK;
private static final int[] EMPTY_INT_ARRAY = new int[0];
/** An offset applied to the field type ID for scalar fields that are a member of a oneof. */
@@ -118,6 +119,11 @@
* [70 - 75] field presence mask shift (unused for oneof/repeated fields)
* [76 - 95] presence field offset / oneof case field offset / cached size field offset
* </pre>
+ *
+ * Note that presence field offset can only use 20 bits - 1. All bits set to 1 is the sentinel
+ * value for non-presence. This is not validated at runtime, we simply assume message layouts
+ * will not exceed 1MB (assuming ~10 bytes per field, that implies 100k fields which should hit
+ * other javac limits first).
*/
private final int[] buffer;
@@ -260,7 +266,7 @@
}
next = result | (next << shift);
}
- final int flags = next;
+ final int unusedFlags = next;
next = info.charAt(i++);
if (next >= 0xD800) {
@@ -464,8 +470,7 @@
|| oneofFieldType == 17 /* FieldType.GROUP */) {
objects[bufferIndex / INTS_PER_FIELD * 2 + 1] = messageInfoObjects[objectsPosition++];
} else if (oneofFieldType == 12 /* FieldType.ENUM */) {
- // proto2
- if ((flags & 0x1) == 0x1) {
+ if (!isProto3) {
objects[bufferIndex / INTS_PER_FIELD * 2 + 1] = messageInfoObjects[objectsPosition++];
}
}
@@ -508,7 +513,7 @@
} else if (fieldType == 12 /* FieldType.ENUM */
|| fieldType == 30 /* FieldType.ENUM_LIST */
|| fieldType == 44 /* FieldType.ENUM_LIST_PACKED */) {
- if ((flags & 0x1) == 0x1) {
+ if (!isProto3) {
objects[bufferIndex / INTS_PER_FIELD * 2 + 1] = messageInfoObjects[objectsPosition++];
}
} else if (fieldType == 50 /* FieldType.MAP */) {
@@ -520,7 +525,8 @@
}
fieldOffset = (int) unsafe.objectFieldOffset(field);
- if ((flags & 0x1) == 0x1 && fieldType <= 17 /* FieldType.GROUP */) {
+ boolean hasHasBit = (fieldTypeWithExtraBits & 0x1000) == 0x1000;
+ if (hasHasBit && fieldType <= 17 /* FieldType.GROUP */) {
next = info.charAt(i++);
if (next >= 0xD800) {
int result = next & 0x1FFF;
@@ -546,7 +552,7 @@
presenceFieldOffset = (int) unsafe.objectFieldOffset(hasBitsField);
presenceMaskShift = hasBitsIndex % 32;
} else {
- presenceFieldOffset = 0;
+ presenceFieldOffset = NO_PRESENCE_SENTINEL;
presenceMaskShift = 0;
}
@@ -662,7 +668,7 @@
// We found the entry for the next field. Store the entry in the manifest for
// this field and increment the field index.
- storeFieldData(fi, buffer, bufferIndex, isProto3, objects);
+ storeFieldData(fi, buffer, bufferIndex, objects);
// Convert field number to index
if (checkInitializedIndex < checkInitialized.length
@@ -719,7 +725,7 @@
}
private static void storeFieldData(
- FieldInfo fi, int[] buffer, int bufferIndex, boolean proto3, Object[] objects) {
+ FieldInfo fi, int[] buffer, int bufferIndex, Object[] objects) {
final int fieldOffset;
final int typeId;
final int presenceMaskShift;
@@ -735,8 +741,13 @@
FieldType type = fi.getType();
fieldOffset = (int) UnsafeUtil.objectFieldOffset(fi.getField());
typeId = type.id();
- if (!proto3 && !type.isList() && !type.isMap()) {
- presenceFieldOffset = (int) UnsafeUtil.objectFieldOffset(fi.getPresenceField());
+ if (!type.isList() && !type.isMap()) {
+ Field presenceField = fi.getPresenceField();
+ if (presenceField == null) {
+ presenceFieldOffset = NO_PRESENCE_SENTINEL;
+ } else {
+ presenceFieldOffset = (int) UnsafeUtil.objectFieldOffset(presenceField);
+ }
presenceMaskShift = Integer.numberOfTrailingZeros(fi.getPresenceMask());
} else {
if (fi.getCachedSizeField() == null) {
@@ -1408,13 +1419,13 @@
public int getSerializedSize(T message) {
return proto3 ? getSerializedSizeProto3(message) : getSerializedSizeProto2(message);
}
-
+
@SuppressWarnings("unchecked")
private int getSerializedSizeProto2(T message) {
int size = 0;
final sun.misc.Unsafe unsafe = UNSAFE;
- int currentPresenceFieldOffset = -1;
+ int currentPresenceFieldOffset = NO_PRESENCE_SENTINEL;
int currentPresenceField = 0;
for (int i = 0; i < buffer.length; i += INTS_PER_FIELD) {
final int typeAndOffset = typeAndOffsetAt(i);
@@ -2548,7 +2559,7 @@
nextExtension = extensionIterator.next();
}
}
- int currentPresenceFieldOffset = -1;
+ int currentPresenceFieldOffset = NO_PRESENCE_SENTINEL;
int currentPresenceField = 0;
final int bufferLength = buffer.length;
final sun.misc.Unsafe unsafe = UNSAFE;
@@ -2924,7 +2935,6 @@
nextExtension = extensionIterator.next();
}
}
-
final int bufferLength = buffer.length;
for (int pos = 0; pos < bufferLength; pos += INTS_PER_FIELD) {
final int typeAndOffset = typeAndOffsetAt(pos);
@@ -4867,7 +4877,7 @@
T message, byte[] data, int position, int limit, int endGroup, Registers registers)
throws IOException {
final sun.misc.Unsafe unsafe = UNSAFE;
- int currentPresenceFieldOffset = -1;
+ int currentPresenceFieldOffset = NO_PRESENCE_SENTINEL;
int currentPresenceField = 0;
int tag = 0;
int oldNumber = -1;
@@ -4901,7 +4911,7 @@
// We cache the 32-bit has-bits integer value and only write it back when parsing a field
// using a different has-bits integer.
if (presenceFieldOffset != currentPresenceFieldOffset) {
- if (currentPresenceFieldOffset != -1) {
+ if (currentPresenceFieldOffset != NO_PRESENCE_SENTINEL) {
unsafe.putInt(message, (long) currentPresenceFieldOffset, currentPresenceField);
}
currentPresenceFieldOffset = presenceFieldOffset;
@@ -5143,7 +5153,7 @@
tag, data, position, limit, getMutableUnknownFields(message), registers);
}
}
- if (currentPresenceFieldOffset != -1) {
+ if (currentPresenceFieldOffset != NO_PRESENCE_SENTINEL) {
unsafe.putInt(message, (long) currentPresenceFieldOffset, currentPresenceField);
}
UnknownFieldSetLite unknownFields = null;
@@ -5175,6 +5185,8 @@
private int parseProto3Message(
T message, byte[] data, int position, int limit, Registers registers) throws IOException {
final sun.misc.Unsafe unsafe = UNSAFE;
+ int currentPresenceFieldOffset = NO_PRESENCE_SENTINEL;
+ int currentPresenceField = 0;
int tag = 0;
int oldNumber = -1;
int pos = 0;
@@ -5200,11 +5212,30 @@
final int fieldType = type(typeAndOffset);
final long fieldOffset = offset(typeAndOffset);
if (fieldType <= 17) {
+ // Proto3 optional fields have has-bits.
+ final int presenceMaskAndOffset = buffer[pos + 2];
+ final int presenceMask = 1 << (presenceMaskAndOffset >>> OFFSET_BITS);
+ final int presenceFieldOffset = presenceMaskAndOffset & OFFSET_MASK;
+ // We cache the 32-bit has-bits integer value and only write it back when parsing a field
+ // using a different has-bits integer.
+ //
+ // Note that for fields that do not have hasbits, we unconditionally write and discard
+ // the data.
+ if (presenceFieldOffset != currentPresenceFieldOffset) {
+ if (currentPresenceFieldOffset != NO_PRESENCE_SENTINEL) {
+ unsafe.putInt(message, (long) currentPresenceFieldOffset, currentPresenceField);
+ }
+ if (presenceFieldOffset != NO_PRESENCE_SENTINEL) {
+ currentPresenceField = unsafe.getInt(message, (long) presenceFieldOffset);
+ }
+ currentPresenceFieldOffset = presenceFieldOffset;
+ }
switch (fieldType) {
case 0: // DOUBLE:
if (wireType == WireFormat.WIRETYPE_FIXED64) {
UnsafeUtil.putDouble(message, fieldOffset, decodeDouble(data, position));
position += 8;
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5212,6 +5243,7 @@
if (wireType == WireFormat.WIRETYPE_FIXED32) {
UnsafeUtil.putFloat(message, fieldOffset, decodeFloat(data, position));
position += 4;
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5220,6 +5252,7 @@
if (wireType == WireFormat.WIRETYPE_VARINT) {
position = decodeVarint64(data, position, registers);
unsafe.putLong(message, fieldOffset, registers.long1);
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5228,6 +5261,7 @@
if (wireType == WireFormat.WIRETYPE_VARINT) {
position = decodeVarint32(data, position, registers);
unsafe.putInt(message, fieldOffset, registers.int1);
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5236,6 +5270,7 @@
if (wireType == WireFormat.WIRETYPE_FIXED64) {
unsafe.putLong(message, fieldOffset, decodeFixed64(data, position));
position += 8;
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5244,6 +5279,7 @@
if (wireType == WireFormat.WIRETYPE_FIXED32) {
unsafe.putInt(message, fieldOffset, decodeFixed32(data, position));
position += 4;
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5251,6 +5287,7 @@
if (wireType == WireFormat.WIRETYPE_VARINT) {
position = decodeVarint64(data, position, registers);
UnsafeUtil.putBoolean(message, fieldOffset, registers.long1 != 0);
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5262,6 +5299,7 @@
position = decodeStringRequireUtf8(data, position, registers);
}
unsafe.putObject(message, fieldOffset, registers.object1);
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5277,6 +5315,7 @@
unsafe.putObject(
message, fieldOffset, Internal.mergeMessage(oldValue, registers.object1));
}
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5284,6 +5323,7 @@
if (wireType == WireFormat.WIRETYPE_LENGTH_DELIMITED) {
position = decodeBytes(data, position, registers);
unsafe.putObject(message, fieldOffset, registers.object1);
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5291,6 +5331,7 @@
if (wireType == WireFormat.WIRETYPE_VARINT) {
position = decodeVarint32(data, position, registers);
unsafe.putInt(message, fieldOffset, registers.int1);
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5299,6 +5340,7 @@
position = decodeVarint32(data, position, registers);
unsafe.putInt(
message, fieldOffset, CodedInputStream.decodeZigZag32(registers.int1));
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5307,6 +5349,7 @@
position = decodeVarint64(data, position, registers);
unsafe.putLong(
message, fieldOffset, CodedInputStream.decodeZigZag64(registers.long1));
+ currentPresenceField |= presenceMask;
continue;
}
break;
@@ -5381,6 +5424,9 @@
position = decodeUnknownField(
tag, data, position, limit, getMutableUnknownFields(message), registers);
}
+ if (currentPresenceFieldOffset != NO_PRESENCE_SENTINEL) {
+ unsafe.putInt(message, (long) currentPresenceFieldOffset, currentPresenceField);
+ }
if (position != limit) {
throw InvalidProtocolBufferException.parseFailure();
}
@@ -5502,28 +5548,26 @@
@Override
public final boolean isInitialized(T message) {
- int currentPresenceFieldOffset = -1;
+ int currentPresenceFieldOffset = NO_PRESENCE_SENTINEL;
int currentPresenceField = 0;
for (int i = 0; i < checkInitializedCount; i++) {
final int pos = intArray[i];
final int number = numberAt(pos);
-
final int typeAndOffset = typeAndOffsetAt(pos);
- int presenceMaskAndOffset = 0;
- int presenceMask = 0;
- if (!proto3) {
- presenceMaskAndOffset = buffer[pos + 2];
- final int presenceFieldOffset = presenceMaskAndOffset & OFFSET_MASK;
- presenceMask = 1 << (presenceMaskAndOffset >>> OFFSET_BITS);
- if (presenceFieldOffset != currentPresenceFieldOffset) {
- currentPresenceFieldOffset = presenceFieldOffset;
+ int presenceMaskAndOffset = buffer[pos + 2];
+ final int presenceFieldOffset = presenceMaskAndOffset & OFFSET_MASK;
+ int presenceMask = 1 << (presenceMaskAndOffset >>> OFFSET_BITS);
+ if (presenceFieldOffset != currentPresenceFieldOffset) {
+ currentPresenceFieldOffset = presenceFieldOffset;
+ if (currentPresenceFieldOffset != NO_PRESENCE_SENTINEL) {
currentPresenceField = UNSAFE.getInt(message, (long) presenceFieldOffset);
}
}
if (isRequired(typeAndOffset)) {
- if (!isFieldPresent(message, pos, currentPresenceField, presenceMask)) {
+ if (!isFieldPresent(
+ message, pos, currentPresenceFieldOffset, currentPresenceField, presenceMask)) {
return false;
}
// If a required message field is set but has no required fields of it's own, we still
@@ -5534,7 +5578,8 @@
switch (type(typeAndOffset)) {
case 9: // MESSAGE
case 17: // GROUP
- if (isFieldPresent(message, pos, currentPresenceField, presenceMask)
+ if (isFieldPresent(
+ message, pos, currentPresenceFieldOffset, currentPresenceField, presenceMask)
&& !isInitialized(message, typeAndOffset, getMessageFieldSchema(pos))) {
return false;
}
@@ -5744,8 +5789,9 @@
return isFieldPresent(message, pos) == isFieldPresent(other, pos);
}
- private boolean isFieldPresent(T message, int pos, int presenceField, int presenceMask) {
- if (proto3) {
+ private boolean isFieldPresent(
+ T message, int pos, int presenceFieldOffset, int presenceField, int presenceMask) {
+ if (presenceFieldOffset == NO_PRESENCE_SENTINEL) {
return isFieldPresent(message, pos);
} else {
return (presenceField & presenceMask) != 0;
@@ -5753,7 +5799,9 @@
}
private boolean isFieldPresent(T message, int pos) {
- if (proto3) {
+ final int presenceMaskAndOffset = presenceMaskAndOffsetAt(pos);
+ final long presenceFieldOffset = presenceMaskAndOffset & OFFSET_MASK;
+ if (presenceFieldOffset == NO_PRESENCE_SENTINEL) {
final int typeAndOffset = typeAndOffsetAt(pos);
final long offset = offset(typeAndOffset);
switch (type(typeAndOffset)) {
@@ -5804,20 +5852,18 @@
throw new IllegalArgumentException();
}
} else {
- int presenceMaskAndOffset = presenceMaskAndOffsetAt(pos);
final int presenceMask = 1 << (presenceMaskAndOffset >>> OFFSET_BITS);
return (UnsafeUtil.getInt(message, presenceMaskAndOffset & OFFSET_MASK) & presenceMask) != 0;
}
}
private void setFieldPresent(T message, int pos) {
- if (proto3) {
- // Proto3 doesn't have presence fields
+ int presenceMaskAndOffset = presenceMaskAndOffsetAt(pos);
+ final long presenceFieldOffset = presenceMaskAndOffset & OFFSET_MASK;
+ if (presenceFieldOffset == NO_PRESENCE_SENTINEL) {
return;
}
- int presenceMaskAndOffset = presenceMaskAndOffsetAt(pos);
final int presenceMask = 1 << (presenceMaskAndOffset >>> OFFSET_BITS);
- final long presenceFieldOffset = presenceMaskAndOffset & OFFSET_MASK;
UnsafeUtil.putInt(
message,
presenceFieldOffset,
diff --git a/java/core/src/main/java/com/google/protobuf/MessageSetSchema.java b/java/core/src/main/java/com/google/protobuf/MessageSetSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/NewInstanceSchema.java b/java/core/src/main/java/com/google/protobuf/NewInstanceSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java b/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaLite.java b/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaLite.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/NewInstanceSchemas.java b/java/core/src/main/java/com/google/protobuf/NewInstanceSchemas.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/OneofInfo.java b/java/core/src/main/java/com/google/protobuf/OneofInfo.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/ProtoSyntax.java b/java/core/src/main/java/com/google/protobuf/ProtoSyntax.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/Protobuf.java b/java/core/src/main/java/com/google/protobuf/Protobuf.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/ProtobufLists.java b/java/core/src/main/java/com/google/protobuf/ProtobufLists.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java b/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java
old mode 100755
new mode 100644
index b9a3d2b..72f56ed
--- a/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java
+++ b/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java
@@ -96,7 +96,7 @@
* If the field is in an oneof:
*
* <ul>
- * <li>[2]: oenof index
+ * <li>[2]: oneof index
* </ul>
*
* For other types, the field entry only has field number and field type.
diff --git a/java/core/src/main/java/com/google/protobuf/Reader.java b/java/core/src/main/java/com/google/protobuf/Reader.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java
index f3b09fb..f51436c 100644
--- a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java
+++ b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java
@@ -346,9 +346,8 @@
// If we can inspect the size, we can more efficiently add messages.
int size = -1;
if (values instanceof Collection) {
- @SuppressWarnings("unchecked")
- final Collection<MType> collection = (Collection<MType>) values;
- if (collection.size() == 0) {
+ final Collection<?> collection = (Collection<?>) values;
+ if (collection.isEmpty()) {
return this;
}
size = collection.size();
@@ -408,8 +407,7 @@
/**
* Removes the element at the specified position in this list. Shifts any subsequent elements to
- * the left (subtracts one from their indices). Returns the element that was removed from the
- * list.
+ * the left (subtracts one from their indices).
*
* @param index the index at which to remove the message
*/
diff --git a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
index fb1667c..91bc3e2 100644
--- a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
+++ b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
@@ -346,9 +346,8 @@
// If we can inspect the size, we can more efficiently add messages.
int size = -1;
if (values instanceof Collection) {
- @SuppressWarnings("unchecked")
- final Collection<MType> collection = (Collection<MType>) values;
- if (collection.size() == 0) {
+ final Collection<?> collection = (Collection<?>) values;
+ if (collection.isEmpty()) {
return this;
}
size = collection.size();
@@ -408,8 +407,7 @@
/**
* Removes the element at the specified position in this list. Shifts any subsequent elements to
- * the left (subtracts one from their indices). Returns the element that was removed from the
- * list.
+ * the left (subtracts one from their indices).
*
* @param index the index at which to remove the message
*/
diff --git a/java/core/src/main/java/com/google/protobuf/Schema.java b/java/core/src/main/java/com/google/protobuf/Schema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/SchemaFactory.java b/java/core/src/main/java/com/google/protobuf/SchemaFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/SchemaUtil.java b/java/core/src/main/java/com/google/protobuf/SchemaUtil.java
old mode 100755
new mode 100644
index 50957fc..4c8bb06
--- a/java/core/src/main/java/com/google/protobuf/SchemaUtil.java
+++ b/java/core/src/main/java/com/google/protobuf/SchemaUtil.java
@@ -767,7 +767,7 @@
* logic in the JDK</a>.
*
* @param lo the lowest fieldNumber contained within the message.
- * @param hi the higest fieldNumber contained within the message.
+ * @param hi the highest fieldNumber contained within the message.
* @param numFields the total number of fields in the message.
* @return {@code true} if tableswitch should be used, rather than lookupswitch.
*/
diff --git a/java/core/src/main/java/com/google/protobuf/StructuralMessageInfo.java b/java/core/src/main/java/com/google/protobuf/StructuralMessageInfo.java
old mode 100755
new mode 100644
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 f3f1011..673343d 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java
@@ -34,10 +34,12 @@
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
+import com.google.protobuf.MessageReflection.MergeTarget;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.CharBuffer;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -137,7 +139,7 @@
/**
* Like {@code print()}, but writes directly to a {@code String} and returns it.
*
- * @deprecated Use {@link MessageOrBuilder#toString()}
+ * @deprecated Use {@code message.toString()}
*/
@Deprecated
public static String printToString(final MessageOrBuilder message) {
@@ -419,7 +421,17 @@
private void printField(
final FieldDescriptor field, final Object value, final TextGenerator generator)
throws IOException {
- if (field.isRepeated()) {
+ // Sort map field entries by key
+ if (field.isMapField()) {
+ List<MapEntryAdapter> adapters = new ArrayList<>();
+ for (Object entry : (List<?>) value) {
+ adapters.add(new MapEntryAdapter(entry, field));
+ }
+ Collections.sort(adapters);
+ for (MapEntryAdapter adapter : adapters) {
+ printSingleField(field, adapter.getEntry(), generator);
+ }
+ } else if (field.isRepeated()) {
// Repeated field. Print each element.
for (Object element : (List<?>) value) {
printSingleField(field, element, generator);
@@ -430,6 +442,94 @@
}
/**
+ * An adapter class that can take a MapEntry or a MutableMapEntry and returns its key and entry.
+ * This class is created solely for the purpose of sorting map entries by its key and prevent
+ * duplicated logic by having a separate comparator for MapEntry and MutableMapEntry.
+ */
+ private static class MapEntryAdapter implements Comparable<MapEntryAdapter> {
+ private Object entry;
+
+ @SuppressWarnings({"rawtypes"})
+ private MapEntry mapEntry;
+
+
+ private final FieldDescriptor.JavaType fieldType;
+
+ public MapEntryAdapter(Object entry, FieldDescriptor fieldDescriptor) {
+ if (entry instanceof MapEntry) {
+ this.mapEntry = (MapEntry) entry;
+ } else {
+ this.entry = entry;
+ }
+ this.fieldType = extractFieldType(fieldDescriptor);
+ }
+
+ private static FieldDescriptor.JavaType extractFieldType(FieldDescriptor fieldDescriptor) {
+ return fieldDescriptor.getMessageType().getFields().get(0).getJavaType();
+ }
+
+ public Object getKey() {
+ if (mapEntry != null) {
+ return mapEntry.getKey();
+ }
+ return null;
+ }
+
+ public Object getEntry() {
+ if (mapEntry != null) {
+ return mapEntry;
+ }
+ return entry;
+ }
+
+ @Override
+ public int compareTo(MapEntryAdapter b) {
+ if (getKey() == null || b.getKey() == null) {
+ logger.info("Invalid key for map field.");
+ return -1;
+ }
+ switch (fieldType) {
+ case BOOLEAN:
+ boolean aBoolean = (boolean) getKey();
+ boolean bBoolean = (boolean) b.getKey();
+ if (aBoolean == bBoolean) {
+ return 0;
+ } else if (aBoolean) {
+ return 1;
+ } else {
+ return -1;
+ }
+ case LONG:
+ long aLong = (long) getKey();
+ long bLong = (long) b.getKey();
+ if (aLong < bLong) {
+ return -1;
+ } else if (aLong > bLong) {
+ return 1;
+ } else {
+ return 0;
+ }
+ case INT:
+ return (int) getKey() - (int) b.getKey();
+ case STRING:
+ String aString = (String) getKey();
+ String bString = (String) b.getKey();
+ if (aString == null && bString == null) {
+ return 0;
+ } else if (aString == null && bString != null) {
+ return -1;
+ } else if (aString != null && bString == null) {
+ return 1;
+ } else {
+ return aString.compareTo(bString);
+ }
+ default:
+ return 0;
+ }
+ }
+ }
+
+ /**
* Outputs a textual representation of the value of given field value.
*
* @param field the descriptor of the field
@@ -1708,6 +1808,12 @@
final Descriptor type = target.getDescriptorForType();
ExtensionRegistry.ExtensionInfo extension = null;
+ if ("google.protobuf.Any".equals(type.getFullName()) && tokenizer.tryConsume("[")) {
+ mergeAnyFieldValue(tokenizer, extensionRegistry, target, parseTreeBuilder, unknownFields,
+ type);
+ return;
+ }
+
if (tokenizer.tryConsume("[")) {
// An extension.
final StringBuilder name = new StringBuilder(tokenizer.consumeIdentifier());
@@ -1928,9 +2034,13 @@
// Try to parse human readable format of Any in the form: [type_url]: { ... }
if (field.getMessageType().getFullName().equals("google.protobuf.Any")
&& tokenizer.tryConsume("[")) {
- value =
- consumeAnyFieldValue(
- tokenizer, extensionRegistry, field, parseTreeBuilder, unknownFields);
+ // Use Proto reflection here since depending on Any would intoduce a cyclic dependency
+ // (java_proto_library for any_java_proto depends on the protobuf_impl).
+ Message anyBuilder = DynamicMessage.getDefaultInstance(field.getMessageType());
+ MessageReflection.MergeTarget anyField = target.newMergeTargetForField(field, anyBuilder);
+ mergeAnyFieldValue(tokenizer, extensionRegistry, anyField, parseTreeBuilder,
+ unknownFields, field.getMessageType());
+ value = anyField.finish();
tokenizer.consume(endToken);
} else {
Message defaultInstance = (extension == null) ? null : extension.defaultInstance;
@@ -2052,12 +2162,13 @@
}
}
- private Object consumeAnyFieldValue(
+ private void mergeAnyFieldValue(
final Tokenizer tokenizer,
final ExtensionRegistry extensionRegistry,
- final FieldDescriptor field,
+ MergeTarget target,
final TextFormatParseInfoTree.Builder parseTreeBuilder,
- List<UnknownField> unknownFields)
+ List<UnknownField> unknownFields,
+ Descriptor anyDescriptor)
throws ParseException {
// Try to parse human readable format of Any in the form: [type_url]: { ... }
StringBuilder typeUrlBuilder = new StringBuilder();
@@ -2105,21 +2216,13 @@
mergeField(tokenizer, extensionRegistry, contentTarget, parseTreeBuilder, unknownFields);
}
- // Serialize the content and put it back into an Any. Note that we can't depend on Any here
- // because of a cyclic dependency (java_proto_library for any_java_proto depends on the
- // protobuf_impl), so we need to construct the Any using proto reflection.
- Descriptor anyDescriptor = field.getMessageType();
- Message.Builder anyBuilder =
- DynamicMessage.getDefaultInstance(anyDescriptor).newBuilderForType();
- anyBuilder.setField(anyDescriptor.findFieldByName("type_url"), typeUrlBuilder.toString());
- anyBuilder.setField(
+ target.setField(anyDescriptor.findFieldByName("type_url"), typeUrlBuilder.toString());
+ target.setField(
anyDescriptor.findFieldByName("value"), contentBuilder.build().toByteString());
-
- return anyBuilder.build();
}
/** Skips the next field including the field's name and value. */
- private void skipField(Tokenizer tokenizer) throws ParseException {
+ private static void skipField(Tokenizer tokenizer) throws ParseException {
if (tokenizer.tryConsume("[")) {
// Extension name.
do {
@@ -2151,7 +2254,7 @@
/**
* Skips the whole body of a message including the beginning delimiter and the ending delimiter.
*/
- private void skipFieldMessage(Tokenizer tokenizer) throws ParseException {
+ private static void skipFieldMessage(Tokenizer tokenizer) throws ParseException {
final String delimiter;
if (tokenizer.tryConsume("<")) {
delimiter = ">";
@@ -2166,7 +2269,7 @@
}
/** Skips a field value. */
- private void skipFieldValue(Tokenizer tokenizer) throws ParseException {
+ private static void skipFieldValue(Tokenizer tokenizer) throws ParseException {
if (tokenizer.tryConsumeString()) {
while (tokenizer.tryConsumeString()) {}
return;
diff --git a/java/core/src/main/java/com/google/protobuf/TypeRegistry.java b/java/core/src/main/java/com/google/protobuf/TypeRegistry.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSchema.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
index 2f6315c..b2cb7be 100644
--- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
+++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
@@ -301,7 +301,7 @@
return size;
}
- private static boolean equals(int[] tags1, int[] tags2, int count) {
+ private static boolean tagsEquals(int[] tags1, int[] tags2, int count) {
for (int i = 0; i < count; ++i) {
if (tags1[i] != tags2[i]) {
return false;
@@ -310,7 +310,7 @@
return true;
}
- private static boolean equals(Object[] objects1, Object[] objects2, int count) {
+ private static boolean objectsEquals(Object[] objects1, Object[] objects2, int count) {
for (int i = 0; i < count; ++i) {
if (!objects1[i].equals(objects2[i])) {
return false;
@@ -335,8 +335,8 @@
UnknownFieldSetLite other = (UnknownFieldSetLite) obj;
if (count != other.count
- || !equals(tags, other.tags, count)
- || !equals(objects, other.objects, count)) {
+ || !tagsEquals(tags, other.tags, count)
+ || !objectsEquals(objects, other.objects, count)) {
return false;
}
diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetSchema.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetSchema.java
old mode 100755
new mode 100644
diff --git a/java/core/src/main/java/com/google/protobuf/Writer.java b/java/core/src/main/java/com/google/protobuf/Writer.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractProto2LiteSchemaTest.java b/java/core/src/test/java/com/google/protobuf/AbstractProto2LiteSchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractProto2SchemaTest.java b/java/core/src/test/java/com/google/protobuf/AbstractProto2SchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractProto3LiteSchemaTest.java b/java/core/src/test/java/com/google/protobuf/AbstractProto3LiteSchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractProto3SchemaTest.java b/java/core/src/test/java/com/google/protobuf/AbstractProto3SchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractSchemaTest.java b/java/core/src/test/java/com/google/protobuf/AbstractSchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/ArrayDecodersTest.java b/java/core/src/test/java/com/google/protobuf/ArrayDecodersTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/BinaryProtocolTest.java b/java/core/src/test/java/com/google/protobuf/BinaryProtocolTest.java
old mode 100755
new mode 100644
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 ae50071..805b7b0 100644
--- a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
@@ -140,6 +140,68 @@
}
}
+ public void testIndexOf_nullElement() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(null));
+ }
+
+ public void testIndexOf_incompatibleElementType() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(new Object()));
+ }
+
+ public void testIndexOf_notInList() {
+ assertEquals(-1, UNARY_LIST.indexOf(false));
+ }
+
+ public void testIndexOf_notInListWithDuplicates() {
+ BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true);
+ assertEquals(-1, listWithDupes.indexOf(false));
+ }
+
+ public void testIndexOf_inList() {
+ assertEquals(1, TERTIARY_LIST.indexOf(false));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchAtHead() {
+ BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true, false);
+ assertEquals(0, listWithDupes.indexOf(true));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchMidList() {
+ BooleanArrayList listWithDupes = newImmutableBooleanArrayList(false, true, true, false);
+ assertEquals(1, listWithDupes.indexOf(true));
+ }
+
+ public void testContains_nullElement() {
+ assertEquals(false, TERTIARY_LIST.contains(null));
+ }
+
+ public void testContains_incompatibleElementType() {
+ assertEquals(false, TERTIARY_LIST.contains(new Object()));
+ }
+
+ public void testContains_notInList() {
+ assertEquals(false, UNARY_LIST.contains(false));
+ }
+
+ public void testContains_notInListWithDuplicates() {
+ BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true);
+ assertEquals(false, listWithDupes.contains(false));
+ }
+
+ public void testContains_inList() {
+ assertEquals(true, TERTIARY_LIST.contains(false));
+ }
+
+ public void testContains_inListWithDuplicates_matchAtHead() {
+ BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true, false);
+ assertEquals(true, listWithDupes.contains(true));
+ }
+
+ public void testContains_inListWithDuplicates_matchMidList() {
+ BooleanArrayList listWithDupes = newImmutableBooleanArrayList(false, true, true, false);
+ assertEquals(true, listWithDupes.contains(true));
+ }
+
public void testSize() {
assertEquals(0, BooleanArrayList.emptyList().size());
assertEquals(1, UNARY_LIST.size());
diff --git a/java/core/src/test/java/com/google/protobuf/CachedFieldSizeTest.java b/java/core/src/test/java/com/google/protobuf/CachedFieldSizeTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/CodedAdapterTest.java b/java/core/src/test/java/com/google/protobuf/CodedAdapterTest.java
old mode 100755
new mode 100644
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 3a8254a..019b5a1 100644
--- a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
@@ -139,6 +139,68 @@
}
}
+ public void testIndexOf_nullElement() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(null));
+ }
+
+ public void testIndexOf_incompatibleElementType() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(new Object()));
+ }
+
+ public void testIndexOf_notInList() {
+ assertEquals(-1, UNARY_LIST.indexOf(2D));
+ }
+
+ public void testIndexOf_notInListWithDuplicates() {
+ DoubleArrayList listWithDupes = newImmutableDoubleArrayList(1D, 1D);
+ assertEquals(-1, listWithDupes.indexOf(2D));
+ }
+
+ public void testIndexOf_inList() {
+ assertEquals(1, TERTIARY_LIST.indexOf(2D));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchAtHead() {
+ DoubleArrayList listWithDupes = newImmutableDoubleArrayList(1D, 1D, 2D);
+ assertEquals(0, listWithDupes.indexOf(1D));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchMidList() {
+ DoubleArrayList listWithDupes = newImmutableDoubleArrayList(2D, 1D, 1D, 2D);
+ assertEquals(1, listWithDupes.indexOf(1D));
+ }
+
+ public void testContains_nullElement() {
+ assertEquals(false, TERTIARY_LIST.contains(null));
+ }
+
+ public void testContains_incompatibleElementType() {
+ assertEquals(false, TERTIARY_LIST.contains(new Object()));
+ }
+
+ public void testContains_notInList() {
+ assertEquals(false, UNARY_LIST.contains(2D));
+ }
+
+ public void testContains_notInListWithDuplicates() {
+ DoubleArrayList listWithDupes = newImmutableDoubleArrayList(1D, 1D);
+ assertEquals(false, listWithDupes.contains(2D));
+ }
+
+ public void testContains_inList() {
+ assertEquals(true, TERTIARY_LIST.contains(2D));
+ }
+
+ public void testContains_inListWithDuplicates_matchAtHead() {
+ DoubleArrayList listWithDupes = newImmutableDoubleArrayList(1D, 1D, 2D);
+ assertEquals(true, listWithDupes.contains(1D));
+ }
+
+ public void testContains_inListWithDuplicates_matchMidList() {
+ DoubleArrayList listWithDupes = newImmutableDoubleArrayList(2D, 1D, 1D, 2D);
+ assertEquals(true, listWithDupes.contains(1D));
+ }
+
public void testSize() {
assertEquals(0, DoubleArrayList.emptyList().size());
assertEquals(1, UNARY_LIST.size());
diff --git a/java/core/src/test/java/com/google/protobuf/ExperimentalMessageFactory.java b/java/core/src/test/java/com/google/protobuf/ExperimentalMessageFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/ExperimentalSerializationUtil.java b/java/core/src/test/java/com/google/protobuf/ExperimentalSerializationUtil.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java b/java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
index 85a2fe0..a1c98c0 100644
--- a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
@@ -34,9 +34,11 @@
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
+import com.google.protobuf.Descriptors.OneofDescriptor;
import com.google.protobuf.FieldPresenceTestProto.TestAllTypes;
import com.google.protobuf.FieldPresenceTestProto.TestOptionalFieldsOnly;
import com.google.protobuf.FieldPresenceTestProto.TestRepeatedFieldsOnly;
+import com.google.protobuf.testing.proto.TestProto3Optional;
import protobuf_unittest.UnittestProto;
import junit.framework.TestCase;
@@ -100,10 +102,118 @@
UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofBytes");
}
+ public void testHasMethodForProto3Optional() throws Exception {
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalInt32());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalInt64());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalUint32());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalUint64());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalSint32());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalSint64());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalFixed32());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalFixed64());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalFloat());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalDouble());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalBool());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalString());
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOptionalBytes());
+
+ TestProto3Optional.Builder builder = TestProto3Optional.newBuilder().setOptionalInt32(0);
+ assertTrue(builder.hasOptionalInt32());
+ assertTrue(builder.build().hasOptionalInt32());
+
+ TestProto3Optional.Builder otherBuilder = TestProto3Optional.newBuilder().setOptionalInt32(1);
+ otherBuilder.mergeFrom(builder.build());
+ assertTrue(otherBuilder.hasOptionalInt32());
+ assertEquals(0, otherBuilder.getOptionalInt32());
+
+ TestProto3Optional.Builder builder3 =
+ TestProto3Optional.newBuilder().setOptionalNestedEnumValue(5);
+ assertTrue(builder3.hasOptionalNestedEnum());
+
+ TestProto3Optional.Builder builder4 =
+ TestProto3Optional.newBuilder().setOptionalNestedEnum(TestProto3Optional.NestedEnum.FOO);
+ assertTrue(builder4.hasOptionalNestedEnum());
+
+ TestProto3Optional proto = TestProto3Optional.parseFrom(builder.build().toByteArray());
+ assertTrue(proto.hasOptionalInt32());
+ assertTrue(proto.toBuilder().hasOptionalInt32());
+ }
+
+ private static void assertProto3OptionalReflection(String name) throws Exception {
+ FieldDescriptor fieldDescriptor = TestProto3Optional.getDescriptor().findFieldByName(name);
+ OneofDescriptor oneofDescriptor = fieldDescriptor.getContainingOneof();
+ assertNotNull(fieldDescriptor.getContainingOneof());
+ assertTrue(fieldDescriptor.hasOptionalKeyword());
+ assertTrue(fieldDescriptor.hasPresence());
+
+ assertFalse(TestProto3Optional.getDefaultInstance().hasOneof(oneofDescriptor));
+ assertNull(TestProto3Optional.getDefaultInstance().getOneofFieldDescriptor(oneofDescriptor));
+
+ TestProto3Optional.Builder builder = TestProto3Optional.newBuilder();
+ builder.setField(fieldDescriptor, fieldDescriptor.getDefaultValue());
+ assertTrue(builder.hasField(fieldDescriptor));
+ assertEquals(fieldDescriptor.getDefaultValue(), builder.getField(fieldDescriptor));
+ assertTrue(builder.build().hasField(fieldDescriptor));
+ assertEquals(fieldDescriptor.getDefaultValue(), builder.build().getField(fieldDescriptor));
+ assertTrue(builder.hasOneof(oneofDescriptor));
+ assertEquals(fieldDescriptor, builder.getOneofFieldDescriptor(oneofDescriptor));
+ assertTrue(builder.build().hasOneof(oneofDescriptor));
+ assertEquals(fieldDescriptor, builder.build().getOneofFieldDescriptor(oneofDescriptor));
+
+ TestProto3Optional.Builder otherBuilder = TestProto3Optional.newBuilder();
+ otherBuilder.mergeFrom(builder.build());
+ assertTrue(otherBuilder.hasField(fieldDescriptor));
+ assertEquals(fieldDescriptor.getDefaultValue(), otherBuilder.getField(fieldDescriptor));
+
+ TestProto3Optional proto = TestProto3Optional.parseFrom(builder.build().toByteArray());
+ assertTrue(proto.hasField(fieldDescriptor));
+ assertTrue(proto.toBuilder().hasField(fieldDescriptor));
+
+ DynamicMessage.Builder dynamicBuilder =
+ DynamicMessage.newBuilder(TestProto3Optional.getDescriptor());
+ dynamicBuilder.setField(fieldDescriptor, fieldDescriptor.getDefaultValue());
+ assertTrue(dynamicBuilder.hasField(fieldDescriptor));
+ assertEquals(fieldDescriptor.getDefaultValue(), dynamicBuilder.getField(fieldDescriptor));
+ assertTrue(dynamicBuilder.build().hasField(fieldDescriptor));
+ assertEquals(
+ fieldDescriptor.getDefaultValue(), dynamicBuilder.build().getField(fieldDescriptor));
+ assertTrue(dynamicBuilder.hasOneof(oneofDescriptor));
+ assertEquals(fieldDescriptor, dynamicBuilder.getOneofFieldDescriptor(oneofDescriptor));
+ assertTrue(dynamicBuilder.build().hasOneof(oneofDescriptor));
+ assertEquals(fieldDescriptor, dynamicBuilder.build().getOneofFieldDescriptor(oneofDescriptor));
+
+ DynamicMessage.Builder otherDynamicBuilder =
+ DynamicMessage.newBuilder(TestProto3Optional.getDescriptor());
+ otherDynamicBuilder.mergeFrom(dynamicBuilder.build());
+ assertTrue(otherDynamicBuilder.hasField(fieldDescriptor));
+ assertEquals(fieldDescriptor.getDefaultValue(), otherDynamicBuilder.getField(fieldDescriptor));
+
+ DynamicMessage dynamicProto =
+ DynamicMessage.parseFrom(TestProto3Optional.getDescriptor(), builder.build().toByteArray());
+ assertTrue(dynamicProto.hasField(fieldDescriptor));
+ assertTrue(dynamicProto.toBuilder().hasField(fieldDescriptor));
+ }
+
+ public void testProto3Optional_reflection() throws Exception {
+ assertProto3OptionalReflection("optional_int32");
+ assertProto3OptionalReflection("optional_int64");
+ assertProto3OptionalReflection("optional_uint32");
+ assertProto3OptionalReflection("optional_uint64");
+ assertProto3OptionalReflection("optional_sint32");
+ assertProto3OptionalReflection("optional_sint64");
+ assertProto3OptionalReflection("optional_fixed32");
+ assertProto3OptionalReflection("optional_fixed64");
+ assertProto3OptionalReflection("optional_float");
+ assertProto3OptionalReflection("optional_double");
+ assertProto3OptionalReflection("optional_bool");
+ assertProto3OptionalReflection("optional_string");
+ assertProto3OptionalReflection("optional_bytes");
+ }
+
public void testOneofEquals() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestAllTypes message1 = builder.build();
- // Set message2's oneof_uint32 field to defalut value. The two
+ // Set message2's oneof_uint32 field to default value. The two
// messages should be different when check with oneof case.
builder.setOneofUint32(0);
TestAllTypes message2 = builder.build();
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 77a2839..091ac5b 100644
--- a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
@@ -139,6 +139,68 @@
}
}
+ public void testIndexOf_nullElement() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(null));
+ }
+
+ public void testIndexOf_incompatibleElementType() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(new Object()));
+ }
+
+ public void testIndexOf_notInList() {
+ assertEquals(-1, UNARY_LIST.indexOf(2F));
+ }
+
+ public void testIndexOf_notInListWithDuplicates() {
+ FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F);
+ assertEquals(-1, listWithDupes.indexOf(2F));
+ }
+
+ public void testIndexOf_inList() {
+ assertEquals(1, TERTIARY_LIST.indexOf(2F));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchAtHead() {
+ FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F, 2F);
+ assertEquals(0, listWithDupes.indexOf(1F));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchMidList() {
+ FloatArrayList listWithDupes = newImmutableFloatArrayList(2F, 1F, 1F, 2F);
+ assertEquals(1, listWithDupes.indexOf(1F));
+ }
+
+ public void testContains_nullElement() {
+ assertEquals(false, TERTIARY_LIST.contains(null));
+ }
+
+ public void testContains_incompatibleElementType() {
+ assertEquals(false, TERTIARY_LIST.contains(new Object()));
+ }
+
+ public void testContains_notInList() {
+ assertEquals(false, UNARY_LIST.contains(2F));
+ }
+
+ public void testContains_notInListWithDuplicates() {
+ FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F);
+ assertEquals(false, listWithDupes.contains(2F));
+ }
+
+ public void testContains_inList() {
+ assertEquals(true, TERTIARY_LIST.contains(2F));
+ }
+
+ public void testContains_inListWithDuplicates_matchAtHead() {
+ FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F, 2F);
+ assertEquals(true, listWithDupes.contains(1F));
+ }
+
+ public void testContains_inListWithDuplicates_matchMidList() {
+ FloatArrayList listWithDupes = newImmutableFloatArrayList(2F, 1F, 1F, 2F);
+ assertEquals(true, listWithDupes.contains(1F));
+ }
+
public void testSize() {
assertEquals(0, FloatArrayList.emptyList().size());
assertEquals(1, UNARY_LIST.size());
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 51ebc98..2ad94f8 100644
--- a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
@@ -139,6 +139,68 @@
}
}
+ public void testIndexOf_nullElement() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(null));
+ }
+
+ public void testIndexOf_incompatibleElementType() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(new Object()));
+ }
+
+ public void testIndexOf_notInList() {
+ assertEquals(-1, UNARY_LIST.indexOf(2));
+ }
+
+ public void testIndexOf_notInListWithDuplicates() {
+ IntArrayList listWithDupes = newImmutableIntArrayList(1, 1);
+ assertEquals(-1, listWithDupes.indexOf(2));
+ }
+
+ public void testIndexOf_inList() {
+ assertEquals(1, TERTIARY_LIST.indexOf(2));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchAtHead() {
+ IntArrayList listWithDupes = newImmutableIntArrayList(1, 1, 2);
+ assertEquals(0, listWithDupes.indexOf(1));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchMidList() {
+ IntArrayList listWithDupes = newImmutableIntArrayList(2, 1, 1, 2);
+ assertEquals(1, listWithDupes.indexOf(1));
+ }
+
+ public void testContains_nullElement() {
+ assertEquals(false, TERTIARY_LIST.contains(null));
+ }
+
+ public void testContains_incompatibleElementType() {
+ assertEquals(false, TERTIARY_LIST.contains(new Object()));
+ }
+
+ public void testContains_notInList() {
+ assertEquals(false, UNARY_LIST.contains(2));
+ }
+
+ public void testContains_notInListWithDuplicates() {
+ IntArrayList listWithDupes = newImmutableIntArrayList(1, 1);
+ assertEquals(false, listWithDupes.contains(2));
+ }
+
+ public void testContains_inList() {
+ assertEquals(true, TERTIARY_LIST.contains(2));
+ }
+
+ public void testContains_inListWithDuplicates_matchAtHead() {
+ IntArrayList listWithDupes = newImmutableIntArrayList(1, 1, 2);
+ assertEquals(true, listWithDupes.contains(1));
+ }
+
+ public void testContains_inListWithDuplicates_matchMidList() {
+ IntArrayList listWithDupes = newImmutableIntArrayList(2, 1, 1, 2);
+ assertEquals(true, listWithDupes.contains(1));
+ }
+
public void testSize() {
assertEquals(0, IntArrayList.emptyList().size());
assertEquals(1, UNARY_LIST.size());
diff --git a/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java b/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java
index 4764ca1..1270ef0 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteEqualsAndHashTest.java
@@ -75,7 +75,7 @@
assertEquals(foo1a, foo1b);
assertEquals(foo1a.hashCode(), foo1b.hashCode());
- // Check that a diffeent object is not equal.
+ // Check that a different object is not equal.
assertFalse(foo1a.equals(foo2));
// Check that two objects which have different types but the same field values are not
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 cab14c3..9f64b6b 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
@@ -94,7 +94,7 @@
stillEqual = (iter.hasNext() && referenceBytes[i] == iter.nextByte());
}
assertTrue(classUnderTest + " must capture the right bytes", stillEqual);
- assertFalse(classUnderTest + " must have exhausted the itertor", iter.hasNext());
+ assertFalse(classUnderTest + " must have exhausted the iterator", iter.hasNext());
try {
iter.nextByte();
@@ -536,7 +536,7 @@
assertThat(input.read(new byte[1], /* off= */ 0, /*len=*/ 0)).isEqualTo(-1);
input.reset();
- assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available());
+ assertEquals("InputStream.reset() succeeded", stringSize - skipped1, input.available());
assertEquals(
"InputStream.reset(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
}
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 1935100..d6fbaf9 100644
--- a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
@@ -139,6 +139,68 @@
}
}
+ public void testIndexOf_nullElement() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(null));
+ }
+
+ public void testIndexOf_incompatibleElementType() {
+ assertEquals(-1, TERTIARY_LIST.indexOf(new Object()));
+ }
+
+ public void testIndexOf_notInList() {
+ assertEquals(-1, UNARY_LIST.indexOf(2L));
+ }
+
+ public void testIndexOf_notInListWithDuplicates() {
+ LongArrayList listWithDupes = newImmutableLongArrayList(1L, 1L);
+ assertEquals(-1, listWithDupes.indexOf(2L));
+ }
+
+ public void testIndexOf_inList() {
+ assertEquals(1, TERTIARY_LIST.indexOf(2L));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchAtHead() {
+ LongArrayList listWithDupes = newImmutableLongArrayList(1L, 1L, 2L);
+ assertEquals(0, listWithDupes.indexOf(1L));
+ }
+
+ public void testIndexOf_inListWithDuplicates_matchMidList() {
+ LongArrayList listWithDupes = newImmutableLongArrayList(2L, 1L, 1L, 2L);
+ assertEquals(1, listWithDupes.indexOf(1L));
+ }
+
+ public void testContains_nullElement() {
+ assertEquals(false, TERTIARY_LIST.contains(null));
+ }
+
+ public void testContains_incompatibleElementType() {
+ assertEquals(false, TERTIARY_LIST.contains(new Object()));
+ }
+
+ public void testContains_notInList() {
+ assertEquals(false, UNARY_LIST.contains(2L));
+ }
+
+ public void testContains_notInListWithDuplicates() {
+ LongArrayList listWithDupes = newImmutableLongArrayList(1L, 1L);
+ assertEquals(false, listWithDupes.contains(2L));
+ }
+
+ public void testContains_inList() {
+ assertEquals(true, TERTIARY_LIST.contains(2L));
+ }
+
+ public void testContains_inListWithDuplicates_matchAtHead() {
+ LongArrayList listWithDupes = newImmutableLongArrayList(1L, 1L, 2L);
+ assertEquals(true, listWithDupes.contains(1L));
+ }
+
+ public void testContains_inListWithDuplicates_matchMidList() {
+ LongArrayList listWithDupes = newImmutableLongArrayList(2L, 1L, 1L, 2L);
+ assertEquals(true, listWithDupes.contains(1L));
+ }
+
public void testSize() {
assertEquals(0, LongArrayList.emptyList().size());
assertEquals(1, UNARY_LIST.size());
diff --git a/java/core/src/test/java/com/google/protobuf/MapLiteTest.java b/java/core/src/test/java/com/google/protobuf/MapLiteTest.java
old mode 100755
new mode 100644
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 304261c..489bb7c 100644
--- a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
@@ -84,7 +84,7 @@
stillEqual = (iter.hasNext() && BYTES[i] == iter.nextByte());
}
assertTrue(CLASSNAME + " must capture the right bytes", stillEqual);
- assertFalse(CLASSNAME + " must have exhausted the itertor", iter.hasNext());
+ assertFalse(CLASSNAME + " must have exhausted the iterator", iter.hasNext());
try {
iter.nextByte();
@@ -590,7 +590,7 @@
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
- assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available());
+ assertEquals("InputStream.reset() succeeded", stringSize - skipped1, input.available());
assertEquals(
"InputStream.reset(), read()", testString.byteAt(nearEndIndex) & 0xFF, input.read());
}
diff --git a/java/core/src/test/java/com/google/protobuf/PackedFieldTest.java b/java/core/src/test/java/com/google/protobuf/PackedFieldTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java b/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java b/java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto2LiteSchemaTest.java b/java/core/src/test/java/com/google/protobuf/Proto2LiteSchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto2MessageFactory.java b/java/core/src/test/java/com/google/protobuf/Proto2MessageFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto2MessageInfoFactory.java b/java/core/src/test/java/com/google/protobuf/Proto2MessageInfoFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto2MessageLiteFactory.java b/java/core/src/test/java/com/google/protobuf/Proto2MessageLiteFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto2SchemaTest.java b/java/core/src/test/java/com/google/protobuf/Proto2SchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto2UnknownEnumValueTest.java b/java/core/src/test/java/com/google/protobuf/Proto2UnknownEnumValueTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto3LiteSchemaTest.java b/java/core/src/test/java/com/google/protobuf/Proto3LiteSchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto3MessageFactory.java b/java/core/src/test/java/com/google/protobuf/Proto3MessageFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto3MessageInfoFactory.java b/java/core/src/test/java/com/google/protobuf/Proto3MessageInfoFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto3MessageLiteFactory.java b/java/core/src/test/java/com/google/protobuf/Proto3MessageLiteFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto3MessageLiteInfoFactory.java b/java/core/src/test/java/com/google/protobuf/Proto3MessageLiteInfoFactory.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java b/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/TestSchemas.java b/java/core/src/test/java/com/google/protobuf/TestSchemas.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/TestSchemasLite.java b/java/core/src/test/java/com/google/protobuf/TestSchemasLite.java
old mode 100755
new mode 100644
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 dd0e8c8..6ca3ae11 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
@@ -40,6 +40,8 @@
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.TextFormat.Parser.SingularOverwritePolicy;
+import com.google.protobuf.testing.proto.TestProto3Optional;
+import com.google.protobuf.testing.proto.TestProto3Optional.NestedEnum;
import any_test.AnyTestProto.TestAny;
import map_test.MapTestProto.TestMap;
import protobuf_unittest.UnittestMset.TestMessageSetExtension1;
@@ -319,6 +321,24 @@
assertEquals(canonicalExoticText, message.toString());
}
+ public void testRoundtripProto3Optional() throws Exception {
+ Message message =
+ TestProto3Optional.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalInt64(2)
+ .setOptionalNestedEnum(NestedEnum.BAZ)
+ .build();
+ TestProto3Optional.Builder message2 = TestProto3Optional.newBuilder();
+ TextFormat.merge(message.toString(), message2);
+
+ assertTrue(message2.hasOptionalInt32());
+ assertTrue(message2.hasOptionalInt64());
+ assertTrue(message2.hasOptionalNestedEnum());
+ assertEquals(1, message2.getOptionalInt32());
+ assertEquals(2, message2.getOptionalInt64());
+ assertEquals(NestedEnum.BAZ, message2.getOptionalNestedEnum());
+ }
+
public void testPrintMessageSet() throws Exception {
TestMessageSet messageSet =
TestMessageSet.newBuilder()
@@ -1536,4 +1556,42 @@
index, line, column));
}
}
+
+ public void testSortMapFields() throws Exception {
+ TestMap message =
+ TestMap.newBuilder()
+ .putStringToInt32Field("cherry", 30)
+ .putStringToInt32Field("banana", 20)
+ .putStringToInt32Field("apple", 10)
+ .putInt32ToStringField(30, "cherry")
+ .putInt32ToStringField(20, "banana")
+ .putInt32ToStringField(10, "apple")
+ .build();
+ String text =
+ "int32_to_string_field {\n"
+ + " key: 10\n"
+ + " value: \"apple\"\n"
+ + "}\n"
+ + "int32_to_string_field {\n"
+ + " key: 20\n"
+ + " value: \"banana\"\n"
+ + "}\n"
+ + "int32_to_string_field {\n"
+ + " key: 30\n"
+ + " value: \"cherry\"\n"
+ + "}\n"
+ + "string_to_int32_field {\n"
+ + " key: \"apple\"\n"
+ + " value: 10\n"
+ + "}\n"
+ + "string_to_int32_field {\n"
+ + " key: \"banana\"\n"
+ + " value: 20\n"
+ + "}\n"
+ + "string_to_int32_field {\n"
+ + " key: \"cherry\"\n"
+ + " value: 30\n"
+ + "}\n";
+ assertEquals(text, TextFormat.printer().printToString(message));
+ }
}
diff --git a/java/core/src/test/java/com/google/protobuf/TypeRegistryTest.java b/java/core/src/test/java/com/google/protobuf/TypeRegistryTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Utf8Test.java b/java/core/src/test/java/com/google/protobuf/Utf8Test.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/Utf8Utils.java b/java/core/src/test/java/com/google/protobuf/Utf8Utils.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/WireFormatLiteTest.java b/java/core/src/test/java/com/google/protobuf/WireFormatLiteTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/WrappersLiteOfMethodTest.java b/java/core/src/test/java/com/google/protobuf/WrappersLiteOfMethodTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/java/com/google/protobuf/WrappersOfMethodTest.java b/java/core/src/test/java/com/google/protobuf/WrappersOfMethodTest.java
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/cached_field_size_test.proto b/java/core/src/test/proto/com/google/protobuf/cached_field_size_test.proto
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/map_initialization_order_test.proto b/java/core/src/test/proto/com/google/protobuf/map_initialization_order_test.proto
index 6ebef5e..ab99e5f 100644
--- a/java/core/src/test/proto/com/google/protobuf/map_initialization_order_test.proto
+++ b/java/core/src/test/proto/com/google/protobuf/map_initialization_order_test.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.
-// Regression test for a map initilaization order bug. The bug only manifests
+// Regression test for a map initialization order bug. The bug only manifests
// when:
// 1. A message contains map fields and is also extendable.
// 2. There is a file-level extension defined in the same file referencing
diff --git a/java/core/src/test/proto/com/google/protobuf/message_lite_extension_util_test.proto b/java/core/src/test/proto/com/google/protobuf/message_lite_extension_util_test.proto
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/packed_field_test.proto b/java/core/src/test/proto/com/google/protobuf/packed_field_test.proto
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/proto2_message.proto b/java/core/src/test/proto/com/google/protobuf/proto2_message.proto
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/proto2_message_lite.proto b/java/core/src/test/proto/com/google/protobuf/proto2_message_lite.proto
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/proto3_message.proto b/java/core/src/test/proto/com/google/protobuf/proto3_message.proto
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto b/java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto
old mode 100755
new mode 100644
diff --git a/java/core/src/test/proto/com/google/protobuf/wrappers_test.proto b/java/core/src/test/proto/com/google/protobuf/wrappers_test.proto
old mode 100755
new mode 100644
diff --git a/java/lite/BUILD b/java/lite/BUILD
new file mode 100644
index 0000000..22840ec
--- /dev/null
+++ b/java/lite/BUILD
@@ -0,0 +1,14 @@
+load("@rules_proto//proto:defs.bzl", "proto_lang_toolchain")
+
+alias(
+ name = "lite",
+ actual = "//java/core:lite",
+ visibility = ["//visibility:public"],
+)
+
+proto_lang_toolchain(
+ name = "toolchain",
+ command_line = "--java_out=lite:$(OUT)",
+ runtime = ":lite",
+ visibility = ["//visibility:public"],
+)
diff --git a/java/lite/generate-test-sources-build.xml b/java/lite/generate-test-sources-build.xml
index 1c1a18c..62bca93 100644
--- a/java/lite/generate-test-sources-build.xml
+++ b/java/lite/generate-test-sources-build.xml
@@ -15,6 +15,7 @@
<arg value="${protobuf.source.dir}/google/protobuf/unittest_no_generic_services.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_optimize_for.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_proto3.proto"/>
+ <arg value="${protobuf.source.dir}/google/protobuf/unittest_proto3_optional.proto"/>
<arg value="${protobuf.source.dir}/google/protobuf/unittest_well_known_types.proto"/>
<arg value="${protobuf.basedir}/java/core/${test.proto.dir}/com/google/protobuf/any_test.proto"/>
<arg value="${protobuf.basedir}/java/core/${test.proto.dir}/com/google/protobuf/cached_field_size_test.proto"/>
diff --git a/java/lite/pom.xml b/java/lite/pom.xml
index fc91b2c..6ce28ee 100644
--- a/java/lite/pom.xml
+++ b/java/lite/pom.xml
@@ -4,7 +4,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.11.0-rc-1</version>
+ <version>3.12.0-rc-2</version>
</parent>
<artifactId>protobuf-javalite</artifactId>
@@ -89,7 +89,7 @@
<resource>
<directory>${basedir}/../core/src/main/java/com/google/protobuf</directory>
<includes>
- <!-- Keep in sync with //:BUILD -->
+ <!-- Keep in sync with //java/core:BUILD -->
<include>AbstractMessageLite.java</include>
<include>AbstractParser.java</include>
<include>AbstractProtobufList.java</include>
diff --git a/java/lite/proguard.pgcfg b/java/lite/proguard.pgcfg
old mode 100755
new mode 100644
diff --git a/java/lite/src/test/java/com/google/protobuf/LiteTest.java b/java/lite/src/test/java/com/google/protobuf/LiteTest.java
old mode 100755
new mode 100644
index e37e2ca..3e39bc7
--- a/java/lite/src/test/java/com/google/protobuf/LiteTest.java
+++ b/java/lite/src/test/java/com/google/protobuf/LiteTest.java
@@ -1997,7 +1997,7 @@
assertEquals(foo1a, foo1b);
assertEquals(foo1a.hashCode(), foo1b.hashCode());
- // Check that a diffeent object is not equal.
+ // Check that a different object is not equal.
assertFalse(foo1a.equals(foo2));
// Check that two objects which have different types but the same field values are not
diff --git a/java/lite/src/test/java/com/google/protobuf/Proto2MessageLiteInfoFactory.java b/java/lite/src/test/java/com/google/protobuf/Proto2MessageLiteInfoFactory.java
old mode 100755
new mode 100644
index 4a1d89b..57e933f
--- a/java/lite/src/test/java/com/google/protobuf/Proto2MessageLiteInfoFactory.java
+++ b/java/lite/src/test/java/com/google/protobuf/Proto2MessageLiteInfoFactory.java
@@ -177,16 +177,20 @@
// To update this after a proto change, run protoc on proto2_message_lite.proto and copy over
// the content of the generated buildMessageInfo() method here.
java.lang.String info =
- "\u0001U\u0001\u0002\u0001XU\u0000 \u0015\u0001\u0000\u0000\u0002\u0001\u0001\u0003"
- + "\u0002\u0002\u0004\u0003\u0003\u0005\u0004\u0004\u0006\u0005\u0005\u0007\u0006\u0006"
- + "\b\u0007\u0007\t\b\b\n\u0409\t\u000b\n\n\f\u000b\u000b\r\f\f\u000e\r\r\u000f\u000e"
- + "\u000e\u0010\u000f\u000f\u0011\u0010\u0010\u0012\u0012\u0013\u0013\u0014\u0014\u0015"
- + "\u0015\u0016\u0016\u0017\u0017\u0018\u0018\u0019\u0019\u001a\u001a\u001b\u041b\u001c"
- + "\u001c\u001d\u001d\u001e\u001e\u001f\u001f !!\"\"##$$%%&&\'\'(())**++,,--..//00"
- + "1\u0011\u00113153\u000064\u000075\u000086\u000097\u0000:8\u0000;9\u0000<:\u0000="
- + ";\u0000>\u043c\u0000?=\u0000@>\u0000A@\u0000BA\u0000CB\u0000DC\u0000ED\u0000G\u0500"
- + "#H\u0501$I\u0502%J\u0503&K\u0504\'L\u0505(M\u0506)N\u0507*O\u0508+P\u0509,Q\u050a"
- + "-R\u050b.S\u050c/T\u050d0U\u050e1V\u050f2W\u05103X\u05114";
+ "\u0001U\u0001\u0002\u0001XU\u0000 \u0015\u0001\u1000\u0000\u0002\u1001\u0001\u0003"
+ + "\u1002\u0002\u0004\u1003\u0003\u0005\u1004\u0004\u0006\u1005\u0005\u0007\u1006\u0006\b\u1007\u0007"
+ + "\t\u1008\b\n"
+ + "\u1409\t\u000b\u100a\n"
+ + "\f\u100b\u000b\r"
+ + "\u100c\f\u000e\u100d\r"
+ + "\u000f\u100e\u000e\u0010\u100f\u000f\u0011\u1010\u0010\u0012\u0012\u0013\u0013"
+ + "\u0014\u0014\u0015\u0015\u0016\u0016\u0017\u0017\u0018\u0018\u0019\u0019\u001a\u001a\u001b\u041b\u001c\u001c\u001d\u001d\u001e\u001e\u001f\u001f"
+ + " !!\"\"##$$%%&&\'\'"
+ + "(())**++,,--..//001\u1011\u0011315\u1033\u00006\u1034\u00007\u1035\u00008\u1036\u0000"
+ + "9\u1037\u0000:\u1038\u0000;\u1039\u0000<\u103a\u0000=\u103b\u0000>\u143c\u0000?\u103d"
+ + "\u0000@\u103e\u0000A\u1040\u0000B\u1041\u0000C\u1042\u0000D\u1043\u0000E\u1044\u0000"
+ + "G\u1500#H\u1501$I\u1502%J\u1503&K\u1504\'L\u1505(M\u1506)N\u1507*O\u1508+P\u1509"
+ + ",Q\u150a-R\u150b.S\u150c/T\u150d0U\u150e1V\u150f2W\u15103X\u15114";
return new RawMessageInfo(Proto2MessageLite.getDefaultInstance(), info, objects);
}
diff --git a/java/pom.xml b/java/pom.xml
index 0444385..eb15314 100644
--- a/java/pom.xml
+++ b/java/pom.xml
@@ -4,7 +4,7 @@
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.11.0-rc-1</version>
+ <version>3.12.0-rc-2</version>
<packaging>pom</packaging>
<name>Protocol Buffers [Parent]</name>
@@ -75,7 +75,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.12</version>
+ <version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -93,18 +93,18 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <version>28.1-android</version>
+ <version>29.0-android</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
- <version>28.1-android</version>
+ <version>29.0-android</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
- <version>1.0</version>
+ <version>1.0.1</version>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/java/util/BUILD b/java/util/BUILD
new file mode 100644
index 0000000..cfdb28e
--- /dev/null
+++ b/java/util/BUILD
@@ -0,0 +1,20 @@
+load("@rules_java//java:defs.bzl", "java_library")
+
+java_library(
+ name = "util",
+ srcs = glob([
+ "src/main/java/com/google/protobuf/util/*.java",
+ ]),
+ javacopts = [
+ "-source 7",
+ "-target 7",
+ ],
+ visibility = ["//visibility:public"],
+ deps = [
+ "//external:error_prone_annotations",
+ "//external:gson",
+ "//external:guava",
+ "//java/core",
+ "//java/lite",
+ ],
+)
diff --git a/java/util/pom.xml b/java/util/pom.xml
index 082c7dd..b7d9676 100644
--- a/java/util/pom.xml
+++ b/java/util/pom.xml
@@ -4,7 +4,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.11.0-rc-1</version>
+ <version>3.12.0-rc-2</version>
</parent>
<artifactId>protobuf-java-util</artifactId>
@@ -25,7 +25,7 @@
<dependency>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_annotations</artifactId>
- <version>2.3.3</version>
+ <version>2.3.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
diff --git a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java
index 9245822..312d30f 100644
--- a/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java
+++ b/java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java
@@ -34,6 +34,7 @@
import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -49,7 +50,7 @@
/**
* Utility helper functions to work with {@link com.google.protobuf.FieldMask}.
*/
-public class FieldMaskUtil {
+public final class FieldMaskUtil {
private static final String FIELD_PATH_SEPARATOR = ",";
private static final String FIELD_PATH_SEPARATOR_REGEX = ",";
private static final String FIELD_SEPARATOR_REGEX = "\\.";
@@ -83,7 +84,7 @@
*/
public static FieldMask fromString(String value) {
// TODO(xiaofeng): Consider using com.google.common.base.Splitter here instead.
- return fromStringList(null, Arrays.asList(value.split(FIELD_PATH_SEPARATOR_REGEX)));
+ return fromStringList(Arrays.asList(value.split(FIELD_PATH_SEPARATOR_REGEX)));
}
/**
@@ -103,14 +104,36 @@
*/
// TODO(xiaofeng): Consider renaming fromStrings()
public static FieldMask fromStringList(Class<? extends Message> type, Iterable<String> paths) {
+ return fromStringList(Internal.getDefaultInstance(type).getDescriptorForType(), paths);
+ }
+
+ /**
+ * Constructs a FieldMask for a list of field paths in a certain type.
+ *
+ * @throws IllegalArgumentException if any of the field path is not valid.
+ */
+ public static FieldMask fromStringList(Descriptor descriptor, Iterable<String> paths) {
+ return fromStringList(Optional.of(descriptor), paths);
+ }
+
+ /**
+ * Constructs a FieldMask for a list of field paths in a certain type. Does not validate the given
+ * paths.
+ */
+ public static FieldMask fromStringList(Iterable<String> paths) {
+ return fromStringList(Optional.<Descriptor>absent(), paths);
+ }
+
+ private static FieldMask fromStringList(Optional<Descriptor> descriptor, Iterable<String> paths) {
FieldMask.Builder builder = FieldMask.newBuilder();
for (String path : paths) {
if (path.isEmpty()) {
// Ignore empty field paths.
continue;
}
- if (type != null && !isValid(type, path)) {
- throw new IllegalArgumentException(path + " is not a valid path for " + type);
+ if (descriptor.isPresent() && !isValid(descriptor.get(), path)) {
+ throw new IllegalArgumentException(
+ path + " is not a valid path for " + descriptor.get().getFullName());
}
builder.addPaths(path);
}
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 d9bcf89..6798143 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
@@ -233,7 +233,7 @@
registry,
oldRegistry,
alwaysOutputDefaultValueFields,
- Collections.<FieldDescriptor>emptySet(),
+ includingDefaultValueFields,
preservingProtoFieldNames,
omittingInsignificantWhitespace,
true,
diff --git a/java/util/src/main/java/com/google/protobuf/util/Structs.java b/java/util/src/main/java/com/google/protobuf/util/Structs.java
old mode 100755
new mode 100644
diff --git a/java/util/src/main/java/com/google/protobuf/util/Values.java b/java/util/src/main/java/com/google/protobuf/util/Values.java
old mode 100755
new mode 100644
index b3ade2d..f03d70e
--- a/java/util/src/main/java/com/google/protobuf/util/Values.java
+++ b/java/util/src/main/java/com/google/protobuf/util/Values.java
@@ -71,8 +71,8 @@
}
/**
- * Returns a Value with ListValue set to the appending the result of calling {@link #of(Object)}
- * on each element in the iterable.
+ * Returns a Value with ListValue set to the appending the result of calling {@link #of} on each
+ * element in the iterable.
*/
public static Value of(Iterable<Value> values) {
Value.Builder valueBuilder = Value.newBuilder();
diff --git a/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java b/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java
index 1a99857..78b470e 100644
--- a/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java
+++ b/java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java
@@ -30,10 +30,12 @@
package com.google.protobuf.util;
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.ImmutableList;
import com.google.protobuf.FieldMask;
import protobuf_unittest.UnittestProto.NestedTestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
import junit.framework.TestCase;
/** Unit tests for {@link FieldMaskUtil}. */
@@ -172,6 +174,38 @@
assertEquals("bar_baz", mask.getPaths(1));
}
+ public void testFromStringList() throws Exception {
+ FieldMask mask =
+ FieldMaskUtil.fromStringList(
+ NestedTestAllTypes.class, ImmutableList.of("payload.repeated_nested_message", "child"));
+ assertThat(mask)
+ .isEqualTo(
+ FieldMask.newBuilder()
+ .addPaths("payload.repeated_nested_message")
+ .addPaths("child")
+ .build());
+
+ mask =
+ FieldMaskUtil.fromStringList(
+ NestedTestAllTypes.getDescriptor(),
+ ImmutableList.of("payload.repeated_nested_message", "child"));
+ assertThat(mask)
+ .isEqualTo(
+ FieldMask.newBuilder()
+ .addPaths("payload.repeated_nested_message")
+ .addPaths("child")
+ .build());
+
+ mask =
+ FieldMaskUtil.fromStringList(ImmutableList.of("payload.repeated_nested_message", "child"));
+ assertThat(mask)
+ .isEqualTo(
+ FieldMask.newBuilder()
+ .addPaths("payload.repeated_nested_message")
+ .addPaths("child")
+ .build());
+ }
+
public void testUnion() throws Exception {
// Only test a simple case here and expect
// {@link FieldMaskTreeTest#testAddFieldPath} to cover all scenarios.
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 a064831..f9358e5 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
@@ -30,6 +30,7 @@
package com.google.protobuf.util;
+import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
@@ -1784,4 +1785,16 @@
TestMap emptyMap = TestMap.getDefaultInstance();
assertEquals("{\n}", toSortedJsonString(emptyMap));
}
+
+ public void testPrintingEnumsAsIntsChainedAfterIncludingDefaultValueFields() throws Exception {
+ TestAllTypes message = TestAllTypes.newBuilder().setOptionalBool(false).build();
+
+ assertEquals(
+ "{\n" + " \"optionalBool\": false\n" + "}",
+ JsonFormat.printer()
+ .includingDefaultValueFields(
+ ImmutableSet.of(message.getDescriptorForType().findFieldByName("optional_bool")))
+ .printingEnumsAsInts()
+ .print(message));
+ }
}
diff --git a/java/util/src/test/java/com/google/protobuf/util/StructsTest.java b/java/util/src/test/java/com/google/protobuf/util/StructsTest.java
old mode 100755
new mode 100644
diff --git a/java/util/src/test/java/com/google/protobuf/util/ValuesTest.java b/java/util/src/test/java/com/google/protobuf/util/ValuesTest.java
old mode 100755
new mode 100644
diff --git a/js/binary/decoder.js b/js/binary/decoder.js
index 75d4ff7..257c283 100644
--- a/js/binary/decoder.js
+++ b/js/binary/decoder.js
@@ -748,7 +748,7 @@
/**
* Reads a raw signed 64-bit integer from the binary stream. Note that since
* Javascript represents all numbers as double-precision floats, there will be
- * precision lost if the absolute vlaue of the integer is larger than 2^53.
+ * precision lost if the absolute value of the integer is larger than 2^53.
*
* @return {number} The signed 64-bit integer read from the binary stream.
* Precision will be lost if the integer exceeds 2^53.
diff --git a/js/binary/decoder_test.js b/js/binary/decoder_test.js
index 9abf7d5..9900e65 100644
--- a/js/binary/decoder_test.js
+++ b/js/binary/decoder_test.js
@@ -303,7 +303,7 @@
});
it('does zigzag encoding properly', function() {
- // Test cases direcly from the protobuf dev guide.
+ // Test cases directly from the protobuf dev guide.
// https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
var testCases = [
{original: '0', zigzag: '0'},
diff --git a/js/binary/utils.js b/js/binary/utils.js
index 195247e..0d55a4a 100644
--- a/js/binary/utils.js
+++ b/js/binary/utils.js
@@ -117,7 +117,7 @@
/**
- * Convers a signed Javascript integer into zigzag format, splits it into two
+ * Converts a signed Javascript integer into zigzag format, splits it into two
* 32-bit halves, and stores it in the temp values above.
* @param {number} value The number to split.
*/
diff --git a/js/binary/utils_test.js b/js/binary/utils_test.js
index e953ace..9f735d3 100644
--- a/js/binary/utils_test.js
+++ b/js/binary/utils_test.js
@@ -506,7 +506,7 @@
function makeHiLoPair(lo, hi) {
return {lo: lo >>> 0, hi: hi >>> 0};
}
- // Test cases direcly from the protobuf dev guide.
+ // Test cases directly from the protobuf dev guide.
// https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
var testCases = [
{original: stringToHiLoPair('0'), zigzag: stringToHiLoPair('0')},
diff --git a/js/binary/writer_test.js b/js/binary/writer_test.js
index 4dafa09..fca1ba4 100644
--- a/js/binary/writer_test.js
+++ b/js/binary/writer_test.js
@@ -210,7 +210,7 @@
});
it('writes zigzag 64 fields', function() {
- // Test cases direcly from the protobuf dev guide.
+ // Test cases directly from the protobuf dev guide.
// https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
var testCases = [
{original: '0', zigzag: '0'},
diff --git a/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto2.js b/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto2.js
new file mode 100644
index 0000000..252520f
--- /dev/null
+++ b/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto2.js
@@ -0,0 +1,314 @@
+/**
+ * @fileoverview The code size benchmark of apps JSPB for proto2 all types
+ */
+goog.module('protobuf.benchmark.code_size.apps_jspb.AllTypesProto2');
+
+// const ForeignEnum = goog.require('proto.proto2_unittest.ForeignEnum');
+const ForeignMessage = goog.require('proto.proto2_unittest.ForeignMessage');
+const TestAllTypes = goog.require('proto.proto2_unittest.TestAllTypes');
+const TestPackedTypes = goog.require('proto.proto2_unittest.TestPackedTypes');
+const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
+
+ensureCommonBaseLine();
+
+/**
+ * The testing scenario is the same as kernel one.
+ * We have
+ * 1) add element to repeated fields
+ * 2) add element list to repeated fields
+ * 3) set fields
+ * 4) set repeated fields element
+ * 5) get fields
+ * 6) get repeated fields element
+ * 7) get repeated fields length
+ * @return {string}
+ */
+function accessAllTypes() {
+ const msgAllTypes = TestAllTypes.deserialize('');
+ const msgPackedTypes = TestPackedTypes.deserialize('');
+
+ msgPackedTypes.addPackedBool(true);
+ [true].forEach((e) => msgPackedTypes.addPackedBool(e));
+ msgAllTypes.addRepeatedBool(true, 1);
+ [true].forEach((e) => msgAllTypes.addRepeatedBool(e));
+ msgAllTypes.addRepeatedBytes('1', 1);
+ ['1'].forEach((e) => msgAllTypes.addRepeatedBytes(e));
+ msgPackedTypes.addPackedDouble(1.0);
+ [1.0].forEach((e) => msgPackedTypes.addPackedDouble(e));
+ msgAllTypes.addRepeatedDouble(1.0, 1);
+ [1.0].forEach((e) => msgAllTypes.addRepeatedDouble(e));
+ msgPackedTypes.addPackedFixed32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedFixed32(e));
+ msgAllTypes.addRepeatedFixed32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedFixed32(e));
+ msgPackedTypes.addPackedFixed64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedFixed64(e));
+ msgAllTypes.addRepeatedFixed64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedFixed64(e));
+ msgPackedTypes.addPackedFloat(1.0, 1);
+ [1.0].forEach((e) => msgPackedTypes.addPackedFloat(e));
+ msgAllTypes.addRepeatedFloat(1.0, 1);
+ [1.0].forEach((e) => msgAllTypes.addRepeatedFloat(e));
+ msgPackedTypes.addPackedInt32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedInt32(e));
+ msgAllTypes.addRepeatedInt32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedInt32(e));
+ msgPackedTypes.addPackedInt64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedInt64(e));
+ msgAllTypes.addRepeatedInt64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedInt64(e));
+ // msgPackedTypes.addPackedEnum(ForeignEnum.FOREIGN_BAR);
+ // [ForeignEnum.FOREIGN_BAR].forEach((e) => msgPackedTypes.addPackedEnum(e));
+ // msgAllTypes.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR);
+ // [ForeignEnum.FOREIGN_BAR].forEach(
+ // (e) => msgAllTypes.addRepeatedForeignEnum(e));
+ msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
+ [ForeignMessage.deserialize('')].forEach(
+ (e) => msgAllTypes.addRepeatedForeignMessage(e));
+ msgPackedTypes.addPackedSfixed32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSfixed32(e));
+ msgAllTypes.addRepeatedSfixed32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSfixed32(e));
+ msgPackedTypes.addPackedSfixed64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSfixed64(e));
+ msgAllTypes.addRepeatedSfixed64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSfixed64(e));
+ msgPackedTypes.addPackedSint32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSint32(e));
+ msgAllTypes.addRepeatedSint32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSint32(e));
+ msgPackedTypes.addPackedSint64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSint64(e));
+ msgAllTypes.addRepeatedSint64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSint64(e));
+ msgAllTypes.addRepeatedString('', 1);
+ [''].forEach((e) => msgAllTypes.addRepeatedString(e));
+ msgPackedTypes.addPackedUint32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedUint32(e));
+ msgAllTypes.addRepeatedUint32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedUint32(e));
+ msgPackedTypes.addPackedUint64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedUint64(e));
+ msgAllTypes.addRepeatedUint64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedUint64(e));
+
+ msgAllTypes.setOptionalBool(true);
+ msgAllTypes.setOptionalBytes('');
+ msgAllTypes.setOptionalDouble(1.0);
+ msgAllTypes.setOptionalFixed32(1);
+ msgAllTypes.setOptionalFixed64(1);
+ msgAllTypes.setOptionalFloat(1.0);
+ msgAllTypes.setOptionalInt32(1);
+ msgAllTypes.setOptionalInt64(1);
+ // msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
+ msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
+ msgAllTypes.setOptionalSfixed32(1);
+ msgAllTypes.setOptionalSfixed64(1);
+ msgAllTypes.setOptionalSint32(1);
+ msgAllTypes.setOptionalSint64(1);
+ msgAllTypes.setOptionalString('');
+ msgAllTypes.setOptionalUint32(1);
+ msgAllTypes.setOptionalUint64(1);
+ msgPackedTypes.setPackedBoolList([true]);
+ let arrayVal;
+ arrayVal = msgPackedTypes.getPackedBoolList();
+ arrayVal[0] = true;
+ msgPackedTypes.setPackedBoolList(arrayVal);
+ msgAllTypes.setRepeatedBoolList([true]);
+ arrayVal = msgAllTypes.getRepeatedBoolList();
+ arrayVal[0] = true;
+ msgAllTypes.setRepeatedBoolList(arrayVal);
+ msgAllTypes.setRepeatedBytesList(['']);
+ arrayVal = msgAllTypes.getRepeatedBytesList();
+ arrayVal[0] = '';
+ msgAllTypes.setRepeatedBytesList(arrayVal);
+ msgPackedTypes.setPackedDoubleList([1.0]);
+ arrayVal = msgPackedTypes.getPackedDoubleList();
+ arrayVal[0] = 1.0;
+ msgPackedTypes.setPackedDoubleList(arrayVal);
+ msgAllTypes.setRepeatedDoubleList([1.0]);
+ arrayVal = msgAllTypes.getRepeatedDoubleList();
+ arrayVal[0] = 1.0;
+ msgAllTypes.setRepeatedDoubleList(arrayVal);
+ msgPackedTypes.setPackedFixed32List([1]);
+ arrayVal = msgPackedTypes.getPackedFixed32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedFixed32List(arrayVal);
+ msgAllTypes.setRepeatedFixed32List([1]);
+ arrayVal = msgAllTypes.getRepeatedFixed32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedFixed32List(arrayVal);
+ msgPackedTypes.setPackedFixed64List([1]);
+ arrayVal = msgPackedTypes.getPackedFixed64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedFixed64List(arrayVal);
+ msgAllTypes.setRepeatedFixed64List([1]);
+ arrayVal = msgAllTypes.getRepeatedFixed64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedFixed64List(arrayVal);
+ msgPackedTypes.setPackedFloatList([1.0]);
+ arrayVal = msgPackedTypes.getPackedFloatList();
+ arrayVal[0] = 1.0;
+ msgPackedTypes.setPackedFloatList(arrayVal);
+ msgAllTypes.setRepeatedFloatList([1.0]);
+ arrayVal = msgAllTypes.getRepeatedFloatList();
+ arrayVal[0] = 1.0;
+ msgAllTypes.setRepeatedFloatList(arrayVal);
+ msgPackedTypes.setPackedInt32List([1]);
+ arrayVal = msgPackedTypes.getPackedInt32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedInt32List(arrayVal);
+ msgAllTypes.setRepeatedInt32List([1]);
+ arrayVal = msgAllTypes.getRepeatedInt32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedInt32List(arrayVal);
+ msgPackedTypes.setPackedInt64List([1]);
+ arrayVal = msgPackedTypes.getPackedInt64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedInt64List(arrayVal);
+ msgAllTypes.setRepeatedInt64List([1]);
+ arrayVal = msgAllTypes.getRepeatedInt64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedInt64List(arrayVal);
+ // msgPackedTypes.setPackedEnumList([ForeignEnum.FOREIGN_BAR]);
+ // arrayVal = msgPackedTypes.getPackedEnumList();
+ // arrayVal[0] = ForeignEnum.FOREIGN_BAR;
+ // msgPackedTypes.setPackedEnumList(arrayVal);
+ // msgAllTypes.setRepeatedForeignEnumList([ForeignEnum.FOREIGN_BAR]);
+ // arrayVal = msgAllTypes.getRepeatedForeignEnumList();
+ // arrayVal[0] = ForeignEnum.FOREIGN_BAR;
+ // msgAllTypes.setRepeatedForeignEnumList(arrayVal);
+ msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
+ arrayVal = msgAllTypes.getRepeatedForeignMessageList();
+ arrayVal[0] = ForeignMessage.deserialize('');
+ msgAllTypes.setRepeatedForeignMessageList(arrayVal);
+ msgPackedTypes.setPackedSfixed32List([1]);
+ arrayVal = msgPackedTypes.getPackedSfixed32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSfixed32List(arrayVal);
+ msgAllTypes.setRepeatedSfixed32List([1]);
+ arrayVal = msgAllTypes.getRepeatedSfixed32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSfixed32List(arrayVal);
+ msgPackedTypes.setPackedSfixed64List([1]);
+ arrayVal = msgPackedTypes.getPackedSfixed64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSfixed64List(arrayVal);
+ msgAllTypes.setRepeatedSfixed64List([1]);
+ arrayVal = msgAllTypes.getRepeatedSfixed64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSfixed64List(arrayVal);
+ msgPackedTypes.setPackedSint32List([1]);
+ arrayVal = msgPackedTypes.getPackedSint32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSint32List(arrayVal);
+ msgAllTypes.setRepeatedSint32List([1]);
+ arrayVal = msgAllTypes.getRepeatedSint32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSint32List(arrayVal);
+ msgPackedTypes.setPackedSint64List([1]);
+ arrayVal = msgPackedTypes.getPackedSint64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSint64List(arrayVal);
+ msgAllTypes.setRepeatedSint64List([1]);
+ arrayVal = msgAllTypes.getRepeatedSint64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSint64List(arrayVal);
+ msgPackedTypes.setPackedUint32List([1]);
+ arrayVal = msgPackedTypes.getPackedUint32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedUint32List(arrayVal);
+ msgAllTypes.setRepeatedUint32List([1]);
+ arrayVal = msgAllTypes.getRepeatedUint32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedUint32List(arrayVal);
+ msgPackedTypes.setPackedUint64List([1]);
+ arrayVal = msgPackedTypes.getPackedUint64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedUint64List(arrayVal);
+ msgAllTypes.setRepeatedUint64List([1]);
+ arrayVal = msgAllTypes.getRepeatedUint64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedUint64List(arrayVal);
+
+ let s = '';
+ s += msgAllTypes.getOptionalBool() || false;
+ s += msgAllTypes.getOptionalBytes() || '';
+ // s += msgAllTypes.getOptionalBytes_asB64() || "";
+ // s += msgAllTypes.getOptionalBytes_asU8() || new Uint8Array([]);
+ s += msgAllTypes.getOptionalDouble() || 0.0;
+ s += msgAllTypes.getOptionalFixed32() || 0;
+ s += msgAllTypes.getOptionalFixed64() || 0;
+ s += msgAllTypes.getOptionalFloat() || 0.0;
+ s += msgAllTypes.getOptionalInt32() || 0;
+ s += msgAllTypes.getOptionalInt64() || 0;
+ // s += msgAllTypes.getOptionalForeignEnum() || ForeignEnum.FOREIGN_BAR;
+ s += msgAllTypes.getOptionalForeignMessage();
+ s += msgAllTypes.getOptionalSfixed32() || 0;
+ s += msgAllTypes.getOptionalSfixed64() || 0;
+ s += msgAllTypes.getOptionalSint32() || 0;
+ s += msgAllTypes.getOptionalSint64() || 0;
+ s += msgAllTypes.getOptionalString() || '';
+ s += msgAllTypes.getOptionalUint32() || 0;
+ s += msgAllTypes.getOptionalUint64() || 0;
+ s += msgAllTypes.getRepeatedBoolList();
+ s += msgAllTypes.getRepeatedBoolList()[0];
+ s += msgAllTypes.getRepeatedBoolList().length;
+ s += msgAllTypes.getRepeatedBytesList();
+ s += msgAllTypes.getRepeatedBytesList()[0];
+ s += msgAllTypes.getRepeatedBytesList().length;
+ s += msgAllTypes.getRepeatedBytesList_asB64();
+ s += msgAllTypes.getRepeatedBytesList_asU8();
+ s += msgAllTypes.getRepeatedDoubleList();
+ s += msgAllTypes.getRepeatedDoubleList()[0];
+ s += msgAllTypes.getRepeatedDoubleList().length;
+ s += msgAllTypes.getRepeatedFixed32List();
+ s += msgAllTypes.getRepeatedFixed32List()[0];
+ s += msgAllTypes.getRepeatedFixed32List().length;
+ s += msgAllTypes.getRepeatedFixed64List();
+ s += msgAllTypes.getRepeatedFixed64List()[0];
+ s += msgAllTypes.getRepeatedFixed64List().length;
+ s += msgAllTypes.getRepeatedFloatList();
+ s += msgAllTypes.getRepeatedFloatList()[0];
+ s += msgAllTypes.getRepeatedFloatList().length;
+ s += msgAllTypes.getRepeatedInt32List();
+ s += msgAllTypes.getRepeatedInt32List()[0];
+ s += msgAllTypes.getRepeatedInt32List().length;
+ s += msgAllTypes.getRepeatedInt64List();
+ s += msgAllTypes.getRepeatedInt64List()[0];
+ s += msgAllTypes.getRepeatedInt64List().length;
+ // s += msgAllTypes.getRepeatedForeignEnumList();
+ // s += msgAllTypes.getRepeatedForeignEnumList()[0];
+ // s += msgAllTypes.getRepeatedForeignEnumList().length;
+ s += msgAllTypes.getRepeatedForeignMessageList();
+ s += msgAllTypes.getRepeatedForeignMessageList()[0];
+ s += msgAllTypes.getRepeatedForeignMessageList().length;
+ s += msgAllTypes.getRepeatedSfixed32List();
+ s += msgAllTypes.getRepeatedSfixed32List()[0];
+ s += msgAllTypes.getRepeatedSfixed32List().length;
+ s += msgAllTypes.getRepeatedSfixed64List();
+ s += msgAllTypes.getRepeatedSfixed64List()[0];
+ s += msgAllTypes.getRepeatedSfixed64List().length;
+ s += msgAllTypes.getRepeatedSint32List();
+ s += msgAllTypes.getRepeatedSint32List()[0];
+ s += msgAllTypes.getRepeatedSint32List().length;
+ s += msgAllTypes.getRepeatedSint64List();
+ s += msgAllTypes.getRepeatedSint64List()[0];
+ s += msgAllTypes.getRepeatedSint64List().length;
+ s += msgAllTypes.getRepeatedStringList();
+ s += msgAllTypes.getRepeatedStringList()[0];
+ s += msgAllTypes.getRepeatedStringList().length;
+ s += msgAllTypes.getRepeatedUint32List();
+ s += msgAllTypes.getRepeatedUint32List()[0];
+ s += msgAllTypes.getRepeatedUint32List().length;
+ s += msgAllTypes.getRepeatedUint64List();
+ s += msgAllTypes.getRepeatedUint64List()[0];
+ s += msgAllTypes.getRepeatedUint64List().length;
+
+ s += msgAllTypes.serialize();
+ s += msgPackedTypes.serialize();
+
+ return s;
+}
+
+goog.global['__hiddenTest'] += accessAllTypes();
diff --git a/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js b/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js
new file mode 100644
index 0000000..3637df6
--- /dev/null
+++ b/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js
@@ -0,0 +1,314 @@
+/**
+ * @fileoverview The code size benchmark of apps JSPB for proto3 all types
+ */
+goog.module('protobuf.benchmark.code_size.apps_jspb.AllTypesProto3');
+
+// const ForeignEnum = goog.require('proto.proto3_unittest.ForeignEnum');
+const ForeignMessage = goog.require('proto.proto3_unittest.ForeignMessage');
+const TestAllTypes = goog.require('proto.proto3_unittest.TestAllTypes');
+const TestPackedTypes = goog.require('proto.proto3_unittest.TestPackedTypes');
+const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
+
+ensureCommonBaseLine();
+
+/**
+ * The testing scenario is the same as kernel one.
+ * We have
+ * 1) add element to repeated fields
+ * 2) add element list to repeated fields
+ * 3) set fields
+ * 4) set repeated fields element
+ * 5) get fields
+ * 6) get repeated fields element
+ * 7) get repeated fields length
+ * @return {string}
+ */
+function accessAllTypes() {
+ const msgAllTypes = TestAllTypes.deserialize('');
+ const msgPackedTypes = TestPackedTypes.deserialize('');
+
+ msgPackedTypes.addPackedBool(true);
+ [true].forEach((e) => msgPackedTypes.addPackedBool(e));
+ msgAllTypes.addRepeatedBool(true, 1);
+ [true].forEach((e) => msgAllTypes.addRepeatedBool(e));
+ msgAllTypes.addRepeatedBytes('1', 1);
+ ['1'].forEach((e) => msgAllTypes.addRepeatedBytes(e));
+ msgPackedTypes.addPackedDouble(1.0);
+ [1.0].forEach((e) => msgPackedTypes.addPackedDouble(e));
+ msgAllTypes.addRepeatedDouble(1.0, 1);
+ [1.0].forEach((e) => msgAllTypes.addRepeatedDouble(e));
+ msgPackedTypes.addPackedFixed32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedFixed32(e));
+ msgAllTypes.addRepeatedFixed32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedFixed32(e));
+ msgPackedTypes.addPackedFixed64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedFixed64(e));
+ msgAllTypes.addRepeatedFixed64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedFixed64(e));
+ msgPackedTypes.addPackedFloat(1.0, 1);
+ [1.0].forEach((e) => msgPackedTypes.addPackedFloat(e));
+ msgAllTypes.addRepeatedFloat(1.0, 1);
+ [1.0].forEach((e) => msgAllTypes.addRepeatedFloat(e));
+ msgPackedTypes.addPackedInt32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedInt32(e));
+ msgAllTypes.addRepeatedInt32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedInt32(e));
+ msgPackedTypes.addPackedInt64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedInt64(e));
+ msgAllTypes.addRepeatedInt64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedInt64(e));
+ // msgPackedTypes.addPackedEnum(ForeignEnum.FOREIGN_BAR);
+ // [ForeignEnum.FOREIGN_BAR].forEach((e) => msgPackedTypes.addPackedEnum(e));
+ // msgAllTypes.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR);
+ // [ForeignEnum.FOREIGN_BAR].forEach(
+ // (e) => msgAllTypes.addRepeatedForeignEnum(e));
+ msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
+ [ForeignMessage.deserialize('')].forEach(
+ (e) => msgAllTypes.addRepeatedForeignMessage(e));
+ msgPackedTypes.addPackedSfixed32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSfixed32(e));
+ msgAllTypes.addRepeatedSfixed32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSfixed32(e));
+ msgPackedTypes.addPackedSfixed64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSfixed64(e));
+ msgAllTypes.addRepeatedSfixed64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSfixed64(e));
+ msgPackedTypes.addPackedSint32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSint32(e));
+ msgAllTypes.addRepeatedSint32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSint32(e));
+ msgPackedTypes.addPackedSint64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedSint64(e));
+ msgAllTypes.addRepeatedSint64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedSint64(e));
+ msgAllTypes.addRepeatedString('', 1);
+ [''].forEach((e) => msgAllTypes.addRepeatedString(e));
+ msgPackedTypes.addPackedUint32(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedUint32(e));
+ msgAllTypes.addRepeatedUint32(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedUint32(e));
+ msgPackedTypes.addPackedUint64(1, 1);
+ [1].forEach((e) => msgPackedTypes.addPackedUint64(e));
+ msgAllTypes.addRepeatedUint64(1, 1);
+ [1].forEach((e) => msgAllTypes.addRepeatedUint64(e));
+
+ msgAllTypes.setOptionalBool(true);
+ msgAllTypes.setOptionalBytes('');
+ msgAllTypes.setOptionalDouble(1.0);
+ msgAllTypes.setOptionalFixed32(1);
+ msgAllTypes.setOptionalFixed64(1);
+ msgAllTypes.setOptionalFloat(1.0);
+ msgAllTypes.setOptionalInt32(1);
+ msgAllTypes.setOptionalInt64(1);
+ // msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
+ msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
+ msgAllTypes.setOptionalSfixed32(1);
+ msgAllTypes.setOptionalSfixed64(1);
+ msgAllTypes.setOptionalSint32(1);
+ msgAllTypes.setOptionalSint64(1);
+ msgAllTypes.setOptionalString('');
+ msgAllTypes.setOptionalUint32(1);
+ msgAllTypes.setOptionalUint64(1);
+ msgPackedTypes.setPackedBoolList([true]);
+ let arrayVal;
+ arrayVal = msgPackedTypes.getPackedBoolList();
+ arrayVal[0] = true;
+ msgPackedTypes.setPackedBoolList(arrayVal);
+ msgAllTypes.setRepeatedBoolList([true]);
+ arrayVal = msgAllTypes.getRepeatedBoolList();
+ arrayVal[0] = true;
+ msgAllTypes.setRepeatedBoolList(arrayVal);
+ msgAllTypes.setRepeatedBytesList(['']);
+ arrayVal = msgAllTypes.getRepeatedBytesList();
+ arrayVal[0] = '';
+ msgAllTypes.setRepeatedBytesList(arrayVal);
+ msgPackedTypes.setPackedDoubleList([1.0]);
+ arrayVal = msgPackedTypes.getPackedDoubleList();
+ arrayVal[0] = 1.0;
+ msgPackedTypes.setPackedDoubleList(arrayVal);
+ msgAllTypes.setRepeatedDoubleList([1.0]);
+ arrayVal = msgAllTypes.getRepeatedDoubleList();
+ arrayVal[0] = 1.0;
+ msgAllTypes.setRepeatedDoubleList(arrayVal);
+ msgPackedTypes.setPackedFixed32List([1]);
+ arrayVal = msgPackedTypes.getPackedFixed32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedFixed32List(arrayVal);
+ msgAllTypes.setRepeatedFixed32List([1]);
+ arrayVal = msgAllTypes.getRepeatedFixed32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedFixed32List(arrayVal);
+ msgPackedTypes.setPackedFixed64List([1]);
+ arrayVal = msgPackedTypes.getPackedFixed64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedFixed64List(arrayVal);
+ msgAllTypes.setRepeatedFixed64List([1]);
+ arrayVal = msgAllTypes.getRepeatedFixed64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedFixed64List(arrayVal);
+ msgPackedTypes.setPackedFloatList([1.0]);
+ arrayVal = msgPackedTypes.getPackedFloatList();
+ arrayVal[0] = 1.0;
+ msgPackedTypes.setPackedFloatList(arrayVal);
+ msgAllTypes.setRepeatedFloatList([1.0]);
+ arrayVal = msgAllTypes.getRepeatedFloatList();
+ arrayVal[0] = 1.0;
+ msgAllTypes.setRepeatedFloatList(arrayVal);
+ msgPackedTypes.setPackedInt32List([1]);
+ arrayVal = msgPackedTypes.getPackedInt32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedInt32List(arrayVal);
+ msgAllTypes.setRepeatedInt32List([1]);
+ arrayVal = msgAllTypes.getRepeatedInt32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedInt32List(arrayVal);
+ msgPackedTypes.setPackedInt64List([1]);
+ arrayVal = msgPackedTypes.getPackedInt64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedInt64List(arrayVal);
+ msgAllTypes.setRepeatedInt64List([1]);
+ arrayVal = msgAllTypes.getRepeatedInt64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedInt64List(arrayVal);
+ // msgPackedTypes.setPackedEnumList([ForeignEnum.FOREIGN_BAR]);
+ // arrayVal = msgPackedTypes.getPackedEnumList();
+ // arrayVal[0] = ForeignEnum.FOREIGN_BAR;
+ // msgPackedTypes.setPackedEnumList(arrayVal);
+ // msgAllTypes.setRepeatedForeignEnumList([ForeignEnum.FOREIGN_BAR]);
+ // arrayVal = msgAllTypes.getRepeatedForeignEnumList();
+ // arrayVal[0] = ForeignEnum.FOREIGN_BAR;
+ // msgAllTypes.setRepeatedForeignEnumList(arrayVal);
+ msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
+ arrayVal = msgAllTypes.getRepeatedForeignMessageList();
+ arrayVal[0] = ForeignMessage.deserialize('');
+ msgAllTypes.setRepeatedForeignMessageList(arrayVal);
+ msgPackedTypes.setPackedSfixed32List([1]);
+ arrayVal = msgPackedTypes.getPackedSfixed32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSfixed32List(arrayVal);
+ msgAllTypes.setRepeatedSfixed32List([1]);
+ arrayVal = msgAllTypes.getRepeatedSfixed32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSfixed32List(arrayVal);
+ msgPackedTypes.setPackedSfixed64List([1]);
+ arrayVal = msgPackedTypes.getPackedSfixed64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSfixed64List(arrayVal);
+ msgAllTypes.setRepeatedSfixed64List([1]);
+ arrayVal = msgAllTypes.getRepeatedSfixed64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSfixed64List(arrayVal);
+ msgPackedTypes.setPackedSint32List([1]);
+ arrayVal = msgPackedTypes.getPackedSint32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSint32List(arrayVal);
+ msgAllTypes.setRepeatedSint32List([1]);
+ arrayVal = msgAllTypes.getRepeatedSint32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSint32List(arrayVal);
+ msgPackedTypes.setPackedSint64List([1]);
+ arrayVal = msgPackedTypes.getPackedSint64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedSint64List(arrayVal);
+ msgAllTypes.setRepeatedSint64List([1]);
+ arrayVal = msgAllTypes.getRepeatedSint64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedSint64List(arrayVal);
+ msgPackedTypes.setPackedUint32List([1]);
+ arrayVal = msgPackedTypes.getPackedUint32List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedUint32List(arrayVal);
+ msgAllTypes.setRepeatedUint32List([1]);
+ arrayVal = msgAllTypes.getRepeatedUint32List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedUint32List(arrayVal);
+ msgPackedTypes.setPackedUint64List([1]);
+ arrayVal = msgPackedTypes.getPackedUint64List();
+ arrayVal[0] = 1;
+ msgPackedTypes.setPackedUint64List(arrayVal);
+ msgAllTypes.setRepeatedUint64List([1]);
+ arrayVal = msgAllTypes.getRepeatedUint64List();
+ arrayVal[0] = 1;
+ msgAllTypes.setRepeatedUint64List(arrayVal);
+
+ let s = '';
+ s += msgAllTypes.getOptionalBool() || false;
+ s += msgAllTypes.getOptionalBytes() || '';
+ // s += msgAllTypes.getOptionalBytes_asB64() || "";
+ // s += msgAllTypes.getOptionalBytes_asU8() || new Uint8Array([]);
+ s += msgAllTypes.getOptionalDouble() || 0.0;
+ s += msgAllTypes.getOptionalFixed32() || 0;
+ s += msgAllTypes.getOptionalFixed64() || 0;
+ s += msgAllTypes.getOptionalFloat() || 0.0;
+ s += msgAllTypes.getOptionalInt32() || 0;
+ s += msgAllTypes.getOptionalInt64() || 0;
+ // s += msgAllTypes.getOptionalForeignEnum() || ForeignEnum.FOREIGN_BAR;
+ s += msgAllTypes.getOptionalForeignMessage();
+ s += msgAllTypes.getOptionalSfixed32() || 0;
+ s += msgAllTypes.getOptionalSfixed64() || 0;
+ s += msgAllTypes.getOptionalSint32() || 0;
+ s += msgAllTypes.getOptionalSint64() || 0;
+ s += msgAllTypes.getOptionalString() || '';
+ s += msgAllTypes.getOptionalUint32() || 0;
+ s += msgAllTypes.getOptionalUint64() || 0;
+ s += msgAllTypes.getRepeatedBoolList();
+ s += msgAllTypes.getRepeatedBoolList()[0];
+ s += msgAllTypes.getRepeatedBoolList().length;
+ s += msgAllTypes.getRepeatedBytesList();
+ s += msgAllTypes.getRepeatedBytesList()[0];
+ s += msgAllTypes.getRepeatedBytesList().length;
+ s += msgAllTypes.getRepeatedBytesList_asB64();
+ s += msgAllTypes.getRepeatedBytesList_asU8();
+ s += msgAllTypes.getRepeatedDoubleList();
+ s += msgAllTypes.getRepeatedDoubleList()[0];
+ s += msgAllTypes.getRepeatedDoubleList().length;
+ s += msgAllTypes.getRepeatedFixed32List();
+ s += msgAllTypes.getRepeatedFixed32List()[0];
+ s += msgAllTypes.getRepeatedFixed32List().length;
+ s += msgAllTypes.getRepeatedFixed64List();
+ s += msgAllTypes.getRepeatedFixed64List()[0];
+ s += msgAllTypes.getRepeatedFixed64List().length;
+ s += msgAllTypes.getRepeatedFloatList();
+ s += msgAllTypes.getRepeatedFloatList()[0];
+ s += msgAllTypes.getRepeatedFloatList().length;
+ s += msgAllTypes.getRepeatedInt32List();
+ s += msgAllTypes.getRepeatedInt32List()[0];
+ s += msgAllTypes.getRepeatedInt32List().length;
+ s += msgAllTypes.getRepeatedInt64List();
+ s += msgAllTypes.getRepeatedInt64List()[0];
+ s += msgAllTypes.getRepeatedInt64List().length;
+ // s += msgAllTypes.getRepeatedForeignEnumList();
+ // s += msgAllTypes.getRepeatedForeignEnumList()[0];
+ // s += msgAllTypes.getRepeatedForeignEnumList().length;
+ s += msgAllTypes.getRepeatedForeignMessageList();
+ s += msgAllTypes.getRepeatedForeignMessageList()[0];
+ s += msgAllTypes.getRepeatedForeignMessageList().length;
+ s += msgAllTypes.getRepeatedSfixed32List();
+ s += msgAllTypes.getRepeatedSfixed32List()[0];
+ s += msgAllTypes.getRepeatedSfixed32List().length;
+ s += msgAllTypes.getRepeatedSfixed64List();
+ s += msgAllTypes.getRepeatedSfixed64List()[0];
+ s += msgAllTypes.getRepeatedSfixed64List().length;
+ s += msgAllTypes.getRepeatedSint32List();
+ s += msgAllTypes.getRepeatedSint32List()[0];
+ s += msgAllTypes.getRepeatedSint32List().length;
+ s += msgAllTypes.getRepeatedSint64List();
+ s += msgAllTypes.getRepeatedSint64List()[0];
+ s += msgAllTypes.getRepeatedSint64List().length;
+ s += msgAllTypes.getRepeatedStringList();
+ s += msgAllTypes.getRepeatedStringList()[0];
+ s += msgAllTypes.getRepeatedStringList().length;
+ s += msgAllTypes.getRepeatedUint32List();
+ s += msgAllTypes.getRepeatedUint32List()[0];
+ s += msgAllTypes.getRepeatedUint32List().length;
+ s += msgAllTypes.getRepeatedUint64List();
+ s += msgAllTypes.getRepeatedUint64List()[0];
+ s += msgAllTypes.getRepeatedUint64List().length;
+
+ s += msgAllTypes.serialize();
+ s += msgPackedTypes.serialize();
+
+ return s;
+}
+
+goog.global['__hiddenTest'] += accessAllTypes();
diff --git a/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto2.js b/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto2.js
new file mode 100644
index 0000000..7bea88a
--- /dev/null
+++ b/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto2.js
@@ -0,0 +1,53 @@
+/**
+ * @fileoverview The code size benchmark of apps JSPB for proto2 popular types.
+ */
+goog.module('protobuf.benchmark.code_size.apps_jspb.PopularTypesProto2');
+
+// const ForeignEnum = goog.require('proto.proto2_unittest.ForeignEnum');
+const ForeignMessage = goog.require('proto.proto2_unittest.ForeignMessage');
+const TestAllTypes = goog.require('proto.proto2_unittest.TestAllTypes');
+const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
+
+ensureCommonBaseLine();
+
+/**
+ * @return {string}
+ */
+function accessPopularTypes() {
+ const msgAllTypes = TestAllTypes.deserialize('');
+ msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
+ [ForeignMessage.deserialize('')].forEach(
+ (e) => msgAllTypes.addRepeatedForeignMessage(e));
+
+ msgAllTypes.setOptionalString('');
+ msgAllTypes.setOptionalInt32(1);
+ msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
+ msgAllTypes.setOptionalBool(true);
+ // msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
+ msgAllTypes.setOptionalInt64(1);
+ msgAllTypes.setOptionalDouble(1.0);
+ msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
+ let arrayVal = msgAllTypes.getRepeatedForeignMessageList();
+ arrayVal[0] = ForeignMessage.deserialize('');
+ msgAllTypes.setRepeatedForeignMessageList(arrayVal);
+ msgAllTypes.setOptionalUint64(1);
+
+ let s = '';
+ s += msgAllTypes.getOptionalString();
+ s += msgAllTypes.getOptionalInt32();
+ s += msgAllTypes.getOptionalForeignMessage();
+ s += msgAllTypes.getOptionalBool();
+ // s += msgAllTypes.getOptionalForeignEnum();
+ s += msgAllTypes.getOptionalInt64();
+ s += msgAllTypes.getOptionalDouble();
+ s += msgAllTypes.getRepeatedForeignMessageList();
+ s += msgAllTypes.getRepeatedForeignMessageList()[0];
+ s += msgAllTypes.getRepeatedForeignMessageList().length;
+ s += msgAllTypes.getOptionalUint64();
+
+ s += msgAllTypes.serialize();
+
+ return s;
+}
+
+goog.global['__hiddenTest'] += accessPopularTypes();
diff --git a/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js b/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js
new file mode 100644
index 0000000..9b80428
--- /dev/null
+++ b/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js
@@ -0,0 +1,53 @@
+/**
+ * @fileoverview The code size benchmark of apps JSPB for proto3 popular types.
+ */
+goog.module('protobuf.benchmark.code_size.apps_jspb.PopularTypesProto3');
+
+// const ForeignEnum = goog.require('proto.proto3_unittest.ForeignEnum');
+const ForeignMessage = goog.require('proto.proto3_unittest.ForeignMessage');
+const TestAllTypes = goog.require('proto.proto3_unittest.TestAllTypes');
+const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
+
+ensureCommonBaseLine();
+
+/**
+ * @return {string}
+ */
+function accessPopularTypes() {
+ const msgAllTypes = TestAllTypes.deserialize('');
+ msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
+ [ForeignMessage.deserialize('')].forEach(
+ (e) => msgAllTypes.addRepeatedForeignMessage(e));
+
+ msgAllTypes.setOptionalString('');
+ msgAllTypes.setOptionalInt32(1);
+ msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
+ msgAllTypes.setOptionalBool(true);
+ // msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
+ msgAllTypes.setOptionalInt64(1);
+ msgAllTypes.setOptionalDouble(1.0);
+ msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
+ let arrayVal = msgAllTypes.getRepeatedForeignMessageList();
+ arrayVal[0] = ForeignMessage.deserialize('');
+ msgAllTypes.setRepeatedForeignMessageList(arrayVal);
+ msgAllTypes.setOptionalUint64(1);
+
+ let s = '';
+ s += msgAllTypes.getOptionalString();
+ s += msgAllTypes.getOptionalInt32();
+ s += msgAllTypes.getOptionalForeignMessage();
+ s += msgAllTypes.getOptionalBool();
+ // s += msgAllTypes.getOptionalForeignEnum();
+ s += msgAllTypes.getOptionalInt64();
+ s += msgAllTypes.getOptionalDouble();
+ s += msgAllTypes.getRepeatedForeignMessageList();
+ s += msgAllTypes.getRepeatedForeignMessageList()[0];
+ s += msgAllTypes.getRepeatedForeignMessageList().length;
+ s += msgAllTypes.getOptionalUint64();
+
+ s += msgAllTypes.serialize();
+
+ return s;
+}
+
+goog.global['__hiddenTest'] += accessPopularTypes();
diff --git a/js/experimental/benchmarks/code_size/code_size_base.js b/js/experimental/benchmarks/code_size/code_size_base.js
new file mode 100644
index 0000000..04f6a47
--- /dev/null
+++ b/js/experimental/benchmarks/code_size/code_size_base.js
@@ -0,0 +1,57 @@
+/**
+ * @fileoverview Ensures types are live that would be live in a typical g3
+ * JS program.
+ *
+ * Making certain constructs live ensures that we compare against the same
+ * baseline for all code size benchmarks. This increases the size
+ * of our benchmarks, but note that this size in a regular app would be
+ * attributes to other places.
+ */
+goog.module('protobuf.benchmark.codeSize.codeSizeBase');
+
+
+/**
+ * Ensures that the array iterator polyfill is live.
+ * @return {string}
+ */
+function useArrayIterator() {
+ let a = [];
+ let s = '';
+ for (let value of a) {
+ s += value;
+ }
+ return s;
+}
+
+/**
+ * Ensures that the symbol iterator polyfill is live.
+ * @return {string}
+ */
+function useSymbolIterator() {
+ /**
+ * @implements {Iterable}
+ */
+ class Foo {
+ /** @return {!Iterator} */
+ [Symbol.iterator]() {}
+ }
+
+ let foo = new Foo();
+ let s = '';
+ for (let value of foo) {
+ s += value;
+ }
+ return s;
+}
+
+/**
+ * Ensures certain base libs are live so we can have an apples to apples
+ * comparison for code size of different implementations
+ */
+function ensureCommonBaseLine() {
+ goog.global['__hiddenTest'] += useArrayIterator();
+ goog.global['__hiddenTest'] += useSymbolIterator();
+}
+
+
+exports = {ensureCommonBaseLine};
diff --git a/js/experimental/benchmarks/code_size/kernel/all_types.js b/js/experimental/benchmarks/code_size/kernel/all_types.js
new file mode 100644
index 0000000..17cc7a6
--- /dev/null
+++ b/js/experimental/benchmarks/code_size/kernel/all_types.js
@@ -0,0 +1,227 @@
+/**
+ * @fileoverview The code size benchmark of binary kernel for accessing all
+ * types setter and getter.
+ */
+goog.module('protobuf.benchmark.KernelCodeSizeBenchmarkAllTypes');
+
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
+const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
+
+ensureCommonBaseLine();
+
+
+/**
+ * @return {string}
+ */
+function accessAllTypes() {
+ const message = new TestMessage(Kernel.createEmpty());
+
+ message.addPackedBoolElement(1, true);
+ message.addPackedBoolIterable(1, [true]);
+ message.addUnpackedBoolElement(1, true);
+ message.addUnpackedBoolIterable(1, [true]);
+ message.addRepeatedBytesElement(1, ByteString.EMPTY);
+ message.addRepeatedBytesIterable(1, [ByteString.EMPTY]);
+ message.addPackedDoubleElement(1, 1.0);
+ message.addPackedDoubleIterable(1, [1.0]);
+ message.addUnpackedDoubleElement(1, 1.0);
+ message.addUnpackedDoubleIterable(1, [1.0]);
+ message.addPackedFixed32Element(1, 1);
+ message.addPackedFixed32Iterable(1, [1]);
+ message.addUnpackedFixed32Element(1, 1);
+ message.addUnpackedFixed32Iterable(1, [1]);
+ message.addPackedFixed64Element(1, Int64.fromBits(0, 1));
+ message.addPackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addUnpackedFixed64Element(1, Int64.fromBits(0, 1));
+ message.addUnpackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addPackedFloatElement(1, 1.0);
+ message.addPackedFloatIterable(1, [1.0]);
+ message.addUnpackedFloatElement(1, 1.0);
+ message.addUnpackedFloatIterable(1, [1.0]);
+ message.addPackedInt32Element(1, 1);
+ message.addPackedInt32Iterable(1, [1]);
+ message.addUnpackedInt32Element(1, 1);
+ message.addUnpackedInt32Iterable(1, [1]);
+ message.addPackedInt64Element(1, Int64.fromBits(0, 1));
+ message.addPackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addUnpackedInt64Element(1, Int64.fromBits(0, 1));
+ message.addUnpackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addRepeatedMessageElement(1, message, TestMessage.instanceCreator);
+ message.addRepeatedMessageIterable(1, [message], TestMessage.instanceCreator);
+ message.addPackedSfixed32Element(1, 1);
+ message.addPackedSfixed32Iterable(1, [1]);
+ message.addUnpackedSfixed32Element(1, 1);
+ message.addUnpackedSfixed32Iterable(1, [1]);
+ message.addPackedSfixed64Element(1, Int64.fromBits(0, 1));
+ message.addPackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addUnpackedSfixed64Element(1, Int64.fromBits(0, 1));
+ message.addUnpackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addPackedSint32Element(1, 1);
+ message.addPackedSint32Iterable(1, [1]);
+ message.addUnpackedSint32Element(1, 1);
+ message.addUnpackedSint32Iterable(1, [1]);
+ message.addPackedSint64Element(1, Int64.fromBits(0, 1));
+ message.addPackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addUnpackedSint64Element(1, Int64.fromBits(0, 1));
+ message.addUnpackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addRepeatedStringElement(1, '');
+ message.addRepeatedStringIterable(1, ['']);
+ message.addPackedUint32Element(1, 1);
+ message.addPackedUint32Iterable(1, [1]);
+ message.addUnpackedUint32Element(1, 1);
+ message.addUnpackedUint32Iterable(1, [1]);
+ message.addPackedUint64Element(1, Int64.fromBits(0, 1));
+ message.addPackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.addUnpackedUint64Element(1, Int64.fromBits(0, 1));
+ message.addUnpackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
+
+ message.setBool(1, true);
+ message.setBytes(1, ByteString.EMPTY);
+ message.setDouble(1, 1.0);
+ message.setFixed32(1, 1);
+ message.setFixed64(1, Int64.fromBits(0, 1));
+ message.setFloat(1, 1.0);
+ message.setInt32(1, 1);
+ message.setInt64(1, Int64.fromBits(0, 1));
+ message.setMessage(1, message);
+ message.setSfixed32(1, 1);
+ message.setSfixed64(1, Int64.fromBits(0, 1));
+ message.setSint32(1, 1);
+ message.setSint64(1, Int64.fromBits(0, 1));
+ message.setString(1, 'abc');
+ message.setUint32(1, 1);
+ message.setUint64(1, Int64.fromBits(0, 1));
+ message.setPackedBoolElement(1, 0, true);
+ message.setPackedBoolIterable(1, [true]);
+ message.setUnpackedBoolElement(1, 0, true);
+ message.setUnpackedBoolIterable(1, [true]);
+ message.setRepeatedBytesElement(1, 0, ByteString.EMPTY);
+ message.setRepeatedBytesIterable(1, [ByteString.EMPTY]);
+ message.setPackedDoubleElement(1, 0, 1.0);
+ message.setPackedDoubleIterable(1, [1.0]);
+ message.setUnpackedDoubleElement(1, 0, 1.0);
+ message.setUnpackedDoubleIterable(1, [1.0]);
+ message.setPackedFixed32Element(1, 0, 1);
+ message.setPackedFixed32Iterable(1, [1]);
+ message.setUnpackedFixed32Element(1, 0, 1);
+ message.setUnpackedFixed32Iterable(1, [1]);
+ message.setPackedFixed64Element(1, 0, Int64.fromBits(0, 1));
+ message.setPackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setUnpackedFixed64Element(1, 0, Int64.fromBits(0, 1));
+ message.setUnpackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setPackedFloatElement(1, 0, 1.0);
+ message.setPackedFloatIterable(1, [1.0]);
+ message.setUnpackedFloatElement(1, 0, 1.0);
+ message.setUnpackedFloatIterable(1, [1.0]);
+ message.setPackedInt32Element(1, 0, 1);
+ message.setPackedInt32Iterable(1, [1]);
+ message.setUnpackedInt32Element(1, 0, 1);
+ message.setUnpackedInt32Iterable(1, [1]);
+ message.setPackedInt64Element(1, 0, Int64.fromBits(0, 1));
+ message.setPackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setUnpackedInt64Element(1, 0, Int64.fromBits(0, 1));
+ message.setUnpackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setRepeatedMessageElement(1, message, TestMessage.instanceCreator, 0);
+ message.setRepeatedMessageIterable(1, [message]);
+ message.setPackedSfixed32Element(1, 0, 1);
+ message.setPackedSfixed32Iterable(1, [1]);
+ message.setUnpackedSfixed32Element(1, 0, 1);
+ message.setUnpackedSfixed32Iterable(1, [1]);
+ message.setPackedSfixed64Element(1, 0, Int64.fromBits(0, 1));
+ message.setPackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setUnpackedSfixed64Element(1, 0, Int64.fromBits(0, 1));
+ message.setUnpackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setRepeatedStringElement(1, 0, '');
+ message.setRepeatedStringIterable(1, ['']);
+ message.setPackedSint32Element(1, 0, 1);
+ message.setPackedSint32Iterable(1, [1]);
+ message.setUnpackedSint32Element(1, 0, 1);
+ message.setUnpackedSint32Iterable(1, [1]);
+ message.setPackedSint64Element(1, 0, Int64.fromBits(0, 1));
+ message.setPackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setUnpackedSint64Element(1, 0, Int64.fromBits(0, 1));
+ message.setUnpackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setPackedUint32Element(1, 0, 1);
+ message.setPackedUint32Iterable(1, [1]);
+ message.setUnpackedUint32Element(1, 0, 1);
+ message.setUnpackedUint32Iterable(1, [1]);
+ message.setPackedUint64Element(1, 0, Int64.fromBits(0, 1));
+ message.setPackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
+ message.setUnpackedUint64Element(1, 0, Int64.fromBits(0, 1));
+ message.setUnpackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
+
+ let s = '';
+ s += message.getBoolWithDefault(1);
+ s += message.getBytesWithDefault(1);
+ s += message.getDoubleWithDefault(1);
+ s += message.getFixed32WithDefault(1);
+ s += message.getFixed64WithDefault(1);
+ s += message.getFloatWithDefault(1);
+ s += message.getInt32WithDefault(1);
+ s += message.getInt64WithDefault(1);
+ s += message.getMessage(1, TestMessage.instanceCreator);
+ s += message.getSfixed32WithDefault(1);
+ s += message.getSfixed64WithDefault(1);
+ s += message.getSint32WithDefault(1);
+ s += message.getSint64WithDefault(1);
+ s += message.getStringWithDefault(1);
+ s += message.getUint32WithDefault(1);
+ s += message.getUint64WithDefault(1);
+ s += message.getRepeatedBoolElement(1, 0);
+ s += message.getRepeatedBoolIterable(1);
+ s += message.getRepeatedBoolSize(1);
+ s += message.getRepeatedBytesElement(1, 0);
+ s += message.getRepeatedBytesIterable(1);
+ s += message.getRepeatedBytesSize(1);
+ s += message.getRepeatedDoubleElement(1, 0);
+ s += message.getRepeatedDoubleIterable(1);
+ s += message.getRepeatedDoubleSize(1);
+ s += message.getRepeatedFixed32Element(1, 0);
+ s += message.getRepeatedFixed32Iterable(1);
+ s += message.getRepeatedFixed32Size(1);
+ s += message.getRepeatedFixed64Element(1, 0);
+ s += message.getRepeatedFixed64Iterable(1);
+ s += message.getRepeatedFixed64Size(1);
+ s += message.getRepeatedFloatElement(1, 0);
+ s += message.getRepeatedFloatIterable(1);
+ s += message.getRepeatedFloatSize(1);
+ s += message.getRepeatedInt32Element(1, 0);
+ s += message.getRepeatedInt32Iterable(1);
+ s += message.getRepeatedInt32Size(1);
+ s += message.getRepeatedInt64Element(1, 0);
+ s += message.getRepeatedInt64Iterable(1);
+ s += message.getRepeatedInt64Size(1);
+ s += message.getRepeatedMessageElement(1, TestMessage.instanceCreator, 0);
+ s += message.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ s += message.getRepeatedMessageSize(1, TestMessage.instanceCreator);
+ s += message.getRepeatedSfixed32Element(1, 0);
+ s += message.getRepeatedSfixed32Iterable(1);
+ s += message.getRepeatedSfixed32Size(1);
+ s += message.getRepeatedSfixed64Element(1, 0);
+ s += message.getRepeatedSfixed64Iterable(1);
+ s += message.getRepeatedSfixed64Size(1);
+ s += message.getRepeatedSint32Element(1, 0);
+ s += message.getRepeatedSint32Iterable(1);
+ s += message.getRepeatedSint32Size(1);
+ s += message.getRepeatedSint64Element(1, 0);
+ s += message.getRepeatedSint64Iterable(1);
+ s += message.getRepeatedSint64Size(1);
+ s += message.getRepeatedStringElement(1, 0);
+ s += message.getRepeatedStringIterable(1);
+ s += message.getRepeatedStringSize(1);
+ s += message.getRepeatedUint32Element(1, 0);
+ s += message.getRepeatedUint32Iterable(1);
+ s += message.getRepeatedUint32Size(1);
+ s += message.getRepeatedUint64Element(1, 0);
+ s += message.getRepeatedUint64Iterable(1);
+ s += message.getRepeatedUint64Size(1);
+
+ s += message.serialize();
+
+ return s;
+}
+
+goog.global['__hiddenTest'] += accessAllTypes();
diff --git a/js/experimental/benchmarks/code_size/kernel/popular_types.js b/js/experimental/benchmarks/code_size/kernel/popular_types.js
new file mode 100644
index 0000000..90e1792
--- /dev/null
+++ b/js/experimental/benchmarks/code_size/kernel/popular_types.js
@@ -0,0 +1,68 @@
+/**
+ * @fileoverview The code size benchmark of binary kernel for accessing all
+ * popular types setter and getter.
+ *
+ * The types are those whose usage are more than 1%:
+ *
+ * ('STRING__LABEL_OPTIONAL', '29.7214%')
+ * ('INT32__LABEL_OPTIONAL', '17.7277%')
+ * ('MESSAGE__LABEL_OPTIONAL', '15.6462%')
+ * ('BOOL__LABEL_OPTIONAL', '13.0038%')
+ * ('ENUM__LABEL_OPTIONAL', '11.4466%')
+ * ('INT64__LABEL_OPTIONAL', '3.2198%')
+ * ('DOUBLE__LABEL_OPTIONAL', '1.357%')
+ * ('MESSAGE__LABEL_REPEATED', '1.2775%')
+ * ('FIXED32__LABEL_REQUIRED', '1.2%')
+ * ('UINT64__LABEL_OPTIONAL', '1.1771%')
+ * ('STRING__LABEL_REQUIRED', '1.0785%')
+ *
+ */
+goog.module('protobuf.benchmark.KernelCodeSizeBenchmarkPopularTypes');
+
+const Int64 = goog.require('protobuf.Int64');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
+const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
+
+ensureCommonBaseLine();
+
+
+/**
+ * @return {string}
+ */
+function accessAllTypes() {
+ const message = new TestMessage(Kernel.createEmpty());
+
+ message.addRepeatedMessageElement(1, message, TestMessage.instanceCreator);
+ message.addRepeatedMessageIterable(1, [message], TestMessage.instanceCreator);
+
+ message.setString(1, 'abc');
+ message.setInt32(1, 1);
+ message.setMessage(1, message);
+ message.setBool(1, true);
+ message.setInt64(1, Int64.fromBits(0, 1));
+ message.setDouble(1, 1.0);
+ message.setRepeatedMessageElement(1, message, TestMessage.instanceCreator, 0);
+ message.setRepeatedMessageIterable(1, [message]);
+ message.setUint64(1, Int64.fromBits(0, 1));
+
+
+ let s = '';
+ s += message.getStringWithDefault(1);
+ s += message.getInt32WithDefault(1);
+ s += message.getMessage(1, TestMessage.instanceCreator);
+ s += message.getMessageOrNull(1, TestMessage.instanceCreator);
+ s += message.getBoolWithDefault(1);
+ s += message.getInt64WithDefault(1);
+ s += message.getDoubleWithDefault(1);
+ s += message.getRepeatedMessageElement(1, TestMessage.instanceCreator, 0);
+ s += message.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ s += message.getRepeatedMessageSize(1, TestMessage.instanceCreator);
+ s += message.getUint64WithDefault(1);
+
+ s += message.serialize();
+
+ return s;
+}
+
+goog.global['__hiddenTest'] += accessAllTypes();
diff --git a/js/experimental/runtime/bytestring.js b/js/experimental/runtime/bytestring.js
new file mode 100644
index 0000000..d6af5f1
--- /dev/null
+++ b/js/experimental/runtime/bytestring.js
@@ -0,0 +1,183 @@
+/**
+ * @fileoverview Provides ByteString as a basic data type for protos.
+ */
+goog.module('protobuf.ByteString');
+
+const base64 = goog.require('goog.crypt.base64');
+const {arrayBufferSlice, cloneArrayBufferView, hashUint8Array, uint8ArrayEqual} = goog.require('protobuf.binary.typedArrays');
+
+/**
+ * Immutable sequence of bytes.
+ *
+ * Bytes can be obtained as an ArrayBuffer or a base64 encoded string.
+ * @final
+ */
+class ByteString {
+ /**
+ * @param {?Uint8Array} bytes
+ * @param {?string} base64
+ * @private
+ */
+ constructor(bytes, base64) {
+ /** @private {?Uint8Array}*/
+ this.bytes_ = bytes;
+ /** @private {?string} */
+ this.base64_ = base64;
+ /** @private {number} */
+ this.hashCode_ = 0;
+ }
+
+ /**
+ * Constructs a ByteString instance from a base64 string.
+ * @param {string} value
+ * @return {!ByteString}
+ */
+ static fromBase64String(value) {
+ if (value == null) {
+ throw new Error('value must not be null');
+ }
+ return new ByteString(/* bytes */ null, value);
+ }
+
+ /**
+ * Constructs a ByteString from an array buffer.
+ * @param {!ArrayBuffer} bytes
+ * @param {number=} start
+ * @param {number=} end
+ * @return {!ByteString}
+ */
+ static fromArrayBuffer(bytes, start = 0, end = undefined) {
+ return new ByteString(
+ new Uint8Array(arrayBufferSlice(bytes, start, end)), /* base64 */ null);
+ }
+
+ /**
+ * Constructs a ByteString from any ArrayBufferView (e.g. DataView,
+ * TypedArray, Uint8Array, etc.).
+ * @param {!ArrayBufferView} bytes
+ * @return {!ByteString}
+ */
+ static fromArrayBufferView(bytes) {
+ return new ByteString(cloneArrayBufferView(bytes), /* base64 */ null);
+ }
+
+ /**
+ * Constructs a ByteString from an Uint8Array. DON'T MODIFY the underlying
+ * ArrayBuffer, since the ByteString directly uses it without making a copy.
+ *
+ * This method exists so that internal APIs can construct a ByteString without
+ * paying the penalty of copying an ArrayBuffer when that ArrayBuffer is not
+ * supposed to change. It is exposed to a limited number of internal classes
+ * through bytestring_internal.js.
+ *
+ * @param {!Uint8Array} bytes
+ * @return {!ByteString}
+ * @package
+ */
+ static fromUint8ArrayUnsafe(bytes) {
+ return new ByteString(bytes, /* base64 */ null);
+ }
+
+ /**
+ * Returns this ByteString as an ArrayBuffer.
+ * @return {!ArrayBuffer}
+ */
+ toArrayBuffer() {
+ const bytes = this.ensureBytes_();
+ return arrayBufferSlice(
+ bytes.buffer, bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
+ }
+
+ /**
+ * Returns this ByteString as an Uint8Array. DON'T MODIFY the returned array,
+ * since the ByteString holds the reference to the same array.
+ *
+ * This method exists so that internal APIs can get contents of a ByteString
+ * without paying the penalty of copying an ArrayBuffer. It is exposed to a
+ * limited number of internal classes through bytestring_internal.js.
+ * @return {!Uint8Array}
+ * @package
+ */
+ toUint8ArrayUnsafe() {
+ return this.ensureBytes_();
+ }
+
+ /**
+ * Returns this ByteString as a base64 encoded string.
+ * @return {string}
+ */
+ toBase64String() {
+ return this.ensureBase64String_();
+ }
+
+ /**
+ * Returns true for Bytestrings that contain identical values.
+ * @param {*} other
+ * @return {boolean}
+ */
+ equals(other) {
+ if (this === other) {
+ return true;
+ }
+
+ if (!(other instanceof ByteString)) {
+ return false;
+ }
+
+ const otherByteString = /** @type {!ByteString} */ (other);
+ return uint8ArrayEqual(this.ensureBytes_(), otherByteString.ensureBytes_());
+ }
+
+ /**
+ * Returns a number (int32) that is suitable for using in hashed structures.
+ * @return {number}
+ */
+ hashCode() {
+ if (this.hashCode_ == 0) {
+ this.hashCode_ = hashUint8Array(this.ensureBytes_());
+ }
+ return this.hashCode_;
+ }
+
+ /**
+ * Returns true if the bytestring is empty.
+ * @return {boolean}
+ */
+ isEmpty() {
+ if (this.bytes_ != null && this.bytes_.byteLength == 0) {
+ return true;
+ }
+ if (this.base64_ != null && this.base64_.length == 0) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @return {!Uint8Array}
+ * @private
+ */
+ ensureBytes_() {
+ if (this.bytes_) {
+ return this.bytes_;
+ }
+ return this.bytes_ = base64.decodeStringToUint8Array(
+ /** @type {string} */ (this.base64_));
+ }
+
+ /**
+ * @return {string}
+ * @private
+ */
+ ensureBase64String_() {
+ if (this.base64_ == null) {
+ this.base64_ = base64.encodeByteArray(this.bytes_);
+ }
+ return this.base64_;
+ }
+}
+
+/** @const {!ByteString} */
+ByteString.EMPTY = new ByteString(new Uint8Array(0), null);
+
+exports = ByteString;
diff --git a/js/experimental/runtime/bytestring_internal.js b/js/experimental/runtime/bytestring_internal.js
new file mode 100644
index 0000000..2ea3f60
--- /dev/null
+++ b/js/experimental/runtime/bytestring_internal.js
@@ -0,0 +1,33 @@
+/**
+ * @fileoverview Exposes internal only functions for ByteString. The
+ * corresponding BUILD rule restricts access to this file to only the binary
+ * kernel and APIs directly using the binary kernel.
+ */
+goog.module('protobuf.byteStringInternal');
+
+const ByteString = goog.require('protobuf.ByteString');
+
+/**
+ * Constructs a ByteString from an Uint8Array. DON'T MODIFY the underlying
+ * ArrayBuffer, since the ByteString directly uses it without making a copy.
+ * @param {!Uint8Array} bytes
+ * @return {!ByteString}
+ */
+function byteStringFromUint8ArrayUnsafe(bytes) {
+ return ByteString.fromUint8ArrayUnsafe(bytes);
+}
+
+/**
+ * Returns this ByteString as an Uint8Array. DON'T MODIFY the returned array,
+ * since the ByteString holds the reference to the same array.
+ * @param {!ByteString} bytes
+ * @return {!Uint8Array}
+ */
+function byteStringToUint8ArrayUnsafe(bytes) {
+ return bytes.toUint8ArrayUnsafe();
+}
+
+exports = {
+ byteStringFromUint8ArrayUnsafe,
+ byteStringToUint8ArrayUnsafe,
+};
diff --git a/js/experimental/runtime/bytestring_test.js b/js/experimental/runtime/bytestring_test.js
new file mode 100644
index 0000000..b9928b6
--- /dev/null
+++ b/js/experimental/runtime/bytestring_test.js
@@ -0,0 +1,277 @@
+goog.module('proto.im.integration.ByteStringFieldsTest');
+goog.setTestOnly();
+
+const ByteString = goog.require('protobuf.ByteString');
+const {arrayBufferSlice} = goog.require('protobuf.binary.typedArrays');
+
+const /** !ArrayBuffer */ TEST_BYTES = new Uint8Array([1, 2, 3, 4]).buffer;
+const /** !ByteString */ TEST_STRING = ByteString.fromArrayBuffer(TEST_BYTES);
+const /** !ArrayBuffer */ PREFIXED_TEST_BYTES =
+ new Uint8Array([0, 1, 2, 3, 4]).buffer;
+const /** string */ HALLO_IN_BASE64 = 'aGFsbG8=';
+const /** string */ HALLO_IN_BASE64_WITH_SPACES = 'a G F s b G 8=';
+const /** !ArrayBufferView */ BYTES_WITH_HALLO = new Uint8Array([
+ 'h'.charCodeAt(0),
+ 'a'.charCodeAt(0),
+ 'l'.charCodeAt(0),
+ 'l'.charCodeAt(0),
+ 'o'.charCodeAt(0),
+]);
+
+describe('ByteString does', () => {
+ it('create bytestring from buffer', () => {
+ const byteString =
+ ByteString.fromArrayBuffer(arrayBufferSlice(TEST_BYTES, 0));
+ expect(byteString.toArrayBuffer()).toEqual(TEST_BYTES);
+ expect(byteString.toUint8ArrayUnsafe()).toEqual(new Uint8Array(TEST_BYTES));
+ });
+
+ it('create bytestring from ArrayBufferView', () => {
+ const byteString =
+ ByteString.fromArrayBufferView(new Uint8Array(TEST_BYTES));
+ expect(byteString.toArrayBuffer()).toEqual(TEST_BYTES);
+ expect(byteString.toUint8ArrayUnsafe()).toEqual(new Uint8Array(TEST_BYTES));
+ });
+
+ it('create bytestring from subarray', () => {
+ const byteString = ByteString.fromArrayBufferView(
+ new Uint8Array(TEST_BYTES, /* offset */ 1, /* length */ 2));
+ const expected = new Uint8Array([2, 3]);
+ expect(new Uint8Array(byteString.toArrayBuffer())).toEqual(expected);
+ expect(byteString.toUint8ArrayUnsafe()).toEqual(expected);
+ });
+
+ it('create bytestring from Uint8Array (unsafe)', () => {
+ const array = new Uint8Array(TEST_BYTES);
+ const byteString = ByteString.fromUint8ArrayUnsafe(array);
+ expect(byteString.toArrayBuffer()).toEqual(array.buffer);
+ expect(byteString.toUint8ArrayUnsafe()).toBe(array);
+ });
+
+ it('create bytestring from base64 string', () => {
+ const byteString = ByteString.fromBase64String(HALLO_IN_BASE64);
+ expect(byteString.toBase64String()).toEqual(HALLO_IN_BASE64);
+ expect(byteString.toArrayBuffer()).toEqual(BYTES_WITH_HALLO.buffer);
+ expect(byteString.toUint8ArrayUnsafe()).toEqual(BYTES_WITH_HALLO);
+ });
+
+ it('preserve immutability if underlying buffer changes: from buffer', () => {
+ const buffer = new ArrayBuffer(4);
+ const array = new Uint8Array(buffer);
+ array[0] = 1;
+ array[1] = 2;
+ array[2] = 3;
+ array[3] = 4;
+
+ const byteString = ByteString.fromArrayBuffer(buffer);
+ const otherBuffer = byteString.toArrayBuffer();
+
+ expect(otherBuffer).not.toBe(buffer);
+ expect(new Uint8Array(otherBuffer)).toEqual(array);
+
+ // modify the original buffer
+ array[0] = 5;
+ // Are we still returning the original bytes?
+ expect(new Uint8Array(byteString.toArrayBuffer())).toEqual(new Uint8Array([
+ 1, 2, 3, 4
+ ]));
+ });
+
+ it('preserve immutability if underlying buffer changes: from ArrayBufferView',
+ () => {
+ const buffer = new ArrayBuffer(4);
+ const array = new Uint8Array(buffer);
+ array[0] = 1;
+ array[1] = 2;
+ array[2] = 3;
+ array[3] = 4;
+
+ const byteString = ByteString.fromArrayBufferView(array);
+ const otherBuffer = byteString.toArrayBuffer();
+
+ expect(otherBuffer).not.toBe(buffer);
+ expect(new Uint8Array(otherBuffer)).toEqual(array);
+
+ // modify the original buffer
+ array[0] = 5;
+ // Are we still returning the original bytes?
+ expect(new Uint8Array(byteString.toArrayBuffer()))
+ .toEqual(new Uint8Array([1, 2, 3, 4]));
+ });
+
+ it('mutate if underlying buffer changes: from Uint8Array (unsafe)', () => {
+ const buffer = new ArrayBuffer(4);
+ const array = new Uint8Array(buffer);
+ array[0] = 1;
+ array[1] = 2;
+ array[2] = 3;
+ array[3] = 4;
+
+ const byteString = ByteString.fromUint8ArrayUnsafe(array);
+ const otherBuffer = byteString.toArrayBuffer();
+
+ expect(otherBuffer).not.toBe(buffer);
+ expect(new Uint8Array(otherBuffer)).toEqual(array);
+
+ // modify the original buffer
+ array[0] = 5;
+ // We are no longer returning the original bytes
+ expect(new Uint8Array(byteString.toArrayBuffer())).toEqual(new Uint8Array([
+ 5, 2, 3, 4
+ ]));
+ });
+
+ it('preserve immutability for returned buffers: toArrayBuffer', () => {
+ const byteString = ByteString.fromArrayBufferView(new Uint8Array(4));
+ const buffer1 = byteString.toArrayBuffer();
+ const buffer2 = byteString.toArrayBuffer();
+
+ expect(buffer1).toEqual(buffer2);
+
+ const array1 = new Uint8Array(buffer1);
+ array1[0] = 1;
+
+ expect(buffer1).not.toEqual(buffer2);
+ });
+
+ it('does not preserve immutability for returned buffers: toUint8ArrayUnsafe',
+ () => {
+ const byteString = ByteString.fromUint8ArrayUnsafe(new Uint8Array(4));
+ const array1 = byteString.toUint8ArrayUnsafe();
+ const array2 = byteString.toUint8ArrayUnsafe();
+
+ expect(array1).toEqual(array2);
+ array1[0] = 1;
+
+ expect(array1).toEqual(array2);
+ });
+
+ it('throws when created with null ArrayBufferView', () => {
+ expect(
+ () => ByteString.fromArrayBufferView(
+ /** @type {!ArrayBufferView} */ (/** @type{*} */ (null))))
+ .toThrow();
+ });
+
+ it('throws when created with null buffer', () => {
+ expect(
+ () => ByteString.fromBase64String(
+ /** @type {string} */ (/** @type{*} */ (null))))
+ .toThrow();
+ });
+
+ it('convert base64 to ArrayBuffer', () => {
+ const other = ByteString.fromBase64String(HALLO_IN_BASE64);
+ expect(BYTES_WITH_HALLO).toEqual(new Uint8Array(other.toArrayBuffer()));
+ });
+
+ it('convert base64 with spaces to ArrayBuffer', () => {
+ const other = ByteString.fromBase64String(HALLO_IN_BASE64_WITH_SPACES);
+ expect(new Uint8Array(other.toArrayBuffer())).toEqual(BYTES_WITH_HALLO);
+ });
+
+ it('convert bytes to base64', () => {
+ const other = ByteString.fromArrayBufferView(BYTES_WITH_HALLO);
+ expect(HALLO_IN_BASE64).toEqual(other.toBase64String());
+ });
+
+ it('equal empty bytetring', () => {
+ const empty = ByteString.fromArrayBuffer(new ArrayBuffer(0));
+ expect(ByteString.EMPTY.equals(empty)).toEqual(true);
+ });
+
+ it('equal empty bytestring constructed from ArrayBufferView', () => {
+ const empty = ByteString.fromArrayBufferView(new Uint8Array(0));
+ expect(ByteString.EMPTY.equals(empty)).toEqual(true);
+ });
+
+ it('equal empty bytestring constructed from Uint8Array (unsafe)', () => {
+ const empty = ByteString.fromUint8ArrayUnsafe(new Uint8Array(0));
+ expect(ByteString.EMPTY.equals(empty)).toEqual(true);
+ });
+
+ it('equal empty bytestring constructed from base64', () => {
+ const empty = ByteString.fromBase64String('');
+ expect(ByteString.EMPTY.equals(empty)).toEqual(true);
+ });
+
+ it('equal other instance', () => {
+ const other = ByteString.fromArrayBuffer(arrayBufferSlice(TEST_BYTES, 0));
+ expect(TEST_STRING.equals(other)).toEqual(true);
+ });
+
+ it('not equal different instance', () => {
+ const other =
+ ByteString.fromArrayBuffer(new Uint8Array([1, 2, 3, 4, 5]).buffer);
+ expect(TEST_STRING.equals(other)).toEqual(false);
+ });
+
+ it('equal other instance constructed from ArrayBufferView', () => {
+ const other =
+ ByteString.fromArrayBufferView(new Uint8Array(PREFIXED_TEST_BYTES, 1));
+ expect(TEST_STRING.equals(other)).toEqual(true);
+ });
+
+ it('not equal different instance constructed from ArrayBufferView', () => {
+ const other =
+ ByteString.fromArrayBufferView(new Uint8Array([1, 2, 3, 4, 5]));
+ expect(TEST_STRING.equals(other)).toEqual(false);
+ });
+
+ it('equal other instance constructed from Uint8Array (unsafe)', () => {
+ const other =
+ ByteString.fromUint8ArrayUnsafe(new Uint8Array(PREFIXED_TEST_BYTES, 1));
+ expect(TEST_STRING.equals(other)).toEqual(true);
+ });
+
+ it('not equal different instance constructed from Uint8Array (unsafe)',
+ () => {
+ const other =
+ ByteString.fromUint8ArrayUnsafe(new Uint8Array([1, 2, 3, 4, 5]));
+ expect(TEST_STRING.equals(other)).toEqual(false);
+ });
+
+ it('have same hashcode for empty bytes', () => {
+ const empty = ByteString.fromArrayBuffer(new ArrayBuffer(0));
+ expect(ByteString.EMPTY.hashCode()).toEqual(empty.hashCode());
+ });
+
+ it('have same hashcode for test bytes', () => {
+ const other = ByteString.fromArrayBuffer(arrayBufferSlice(TEST_BYTES, 0));
+ expect(TEST_STRING.hashCode()).toEqual(other.hashCode());
+ });
+
+ it('have same hashcode for test bytes', () => {
+ const other = ByteString.fromArrayBufferView(
+ new Uint8Array(arrayBufferSlice(TEST_BYTES, 0)));
+ expect(TEST_STRING.hashCode()).toEqual(other.hashCode());
+ });
+
+ it('have same hashcode for different instance constructed with base64',
+ () => {
+ const other = ByteString.fromBase64String(HALLO_IN_BASE64);
+ expect(ByteString.fromArrayBufferView(BYTES_WITH_HALLO).hashCode())
+ .toEqual(other.hashCode());
+ });
+
+ it('preserves the length of a Uint8Array', () => {
+ const original = new Uint8Array([105, 183, 51, 251, 253, 118, 247]);
+ const afterByteString = new Uint8Array(
+ ByteString.fromArrayBufferView(original).toArrayBuffer());
+ expect(afterByteString).toEqual(original);
+ });
+
+ it('preserves the length of a base64 value', () => {
+ const expected = new Uint8Array([105, 183, 51, 251, 253, 118, 247]);
+ const afterByteString = new Uint8Array(
+ ByteString.fromBase64String('abcz+/129w').toArrayBuffer());
+ expect(afterByteString).toEqual(expected);
+ });
+
+ it('preserves the length of a base64 value with padding', () => {
+ const expected = new Uint8Array([105, 183, 51, 251, 253, 118, 247]);
+ const afterByteString = new Uint8Array(
+ ByteString.fromBase64String('abcz+/129w==').toArrayBuffer());
+ expect(afterByteString).toEqual(expected);
+ });
+});
diff --git a/js/experimental/runtime/int64.js b/js/experimental/runtime/int64.js
new file mode 100644
index 0000000..45585b7
--- /dev/null
+++ b/js/experimental/runtime/int64.js
@@ -0,0 +1,403 @@
+/**
+ * @fileoverview Protobufs Int64 representation.
+ */
+goog.module('protobuf.Int64');
+
+const Long = goog.require('goog.math.Long');
+const {assert} = goog.require('goog.asserts');
+
+/**
+ * A container for protobufs Int64/Uint64 data type.
+ * @final
+ */
+class Int64 {
+ /** @return {!Int64} */
+ static getZero() {
+ return ZERO;
+ }
+
+ /** @return {!Int64} */
+ static getMinValue() {
+ return MIN_VALUE;
+ }
+
+ /** @return {!Int64} */
+ static getMaxValue() {
+ return MAX_VALUE;
+ }
+
+ /**
+ * Constructs a Int64 given two 32 bit numbers
+ * @param {number} lowBits
+ * @param {number} highBits
+ * @return {!Int64}
+ */
+ static fromBits(lowBits, highBits) {
+ return new Int64(lowBits, highBits);
+ }
+
+ /**
+ * Constructs an Int64 from a signed 32 bit number.
+ * @param {number} value
+ * @return {!Int64}
+ */
+ static fromInt(value) {
+ // TODO: Use our own checking system here.
+ assert(value === (value | 0), 'value should be a 32-bit integer');
+ // Right shift 31 bits so all high bits are equal to the sign bit.
+ // Note: cannot use >> 32, because (1 >> 32) = 1 (!).
+ const signExtendedHighBits = value >> 31;
+ return new Int64(value, signExtendedHighBits);
+ }
+
+ /**
+ * Constructs an Int64 from a number (over 32 bits).
+ * @param {number} value
+ * @return {!Int64}
+ */
+ static fromNumber(value) {
+ if (value > 0) {
+ return new Int64(value, value / TWO_PWR_32_DBL);
+ } else if (value < 0) {
+ return negate(-value, -value / TWO_PWR_32_DBL);
+ }
+ return ZERO;
+ }
+
+ /**
+ * Construct an Int64 from a signed decimal string.
+ * @param {string} value
+ * @return {!Int64}
+ */
+ static fromDecimalString(value) {
+ // TODO: Use our own checking system here.
+ assert(value.length > 0);
+ // The basic Number conversion loses precision, but we can use it for
+ // a quick validation that the format is correct and it is an integer.
+ assert(Math.floor(Number(value)).toString().length == value.length);
+ return decimalStringToInt64(value);
+ }
+
+ /**
+ * Construct an Int64 from a signed hexadecimal string.
+ * @param {string} value
+ * @return {!Int64}
+ */
+ static fromHexString(value) {
+ // TODO: Use our own checking system here.
+ assert(value.length > 0);
+ assert(value.slice(0, 2) == '0x' || value.slice(0, 3) == '-0x');
+ const minus = value[0] === '-';
+ // Strip the 0x or -0x prefix.
+ value = value.slice(minus ? 3 : 2);
+ const lowBits = parseInt(value.slice(-8), 16);
+ const highBits = parseInt(value.slice(-16, -8) || '', 16);
+ return (minus ? negate : Int64.fromBits)(lowBits, highBits);
+ }
+
+ // Note to the reader:
+ // goog.math.Long suffers from a code size issue. JsCompiler almost always
+ // considers toString methods to be alive in a program. So if you are
+ // constructing a Long instance the toString method is assumed to be live.
+ // Unfortunately Long's toString method makes a large chunk of code alive
+ // of the entire class adding 1.3kB (gzip) of extra code size.
+ // Callers that are sensitive to code size and are not using Long already
+ // should avoid calling this method.
+ /**
+ * Creates an Int64 instance from a Long value.
+ * @param {!Long} value
+ * @return {!Int64}
+ */
+ static fromLong(value) {
+ return new Int64(value.getLowBits(), value.getHighBits());
+ }
+
+ /**
+ * @param {number} lowBits
+ * @param {number} highBits
+ * @private
+ */
+ constructor(lowBits, highBits) {
+ /** @const @private {number} */
+ this.lowBits_ = lowBits | 0;
+ /** @const @private {number} */
+ this.highBits_ = highBits | 0;
+ }
+
+ /**
+ * Returns the int64 value as a JavaScript number. This will lose precision
+ * if the number is outside of the safe range for JavaScript of 53 bits
+ * precision.
+ * @return {number}
+ */
+ asNumber() {
+ const result = this.highBits_ * TWO_PWR_32_DBL + this.getLowBitsUnsigned();
+ // TODO: Use our own checking system here.
+ assert(
+ Number.isSafeInteger(result), 'conversion to number loses precision.');
+ return result;
+ }
+
+ // Note to the reader:
+ // goog.math.Long suffers from a code size issue. JsCompiler almost always
+ // considers toString methods to be alive in a program. So if you are
+ // constructing a Long instance the toString method is assumed to be live.
+ // Unfortunately Long's toString method makes a large chunk of code alive
+ // of the entire class adding 1.3kB (gzip) of extra code size.
+ // Callers that are sensitive to code size and are not using Long already
+ // should avoid calling this method.
+ /** @return {!Long} */
+ asLong() {
+ return Long.fromBits(this.lowBits_, this.highBits_);
+ }
+
+ /** @return {number} Signed 32-bit integer value. */
+ getLowBits() {
+ return this.lowBits_;
+ }
+
+ /** @return {number} Signed 32-bit integer value. */
+ getHighBits() {
+ return this.highBits_;
+ }
+
+ /** @return {number} Unsigned 32-bit integer. */
+ getLowBitsUnsigned() {
+ return this.lowBits_ >>> 0;
+ }
+
+ /** @return {number} Unsigned 32-bit integer. */
+ getHighBitsUnsigned() {
+ return this.highBits_ >>> 0;
+ }
+
+ /** @return {string} */
+ toSignedDecimalString() {
+ return joinSignedDecimalString(this);
+ }
+
+ /** @return {string} */
+ toUnsignedDecimalString() {
+ return joinUnsignedDecimalString(this);
+ }
+
+ /**
+ * Returns an unsigned hexadecimal string representation of the Int64.
+ * @return {string}
+ */
+ toHexString() {
+ let nibbles = new Array(16);
+ let lowBits = this.lowBits_;
+ let highBits = this.highBits_;
+ for (let highIndex = 7, lowIndex = 15; lowIndex > 7;
+ highIndex--, lowIndex--) {
+ nibbles[highIndex] = HEX_DIGITS[highBits & 0xF];
+ nibbles[lowIndex] = HEX_DIGITS[lowBits & 0xF];
+ highBits = highBits >>> 4;
+ lowBits = lowBits >>> 4;
+ }
+ // Always leave the least significant hex digit.
+ while (nibbles.length > 1 && nibbles[0] == '0') {
+ nibbles.shift();
+ }
+ return `0x${nibbles.join('')}`;
+ }
+
+ /**
+ * @param {*} other object to compare against.
+ * @return {boolean} Whether this Int64 equals the other.
+ */
+ equals(other) {
+ if (this === other) {
+ return true;
+ }
+ if (!(other instanceof Int64)) {
+ return false;
+ }
+ // Compare low parts first as there is higher chance they are different.
+ const otherInt64 = /** @type{!Int64} */ (other);
+ return (this.lowBits_ === otherInt64.lowBits_) &&
+ (this.highBits_ === otherInt64.highBits_);
+ }
+
+ /**
+ * Returns a number (int32) that is suitable for using in hashed structures.
+ * @return {number}
+ */
+ hashCode() {
+ return (31 * this.lowBits_ + 17 * this.highBits_) | 0;
+ }
+}
+
+/**
+ * Losslessly converts a 64-bit unsigned integer in 32:32 split representation
+ * into a decimal string.
+ * @param {!Int64} int64
+ * @return {string} The binary number represented as a string.
+ */
+const joinUnsignedDecimalString = (int64) => {
+ const lowBits = int64.getLowBitsUnsigned();
+ const highBits = int64.getHighBitsUnsigned();
+ // Skip the expensive conversion if the number is small enough to use the
+ // built-in conversions.
+ // Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with
+ // highBits <= 0x1FFFFF can be safely expressed with a double and retain
+ // integer precision.
+ // Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.
+ if (highBits <= 0x1FFFFF) {
+ return String(TWO_PWR_32_DBL * highBits + lowBits);
+ }
+
+ // What this code is doing is essentially converting the input number from
+ // base-2 to base-1e7, which allows us to represent the 64-bit range with
+ // only 3 (very large) digits. Those digits are then trivial to convert to
+ // a base-10 string.
+
+ // The magic numbers used here are -
+ // 2^24 = 16777216 = (1,6777216) in base-1e7.
+ // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
+
+ // Split 32:32 representation into 16:24:24 representation so our
+ // intermediate digits don't overflow.
+ const low = lowBits & LOW_24_BITS;
+ const mid = ((lowBits >>> 24) | (highBits << 8)) & LOW_24_BITS;
+ const high = (highBits >> 16) & LOW_16_BITS;
+
+ // Assemble our three base-1e7 digits, ignoring carries. The maximum
+ // value in a digit at this step is representable as a 48-bit integer, which
+ // can be stored in a 64-bit floating point number.
+ let digitA = low + (mid * 6777216) + (high * 6710656);
+ let digitB = mid + (high * 8147497);
+ let digitC = (high * 2);
+
+ // Apply carries from A to B and from B to C.
+ const base = 10000000;
+ if (digitA >= base) {
+ digitB += Math.floor(digitA / base);
+ digitA %= base;
+ }
+
+ if (digitB >= base) {
+ digitC += Math.floor(digitB / base);
+ digitB %= base;
+ }
+
+ // If digitC is 0, then we should have returned in the trivial code path
+ // at the top for non-safe integers. Given this, we can assume both digitB
+ // and digitA need leading zeros.
+ // TODO: Use our own checking system here.
+ assert(digitC);
+ return digitC + decimalFrom1e7WithLeadingZeros(digitB) +
+ decimalFrom1e7WithLeadingZeros(digitA);
+};
+
+/**
+ * @param {number} digit1e7 Number < 1e7
+ * @return {string} Decimal representation of digit1e7 with leading zeros.
+ */
+const decimalFrom1e7WithLeadingZeros = (digit1e7) => {
+ const partial = String(digit1e7);
+ return '0000000'.slice(partial.length) + partial;
+};
+
+/**
+ * Losslessly converts a 64-bit signed integer in 32:32 split representation
+ * into a decimal string.
+ * @param {!Int64} int64
+ * @return {string} The binary number represented as a string.
+ */
+const joinSignedDecimalString = (int64) => {
+ // If we're treating the input as a signed value and the high bit is set, do
+ // a manual two's complement conversion before the decimal conversion.
+ const negative = (int64.getHighBits() & 0x80000000);
+ if (negative) {
+ int64 = negate(int64.getLowBits(), int64.getHighBits());
+ }
+
+ const result = joinUnsignedDecimalString(int64);
+ return negative ? '-' + result : result;
+};
+
+/**
+ * @param {string} dec
+ * @return {!Int64}
+ */
+const decimalStringToInt64 = (dec) => {
+ // Check for minus sign.
+ const minus = dec[0] === '-';
+ if (minus) {
+ dec = dec.slice(1);
+ }
+
+ // Work 6 decimal digits at a time, acting like we're converting base 1e6
+ // digits to binary. This is safe to do with floating point math because
+ // Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
+ const base = 1e6;
+ let lowBits = 0;
+ let highBits = 0;
+ function add1e6digit(begin, end = undefined) {
+ // Note: Number('') is 0.
+ const digit1e6 = Number(dec.slice(begin, end));
+ highBits *= base;
+ lowBits = lowBits * base + digit1e6;
+ // Carry bits from lowBits to
+ if (lowBits >= TWO_PWR_32_DBL) {
+ highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);
+ lowBits = lowBits % TWO_PWR_32_DBL;
+ }
+ }
+ add1e6digit(-24, -18);
+ add1e6digit(-18, -12);
+ add1e6digit(-12, -6);
+ add1e6digit(-6);
+
+ return (minus ? negate : Int64.fromBits)(lowBits, highBits);
+};
+
+/**
+ * @param {number} lowBits
+ * @param {number} highBits
+ * @return {!Int64} Two's compliment negation of input.
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers
+ */
+const negate = (lowBits, highBits) => {
+ highBits = ~highBits;
+ if (lowBits) {
+ lowBits = ~lowBits + 1;
+ } else {
+ // If lowBits is 0, then bitwise-not is 0xFFFFFFFF,
+ // adding 1 to that, results in 0x100000000, which leaves
+ // the low bits 0x0 and simply adds one to the high bits.
+ highBits += 1;
+ }
+ return Int64.fromBits(lowBits, highBits);
+};
+
+/** @const {!Int64} */
+const ZERO = new Int64(0, 0);
+
+/** @const @private {number} */
+const LOW_16_BITS = 0xFFFF;
+
+/** @const @private {number} */
+const LOW_24_BITS = 0xFFFFFF;
+
+/** @const @private {number} */
+const LOW_31_BITS = 0x7FFFFFFF;
+
+/** @const @private {number} */
+const ALL_32_BITS = 0xFFFFFFFF;
+
+/** @const {!Int64} */
+const MAX_VALUE = Int64.fromBits(ALL_32_BITS, LOW_31_BITS);
+
+/** @const {!Int64} */
+const MIN_VALUE = Int64.fromBits(0, 0x80000000);
+
+/** @const {number} */
+const TWO_PWR_32_DBL = 0x100000000;
+
+/** @const {string} */
+const HEX_DIGITS = '0123456789abcdef';
+
+exports = Int64;
diff --git a/js/experimental/runtime/int64_test.js b/js/experimental/runtime/int64_test.js
new file mode 100644
index 0000000..76af14e
--- /dev/null
+++ b/js/experimental/runtime/int64_test.js
@@ -0,0 +1,213 @@
+/**
+ * @fileoverview Tests for Int64.
+ */
+goog.module('protobuf.Int64Test');
+goog.setTestOnly();
+
+const Int64 = goog.require('protobuf.Int64');
+const Long = goog.require('goog.math.Long');
+
+describe('Int64', () => {
+ it('can be constructed from bits', () => {
+ const int64 = Int64.fromBits(0, 1);
+ expect(int64.getLowBits()).toEqual(0);
+ expect(int64.getHighBits()).toEqual(1);
+ });
+
+ it('zero is defined', () => {
+ const int64 = Int64.getZero();
+ expect(int64.getLowBits()).toEqual(0);
+ expect(int64.getHighBits()).toEqual(0);
+ });
+
+ it('max value is defined', () => {
+ const int64 = Int64.getMaxValue();
+ expect(int64).toEqual(Int64.fromBits(0xFFFFFFFF, 0x7FFFFFFF));
+ expect(int64.asLong()).toEqual(Long.getMaxValue());
+ });
+
+ it('min value is defined', () => {
+ const int64 = Int64.getMinValue();
+ expect(int64).toEqual(Int64.fromBits(0, 0x80000000));
+ expect(int64.asLong()).toEqual(Long.getMinValue());
+ });
+
+ it('Can be converted to long', () => {
+ const int64 = Int64.fromInt(1);
+ expect(int64.asLong()).toEqual(Long.fromInt(1));
+ });
+
+ it('Negative value can be converted to long', () => {
+ const int64 = Int64.fromInt(-1);
+ expect(int64.getLowBits()).toEqual(0xFFFFFFFF | 0);
+ expect(int64.getHighBits()).toEqual(0xFFFFFFFF | 0);
+ expect(int64.asLong()).toEqual(Long.fromInt(-1));
+ });
+
+ it('Can be converted to number', () => {
+ const int64 = Int64.fromInt(1);
+ expect(int64.asNumber()).toEqual(1);
+ });
+
+ it('Can convert negative value to number', () => {
+ const int64 = Int64.fromInt(-1);
+ expect(int64.asNumber()).toEqual(-1);
+ });
+
+ it('MAX_SAFE_INTEGER can be used.', () => {
+ const int64 = Int64.fromNumber(Number.MAX_SAFE_INTEGER);
+ expect(int64.getLowBitsUnsigned()).toEqual(0xFFFFFFFF);
+ expect(int64.getHighBits()).toEqual(0x1FFFFF);
+ expect(int64.asNumber()).toEqual(Number.MAX_SAFE_INTEGER);
+ });
+
+ it('MIN_SAFE_INTEGER can be used.', () => {
+ const int64 = Int64.fromNumber(Number.MIN_SAFE_INTEGER);
+ expect(int64.asNumber()).toEqual(Number.MIN_SAFE_INTEGER);
+ });
+
+ it('constructs fromInt', () => {
+ const int64 = Int64.fromInt(1);
+ expect(int64.getLowBits()).toEqual(1);
+ expect(int64.getHighBits()).toEqual(0);
+ });
+
+ it('constructs fromLong', () => {
+ const int64 = Int64.fromLong(Long.fromInt(1));
+ expect(int64.getLowBits()).toEqual(1);
+ expect(int64.getHighBits()).toEqual(0);
+ });
+
+ // TODO: Use our own checking system here.
+ if (goog.DEBUG) {
+ it('asNumber throws for MAX_SAFE_INTEGER + 1', () => {
+ expect(() => Int64.fromNumber(Number.MAX_SAFE_INTEGER + 1).asNumber())
+ .toThrow();
+ });
+
+ it('fromInt(MAX_SAFE_INTEGER) throws', () => {
+ expect(() => Int64.fromInt(Number.MAX_SAFE_INTEGER)).toThrow();
+ });
+
+ it('fromInt(1.5) throws', () => {
+ expect(() => Int64.fromInt(1.5)).toThrow();
+ });
+ }
+
+ const decimalHexPairs = {
+ '0x0000000000000000': {signed: '0'},
+ '0x0000000000000001': {signed: '1'},
+ '0x00000000ffffffff': {signed: '4294967295'},
+ '0x0000000100000000': {signed: '4294967296'},
+ '0xffffffffffffffff': {signed: '-1', unsigned: '18446744073709551615'},
+ '0x8000000000000000':
+ {signed: '-9223372036854775808', unsigned: '9223372036854775808'},
+ '0x8000000080000000':
+ {signed: '-9223372034707292160', unsigned: '9223372039002259456'},
+ '0x01b69b4bacd05f15': {signed: '123456789123456789'},
+ '0xfe4964b4532fa0eb':
+ {signed: '-123456789123456789', unsigned: '18323287284586094827'},
+ '0xa5a5a5a5a5a5a5a5':
+ {signed: '-6510615555426900571', unsigned: '11936128518282651045'},
+ '0x5a5a5a5a5a5a5a5a': {signed: '6510615555426900570'},
+ '0xffffffff00000000':
+ {signed: '-4294967296', unsigned: '18446744069414584320'},
+ };
+
+ it('serializes to signed decimal strings', () => {
+ for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
+ const int64 = hexToInt64(hex);
+ expect(int64.toSignedDecimalString()).toEqual(decimals.signed);
+ }
+ });
+
+ it('serializes to unsigned decimal strings', () => {
+ for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
+ const int64 = hexToInt64(hex);
+ expect(int64.toUnsignedDecimalString())
+ .toEqual(decimals.unsigned || decimals.signed);
+ }
+ });
+
+ it('serializes to unsigned hex strings', () => {
+ for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
+ const int64 = hexToInt64(hex);
+ let shortHex = hex.replace(/0x0*/, '0x');
+ if (shortHex == '0x') {
+ shortHex = '0x0';
+ }
+ expect(int64.toHexString()).toEqual(shortHex);
+ }
+ });
+
+ it('parses decimal strings', () => {
+ for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
+ const signed = Int64.fromDecimalString(decimals.signed);
+ expect(int64ToHex(signed)).toEqual(hex);
+ if (decimals.unsigned) {
+ const unsigned = Int64.fromDecimalString(decimals.unsigned);
+ expect(int64ToHex(unsigned)).toEqual(hex);
+ }
+ }
+ });
+
+ it('parses hex strings', () => {
+ for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
+ expect(int64ToHex(Int64.fromHexString(hex))).toEqual(hex);
+ }
+ expect(int64ToHex(Int64.fromHexString('-0x1')))
+ .toEqual('0xffffffffffffffff');
+ });
+
+ // TODO: Use our own checking system here.
+ if (goog.DEBUG) {
+ it('throws when parsing empty string', () => {
+ expect(() => Int64.fromDecimalString('')).toThrow();
+ });
+
+ it('throws when parsing float string', () => {
+ expect(() => Int64.fromDecimalString('1.5')).toThrow();
+ });
+
+ it('throws when parsing non-numeric string', () => {
+ expect(() => Int64.fromDecimalString('0xa')).toThrow();
+ });
+ }
+
+ it('checks if equal', () => {
+ const low = Int64.fromInt(1);
+ const high = Int64.getMaxValue();
+ expect(low.equals(Int64.fromInt(1))).toEqual(true);
+ expect(low.equals(high)).toEqual(false);
+ expect(high.equals(Int64.getMaxValue())).toEqual(true);
+ });
+
+ it('returns unique hashcode', () => {
+ expect(Int64.fromInt(1).hashCode()).toEqual(Int64.fromInt(1).hashCode());
+ expect(Int64.fromInt(1).hashCode())
+ .not.toEqual(Int64.fromInt(2).hashCode());
+ });
+});
+
+/**
+ * @param {string} hexString
+ * @return {!Int64}
+ */
+function hexToInt64(hexString) {
+ const high = hexString.slice(2, 10);
+ const low = hexString.slice(10);
+ return Int64.fromBits(parseInt(low, 16), parseInt(high, 16));
+}
+
+/**
+ * @param {!Int64} int64
+ * @return {string}
+ */
+function int64ToHex(int64) {
+ const ZEROS_32_BIT = '00000000';
+ const highPartialHex = int64.getHighBitsUnsigned().toString(16);
+ const lowPartialHex = int64.getLowBitsUnsigned().toString(16);
+ const highHex = ZEROS_32_BIT.slice(highPartialHex.length) + highPartialHex;
+ const lowHex = ZEROS_32_BIT.slice(lowPartialHex.length) + lowPartialHex;
+ return `0x${highHex}${lowHex}`;
+}
diff --git a/js/experimental/runtime/internal/checks.js b/js/experimental/runtime/internal/checks.js
new file mode 100644
index 0000000..369c6af
--- /dev/null
+++ b/js/experimental/runtime/internal/checks.js
@@ -0,0 +1,708 @@
+/**
+ * @fileoverview Proto internal runtime checks.
+ *
+ * Checks are grouped into different severity, see:
+ * http://g3doc/javascript/protobuf/README.md#configurable-check-support-in-protocol-buffers
+ *
+ * Checks are also grouped into different sections:
+ * - CHECK_BOUNDS:
+ * Checks that ensure that indexed access is within bounds
+ * (e.g. an array being accessed past its size).
+ * - CHECK_STATE
+ * Checks related to the state of an object
+ * (e.g. a parser hitting an invalid case).
+ * - CHECK_TYPE:
+ * Checks that relate to type errors (e.g. code receives a number instead
+ * of a string).
+ */
+goog.module('protobuf.internal.checks');
+
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const WireType = goog.require('protobuf.binary.WireType');
+
+//
+// See
+// http://g3doc/javascript/protobuf/README.md#configurable-check-support-in-protocol-buffers
+//
+/** @define{string} */
+const CHECK_LEVEL_DEFINE = goog.define('protobuf.defines.CHECK_LEVEL', '');
+
+/** @define{boolean} */
+const POLYFILL_TEXT_ENCODING =
+ goog.define('protobuf.defines.POLYFILL_TEXT_ENCODING', true);
+
+/**
+ * @const {number}
+ */
+const MAX_FIELD_NUMBER = Math.pow(2, 29) - 1;
+
+/**
+ * The largest finite float32 value.
+ * @const {number}
+ */
+const FLOAT32_MAX = 3.4028234663852886e+38;
+
+/** @enum {number} */
+const CheckLevel = {
+ DEBUG: 0,
+ CRITICAL: 1,
+ OFF: 2
+};
+
+
+/** @return {!CheckLevel} */
+function calculateCheckLevel() {
+ const definedLevel = CHECK_LEVEL_DEFINE.toUpperCase();
+ if (definedLevel === '') {
+ // user did not set a value, value now just depends on goog.DEBUG
+ return goog.DEBUG ? CheckLevel.DEBUG : CheckLevel.CRITICAL;
+ }
+
+ if (definedLevel === 'CRITICAL') {
+ return CheckLevel.CRITICAL;
+ }
+
+ if (definedLevel === 'OFF') {
+ return CheckLevel.OFF;
+ }
+
+ if (definedLevel === 'DEBUG') {
+ return CheckLevel.DEBUG;
+ }
+
+ throw new Error(`Unknown value for CHECK_LEVEL: ${CHECK_LEVEL_DEFINE}`);
+}
+
+const /** !CheckLevel */ CHECK_LEVEL = calculateCheckLevel();
+
+const /** boolean */ CHECK_STATE = CHECK_LEVEL === CheckLevel.DEBUG;
+
+const /** boolean */ CHECK_CRITICAL_STATE =
+ CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG;
+
+const /** boolean */ CHECK_BOUNDS = CHECK_LEVEL === CheckLevel.DEBUG;
+
+const /** boolean */ CHECK_CRITICAL_BOUNDS =
+ CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG;
+
+const /** boolean */ CHECK_TYPE = CHECK_LEVEL === CheckLevel.DEBUG;
+
+const /** boolean */ CHECK_CRITICAL_TYPE =
+ CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG;
+
+/**
+ * Ensures the truth of an expression involving the state of the calling
+ * instance, but not involving any parameters to the calling method.
+ *
+ * For cases where failing fast is pretty important and not failing early could
+ * cause bugs that are much harder to debug.
+ * @param {boolean} state
+ * @param {string=} message
+ * @throws {!Error} If the state is false and the check state is critical.
+ */
+function checkCriticalState(state, message = '') {
+ if (!CHECK_CRITICAL_STATE) {
+ return;
+ }
+ if (!state) {
+ throw new Error(message);
+ }
+}
+
+/**
+ * Ensures the truth of an expression involving the state of the calling
+ * instance, but not involving any parameters to the calling method.
+ *
+ * @param {boolean} state
+ * @param {string=} message
+ * @throws {!Error} If the state is false and the check state is debug.
+ */
+function checkState(state, message = '') {
+ if (!CHECK_STATE) {
+ return;
+ }
+ checkCriticalState(state, message);
+}
+
+/**
+ * Ensures that `index` specifies a valid position in an indexable object of
+ * size `size`. A position index may range from zero to size, inclusive.
+ * @param {number} index
+ * @param {number} size
+ * @throws {!Error} If the index is out of range and the check state is debug.
+ */
+function checkPositionIndex(index, size) {
+ if (!CHECK_BOUNDS) {
+ return;
+ }
+ checkCriticalPositionIndex(index, size);
+}
+
+/**
+ * Ensures that `index` specifies a valid position in an indexable object of
+ * size `size`. A position index may range from zero to size, inclusive.
+ * @param {number} index
+ * @param {number} size
+ * @throws {!Error} If the index is out of range and the check state is
+ * critical.
+ */
+function checkCriticalPositionIndex(index, size) {
+ if (!CHECK_CRITICAL_BOUNDS) {
+ return;
+ }
+ if (index < 0 || index > size) {
+ throw new Error(`Index out of bounds: index: ${index} size: ${size}`);
+ }
+}
+
+/**
+ * Ensures that `index` specifies a valid element in an indexable object of
+ * size `size`. A element index may range from zero to size, exclusive.
+ * @param {number} index
+ * @param {number} size
+ * @throws {!Error} If the index is out of range and the check state is
+ * debug.
+ */
+function checkElementIndex(index, size) {
+ if (!CHECK_BOUNDS) {
+ return;
+ }
+ checkCriticalElementIndex(index, size);
+}
+
+/**
+ * Ensures that `index` specifies a valid element in an indexable object of
+ * size `size`. A element index may range from zero to size, exclusive.
+ * @param {number} index
+ * @param {number} size
+ * @throws {!Error} If the index is out of range and the check state is
+ * critical.
+ */
+function checkCriticalElementIndex(index, size) {
+ if (!CHECK_CRITICAL_BOUNDS) {
+ return;
+ }
+ if (index < 0 || index >= size) {
+ throw new Error(`Index out of bounds: index: ${index} size: ${size}`);
+ }
+}
+
+/**
+ * Ensures the range of [start, end) is with the range of [0, size).
+ * @param {number} start
+ * @param {number} end
+ * @param {number} size
+ * @throws {!Error} If start and end are out of range and the check state is
+ * debug.
+ */
+function checkRange(start, end, size) {
+ if (!CHECK_BOUNDS) {
+ return;
+ }
+ checkCriticalRange(start, end, size);
+}
+
+/**
+ * Ensures the range of [start, end) is with the range of [0, size).
+ * @param {number} start
+ * @param {number} end
+ * @param {number} size
+ * @throws {!Error} If start and end are out of range and the check state is
+ * critical.
+ */
+function checkCriticalRange(start, end, size) {
+ if (!CHECK_CRITICAL_BOUNDS) {
+ return;
+ }
+ if (start < 0 || end < 0 || start > size || end > size) {
+ throw new Error(`Range error: start: ${start} end: ${end} size: ${size}`);
+ }
+ if (start > end) {
+ throw new Error(`Start > end: ${start} > ${end}`);
+ }
+}
+
+/**
+ * Ensures that field number is an integer and within the range of
+ * [1, MAX_FIELD_NUMBER].
+ * @param {number} fieldNumber
+ * @throws {!Error} If the field number is out of range and the check state is
+ * debug.
+ */
+function checkFieldNumber(fieldNumber) {
+ if (!CHECK_TYPE) {
+ return;
+ }
+ checkCriticalFieldNumber(fieldNumber);
+}
+
+/**
+ * Ensures that the value is neither null nor undefined.
+ *
+ * @param {T} value
+ * @return {R}
+ *
+ * @template T
+ * @template R :=
+ * mapunion(T, (V) =>
+ * cond(eq(V, 'null'),
+ * none(),
+ * cond(eq(V, 'undefined'),
+ * none(),
+ * V)))
+ * =:
+ */
+function checkDefAndNotNull(value) {
+ if (CHECK_TYPE) {
+ // Note that undefined == null.
+ if (value == null) {
+ throw new Error(`Value can't be null`);
+ }
+ }
+ return value;
+}
+
+/**
+ * Ensures that the value exists and is a function.
+ *
+ * @param {function(?): ?} func
+ */
+function checkFunctionExists(func) {
+ if (CHECK_TYPE) {
+ if (typeof func !== 'function') {
+ throw new Error(`${func} is not a function`);
+ }
+ }
+}
+
+/**
+ * Ensures that field number is an integer and within the range of
+ * [1, MAX_FIELD_NUMBER].
+ * @param {number} fieldNumber
+ * @throws {!Error} If the field number is out of range and the check state is
+ * critical.
+ */
+function checkCriticalFieldNumber(fieldNumber) {
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ if (fieldNumber <= 0 || fieldNumber > MAX_FIELD_NUMBER) {
+ throw new Error(`Field number is out of range: ${fieldNumber}`);
+ }
+}
+
+/**
+ * Ensures that wire type is valid.
+ * @param {!WireType} wireType
+ * @throws {!Error} If the wire type is invalid and the check state is debug.
+ */
+function checkWireType(wireType) {
+ if (!CHECK_TYPE) {
+ return;
+ }
+ checkCriticalWireType(wireType);
+}
+
+/**
+ * Ensures that wire type is valid.
+ * @param {!WireType} wireType
+ * @throws {!Error} If the wire type is invalid and the check state is critical.
+ */
+function checkCriticalWireType(wireType) {
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ if (wireType < WireType.VARINT || wireType > WireType.FIXED32) {
+ throw new Error(`Invalid wire type: ${wireType}`);
+ }
+}
+
+/**
+ * Ensures the given value has the correct type.
+ * @param {boolean} expression
+ * @param {string} errorMsg
+ * @throws {!Error} If the value has the wrong type and the check state is
+ * critical.
+ */
+function checkCriticalType(expression, errorMsg) {
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ if (!expression) {
+ throw new Error(errorMsg);
+ }
+}
+
+/**
+ * Checks whether a given object is an array.
+ * @param {*} value
+ * @return {!Array<*>}
+ */
+function checkCriticalTypeArray(value) {
+ checkCriticalType(
+ Array.isArray(value), `Must be an array, but got: ${value}`);
+ return /** @type {!Array<*>} */ (value);
+}
+
+/**
+ * Checks whether a given object is an iterable.
+ * @param {*} value
+ * @return {!Iterable<*>}
+ */
+function checkCriticalTypeIterable(value) {
+ checkCriticalType(
+ !!value[Symbol.iterator], `Must be an iterable, but got: ${value}`);
+ return /** @type {!Iterable<*>} */ (value);
+}
+
+/**
+ * Checks whether a given object is a boolean.
+ * @param {*} value
+ */
+function checkCriticalTypeBool(value) {
+ checkCriticalType(
+ typeof value === 'boolean', `Must be a boolean, but got: ${value}`);
+}
+
+/**
+ * Checks whether a given object is an array of boolean.
+ * @param {*} values
+ */
+function checkCriticalTypeBoolArray(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalTypeBool(value);
+ }
+}
+
+/**
+ * Checks whether a given object is a ByteString.
+ * @param {*} value
+ */
+function checkCriticalTypeByteString(value) {
+ checkCriticalType(
+ value instanceof ByteString, `Must be a ByteString, but got: ${value}`);
+}
+
+/**
+ * Checks whether a given object is an array of ByteString.
+ * @param {*} values
+ */
+function checkCriticalTypeByteStringArray(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalTypeByteString(value);
+ }
+}
+
+/**
+ * Checks whether a given object is a number.
+ * @param {*} value
+ * @throws {!Error} If the value is not float and the check state is debug.
+ */
+function checkTypeDouble(value) {
+ if (!CHECK_TYPE) {
+ return;
+ }
+ checkCriticalTypeDouble(value);
+}
+
+/**
+ * Checks whether a given object is a number.
+ * @param {*} value
+ * @throws {!Error} If the value is not float and the check state is critical.
+ */
+function checkCriticalTypeDouble(value) {
+ checkCriticalType(
+ typeof value === 'number', `Must be a number, but got: ${value}`);
+}
+
+/**
+ * Checks whether a given object is an array of double.
+ * @param {*} values
+ */
+function checkCriticalTypeDoubleArray(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalTypeDouble(value);
+ }
+}
+
+/**
+ * Checks whether a given object is a number.
+ * @param {*} value
+ * @throws {!Error} If the value is not signed int32 and the check state is
+ * debug.
+ */
+function checkTypeSignedInt32(value) {
+ if (!CHECK_TYPE) {
+ return;
+ }
+ checkCriticalTypeSignedInt32(value);
+}
+
+/**
+ * Checks whether a given object is a number.
+ * @param {*} value
+ * @throws {!Error} If the value is not signed int32 and the check state is
+ * critical.
+ */
+function checkCriticalTypeSignedInt32(value) {
+ checkCriticalTypeDouble(value);
+ const valueAsNumber = /** @type {number} */ (value);
+ if (CHECK_CRITICAL_TYPE) {
+ if (valueAsNumber < -Math.pow(2, 31) || valueAsNumber > Math.pow(2, 31) ||
+ !Number.isInteger(valueAsNumber)) {
+ throw new Error(`Must be int32, but got: ${valueAsNumber}`);
+ }
+ }
+}
+
+/**
+ * Checks whether a given object is an array of numbers.
+ * @param {*} values
+ */
+function checkCriticalTypeSignedInt32Array(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalTypeSignedInt32(value);
+ }
+}
+
+/**
+ * Ensures that value is a long instance.
+ * @param {*} value
+ * @throws {!Error} If the value is not a long instance and check state is
+ * debug.
+ */
+function checkTypeSignedInt64(value) {
+ if (!CHECK_TYPE) {
+ return;
+ }
+ checkCriticalTypeSignedInt64(value);
+}
+
+/**
+ * Ensures that value is a long instance.
+ * @param {*} value
+ * @throws {!Error} If the value is not a long instance and check state is
+ * critical.
+ */
+function checkCriticalTypeSignedInt64(value) {
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ if (!(value instanceof Int64)) {
+ throw new Error(`Must be Int64 instance, but got: ${value}`);
+ }
+}
+
+/**
+ * Checks whether a given object is an array of long instances.
+ * @param {*} values
+ * @throws {!Error} If values is not an array of long instances.
+ */
+function checkCriticalTypeSignedInt64Array(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalTypeSignedInt64(value);
+ }
+}
+
+/**
+ * Checks whether a given object is a number and within float32 precision.
+ * @param {*} value
+ * @throws {!Error} If the value is not float and the check state is debug.
+ */
+function checkTypeFloat(value) {
+ if (!CHECK_TYPE) {
+ return;
+ }
+ checkCriticalTypeFloat(value);
+}
+
+/**
+ * Checks whether a given object is a number and within float32 precision.
+ * @param {*} value
+ * @throws {!Error} If the value is not float and the check state is critical.
+ */
+function checkCriticalTypeFloat(value) {
+ checkCriticalTypeDouble(value);
+ if (CHECK_CRITICAL_TYPE) {
+ const valueAsNumber = /** @type {number} */ (value);
+ if (Number.isFinite(valueAsNumber) &&
+ (valueAsNumber > FLOAT32_MAX || valueAsNumber < -FLOAT32_MAX)) {
+ throw new Error(
+ `Given number does not fit into float precision: ${value}`);
+ }
+ }
+}
+
+/**
+ * Checks whether a given object is an iterable of floats.
+ * @param {*} values
+ */
+function checkCriticalTypeFloatIterable(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const iterable = checkCriticalTypeIterable(values);
+ for (const value of iterable) {
+ checkCriticalTypeFloat(value);
+ }
+}
+
+/**
+ * Checks whether a given object is a string.
+ * @param {*} value
+ */
+function checkCriticalTypeString(value) {
+ checkCriticalType(
+ typeof value === 'string', `Must be string, but got: ${value}`);
+}
+
+/**
+ * Checks whether a given object is an array of string.
+ * @param {*} values
+ */
+function checkCriticalTypeStringArray(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalTypeString(value);
+ }
+}
+
+/**
+ * Ensures that value is a valid unsigned int32.
+ * @param {*} value
+ * @throws {!Error} If the value is out of range and the check state is debug.
+ */
+function checkTypeUnsignedInt32(value) {
+ if (!CHECK_TYPE) {
+ return;
+ }
+ checkCriticalTypeUnsignedInt32(value);
+}
+
+/**
+ * Ensures that value is a valid unsigned int32.
+ * @param {*} value
+ * @throws {!Error} If the value is out of range and the check state
+ * is critical.
+ */
+function checkCriticalTypeUnsignedInt32(value) {
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ checkCriticalTypeDouble(value);
+ const valueAsNumber = /** @type {number} */ (value);
+ if (valueAsNumber < 0 || valueAsNumber > Math.pow(2, 32) - 1 ||
+ !Number.isInteger(valueAsNumber)) {
+ throw new Error(`Must be uint32, but got: ${value}`);
+ }
+}
+
+/**
+ * Checks whether a given object is an array of unsigned int32.
+ * @param {*} values
+ */
+function checkCriticalTypeUnsignedInt32Array(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalTypeUnsignedInt32(value);
+ }
+}
+
+/**
+ * Checks whether a given object is an array of message.
+ * @param {*} values
+ */
+function checkCriticalTypeMessageArray(values) {
+ // TODO(b/134765672)
+ if (!CHECK_CRITICAL_TYPE) {
+ return;
+ }
+ const array = checkCriticalTypeArray(values);
+ for (const value of array) {
+ checkCriticalType(
+ value !== null, 'Given value is not a message instance: null');
+ }
+}
+
+exports = {
+ checkDefAndNotNull,
+ checkCriticalElementIndex,
+ checkCriticalFieldNumber,
+ checkCriticalPositionIndex,
+ checkCriticalRange,
+ checkCriticalState,
+ checkCriticalTypeBool,
+ checkCriticalTypeBoolArray,
+ checkCriticalTypeByteString,
+ checkCriticalTypeByteStringArray,
+ checkCriticalTypeDouble,
+ checkTypeDouble,
+ checkCriticalTypeDoubleArray,
+ checkTypeFloat,
+ checkCriticalTypeFloat,
+ checkCriticalTypeFloatIterable,
+ checkCriticalTypeMessageArray,
+ checkCriticalTypeSignedInt32,
+ checkCriticalTypeSignedInt32Array,
+ checkCriticalTypeSignedInt64,
+ checkTypeSignedInt64,
+ checkCriticalTypeSignedInt64Array,
+ checkCriticalTypeString,
+ checkCriticalTypeStringArray,
+ checkCriticalTypeUnsignedInt32,
+ checkCriticalTypeUnsignedInt32Array,
+ checkCriticalType,
+ checkCriticalWireType,
+ checkElementIndex,
+ checkFieldNumber,
+ checkFunctionExists,
+ checkPositionIndex,
+ checkRange,
+ checkState,
+ checkTypeUnsignedInt32,
+ checkTypeSignedInt32,
+ checkWireType,
+ CHECK_BOUNDS,
+ CHECK_CRITICAL_BOUNDS,
+ CHECK_STATE,
+ CHECK_CRITICAL_STATE,
+ CHECK_TYPE,
+ CHECK_CRITICAL_TYPE,
+ MAX_FIELD_NUMBER,
+ POLYFILL_TEXT_ENCODING,
+};
diff --git a/js/experimental/runtime/internal/checks_test.js b/js/experimental/runtime/internal/checks_test.js
new file mode 100644
index 0000000..50e857b
--- /dev/null
+++ b/js/experimental/runtime/internal/checks_test.js
@@ -0,0 +1,58 @@
+/**
+ * @fileoverview Tests for checks.js.
+ */
+goog.module('protobuf.internal.checksTest');
+
+const {CHECK_TYPE, checkDefAndNotNull, checkFunctionExists} = goog.require('protobuf.internal.checks');
+
+describe('checkDefAndNotNull', () => {
+ it('throws if undefined', () => {
+ let value;
+ if (CHECK_TYPE) {
+ expect(() => checkDefAndNotNull(value)).toThrow();
+ } else {
+ expect(checkDefAndNotNull(value)).toBeUndefined();
+ }
+ });
+
+ it('throws if null', () => {
+ const value = null;
+ if (CHECK_TYPE) {
+ expect(() => checkDefAndNotNull(value)).toThrow();
+ } else {
+ expect(checkDefAndNotNull(value)).toBeNull();
+ }
+ });
+
+ it('does not throw if empty string', () => {
+ const value = '';
+ expect(checkDefAndNotNull(value)).toEqual('');
+ });
+});
+
+describe('checkFunctionExists', () => {
+ it('throws if the function is undefined', () => {
+ let foo = /** @type {function()} */ (/** @type {*} */ (undefined));
+ if (CHECK_TYPE) {
+ expect(() => checkFunctionExists(foo)).toThrow();
+ } else {
+ checkFunctionExists(foo);
+ }
+ });
+
+ it('throws if the property is defined but not a function', () => {
+ let foo = /** @type {function()} */ (/** @type {*} */ (1));
+ if (CHECK_TYPE) {
+ expect(() => checkFunctionExists(foo)).toThrow();
+ } else {
+ checkFunctionExists(foo);
+ }
+ });
+
+ it('does not throw if the function is defined', () => {
+ function foo(x) {
+ return x;
+ }
+ checkFunctionExists(foo);
+ });
+});
\ No newline at end of file
diff --git a/js/experimental/runtime/kernel/binary_storage.js b/js/experimental/runtime/kernel/binary_storage.js
new file mode 100644
index 0000000..4cbde30
--- /dev/null
+++ b/js/experimental/runtime/kernel/binary_storage.js
@@ -0,0 +1,130 @@
+goog.module('protobuf.runtime.BinaryStorage');
+
+const Storage = goog.require('protobuf.runtime.Storage');
+const {checkDefAndNotNull} = goog.require('protobuf.internal.checks');
+
+/**
+ * Class storing all the fields of a binary protobuf message.
+ *
+ * @package
+ * @template FieldType
+ * @implements {Storage}
+ */
+class BinaryStorage {
+ /**
+ * @param {number=} pivot
+ */
+ constructor(pivot = Storage.DEFAULT_PIVOT) {
+ /**
+ * Fields having a field number no greater than the pivot value are stored
+ * into an array for fast access. A field with field number X is stored into
+ * the array position X - 1.
+ *
+ * @private @const {!Array<!FieldType|undefined>}
+ */
+ this.array_ = new Array(pivot);
+
+ /**
+ * Fields having a field number higher than the pivot value are stored into
+ * the map. We create the map only when it's needed, since even an empty map
+ * takes up a significant amount of memory.
+ *
+ * @private {?Map<number, !FieldType>}
+ */
+ this.map_ = null;
+ }
+
+ /**
+ * Fields having a field number no greater than the pivot value are stored
+ * into an array for fast access. A field with field number X is stored into
+ * the array position X - 1.
+ * @return {number}
+ * @override
+ */
+ getPivot() {
+ return this.array_.length;
+ }
+
+ /**
+ * Sets a field in the specified field number.
+ *
+ * @param {number} fieldNumber
+ * @param {!FieldType} field
+ * @override
+ */
+ set(fieldNumber, field) {
+ if (fieldNumber <= this.getPivot()) {
+ this.array_[fieldNumber - 1] = field;
+ } else {
+ if (this.map_) {
+ this.map_.set(fieldNumber, field);
+ } else {
+ this.map_ = new Map([[fieldNumber, field]]);
+ }
+ }
+ }
+
+ /**
+ * Returns a field at the specified field number.
+ *
+ * @param {number} fieldNumber
+ * @return {!FieldType|undefined}
+ * @override
+ */
+ get(fieldNumber) {
+ if (fieldNumber <= this.getPivot()) {
+ return this.array_[fieldNumber - 1];
+ } else {
+ return this.map_ ? this.map_.get(fieldNumber) : undefined;
+ }
+ }
+
+ /**
+ * Deletes a field from the specified field number.
+ *
+ * @param {number} fieldNumber
+ * @override
+ */
+ delete(fieldNumber) {
+ if (fieldNumber <= this.getPivot()) {
+ delete this.array_[fieldNumber - 1];
+ } else {
+ if (this.map_) {
+ this.map_.delete(fieldNumber);
+ }
+ }
+ }
+
+ /**
+ * Executes the provided function once for each field.
+ *
+ * @param {function(!FieldType, number): void} callback
+ * @override
+ */
+ forEach(callback) {
+ this.array_.forEach((field, fieldNumber) => {
+ if (field) {
+ callback(checkDefAndNotNull(field), fieldNumber + 1);
+ }
+ });
+ if (this.map_) {
+ this.map_.forEach(callback);
+ }
+ }
+
+ /**
+ * Creates a shallow copy of the storage.
+ *
+ * @return {!BinaryStorage}
+ * @override
+ */
+ shallowCopy() {
+ const copy = new BinaryStorage(this.getPivot());
+ this.forEach(
+ (field, fieldNumber) =>
+ void copy.set(fieldNumber, field.shallowCopy()));
+ return copy;
+ }
+}
+
+exports = BinaryStorage;
diff --git a/js/experimental/runtime/kernel/binary_storage_test.js b/js/experimental/runtime/kernel/binary_storage_test.js
new file mode 100644
index 0000000..2686f04
--- /dev/null
+++ b/js/experimental/runtime/kernel/binary_storage_test.js
@@ -0,0 +1,165 @@
+/**
+ * @fileoverview Tests for storage.js.
+ */
+goog.module('protobuf.runtime.BinaryStorageTest');
+
+goog.setTestOnly();
+
+const BinaryStorage = goog.require('protobuf.runtime.BinaryStorage');
+const {Field} = goog.require('protobuf.binary.field');
+
+/**
+ * @type {number}
+ */
+const DEFAULT_PIVOT = 24;
+
+const /** !Field */ field1 =
+ Field.fromDecodedValue(/* decodedValue= */ 1, /* encoder= */ () => {});
+const /** !Field */ field2 =
+ Field.fromDecodedValue(/* decodedValue= */ 2, /* encoder= */ () => {});
+const /** !Field */ field3 =
+ Field.fromDecodedValue(/* decodedValue= */ 3, /* encoder= */ () => {});
+const /** !Field */ field4 =
+ Field.fromDecodedValue(/* decodedValue= */ 4, /* encoder= */ () => {});
+
+/**
+ * Returns the number of fields stored.
+ *
+ * @param {!BinaryStorage} storage
+ * @return {number}
+ */
+function getStorageSize(storage) {
+ let size = 0;
+ storage.forEach(() => void size++);
+ return size;
+}
+
+describe('BinaryStorage', () => {
+ it('sets and gets a field not greater than the pivot', () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+
+ storage.set(1, field1);
+ storage.set(DEFAULT_PIVOT, field2);
+
+ expect(storage.getPivot()).toBe(DEFAULT_PIVOT);
+ expect(storage.get(1)).toBe(field1);
+ expect(storage.get(DEFAULT_PIVOT)).toBe(field2);
+ });
+
+ it('sets and gets a field greater than the pivot', () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+
+ storage.set(DEFAULT_PIVOT + 1, field1);
+ storage.set(100000, field2);
+
+ expect(storage.get(DEFAULT_PIVOT + 1)).toBe(field1);
+ expect(storage.get(100000)).toBe(field2);
+ });
+
+ it('sets and gets a field when pivot is zero', () => {
+ const storage = new BinaryStorage(0);
+
+ storage.set(0, field1);
+ storage.set(100000, field2);
+
+ expect(storage.getPivot()).toBe(0);
+ expect(storage.get(0)).toBe(field1);
+ expect(storage.get(100000)).toBe(field2);
+ });
+
+ it('sets and gets a field when pivot is undefined', () => {
+ const storage = new BinaryStorage();
+
+ storage.set(0, field1);
+ storage.set(DEFAULT_PIVOT, field2);
+ storage.set(DEFAULT_PIVOT + 1, field3);
+
+ expect(storage.getPivot()).toBe(DEFAULT_PIVOT);
+ expect(storage.get(0)).toBe(field1);
+ expect(storage.get(DEFAULT_PIVOT)).toBe(field2);
+ expect(storage.get(DEFAULT_PIVOT + 1)).toBe(field3);
+ });
+
+ it('returns undefined for nonexistent fields', () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+
+ expect(storage.get(1)).toBeUndefined();
+ expect(storage.get(DEFAULT_PIVOT)).toBeUndefined();
+ expect(storage.get(DEFAULT_PIVOT + 1)).toBeUndefined();
+ expect(storage.get(100000)).toBeUndefined();
+ });
+
+ it('returns undefined for nonexistent fields after map initialization',
+ () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+ storage.set(100001, field1);
+
+ expect(storage.get(1)).toBeUndefined();
+ expect(storage.get(DEFAULT_PIVOT)).toBeUndefined();
+ expect(storage.get(DEFAULT_PIVOT + 1)).toBeUndefined();
+ expect(storage.get(100000)).toBeUndefined();
+ });
+
+ it('deletes a field in delete() when values are only in array', () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+ storage.set(1, field1);
+
+ storage.delete(1);
+
+ expect(storage.get(1)).toBeUndefined();
+ });
+
+ it('deletes a field in delete() when values are both in array and map',
+ () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+ storage.set(DEFAULT_PIVOT, field2);
+ storage.set(DEFAULT_PIVOT + 1, field3);
+
+ storage.delete(DEFAULT_PIVOT);
+ storage.delete(DEFAULT_PIVOT + 1);
+
+ expect(storage.get(DEFAULT_PIVOT)).toBeUndefined();
+ expect(storage.get(DEFAULT_PIVOT + 1)).toBeUndefined();
+ });
+
+ it('deletes a field in delete() when values are only in map', () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+ storage.set(100000, field4);
+
+ storage.delete(100000);
+
+ expect(storage.get(100000)).toBeUndefined();
+ });
+
+ it('loops over all the elements in forEach()', () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+ storage.set(1, field1);
+ storage.set(DEFAULT_PIVOT, field2);
+ storage.set(DEFAULT_PIVOT + 1, field3);
+ storage.set(100000, field4);
+
+ const fields = new Map();
+ storage.forEach(
+ (field, fieldNumber) => void fields.set(fieldNumber, field));
+
+ expect(fields.size).toEqual(4);
+ expect(fields.get(1)).toBe(field1);
+ expect(storage.get(DEFAULT_PIVOT)).toBe(field2);
+ expect(storage.get(DEFAULT_PIVOT + 1)).toBe(field3);
+ expect(fields.get(100000)).toBe(field4);
+ });
+
+ it('creates a shallow copy of the storage in shallowCopy()', () => {
+ const storage = new BinaryStorage(DEFAULT_PIVOT);
+ storage.set(1, field1);
+ storage.set(100000, field2);
+
+ const copy = storage.shallowCopy();
+
+ expect(getStorageSize(copy)).toEqual(2);
+ expect(copy.get(1)).not.toBe(field1);
+ expect(copy.get(1).getDecodedValue()).toEqual(1);
+ expect(copy.get(100000)).not.toBe(field1);
+ expect(copy.get(100000).getDecodedValue()).toEqual(2);
+ });
+});
diff --git a/js/experimental/runtime/kernel/bool_test_pairs.js b/js/experimental/runtime/kernel/bool_test_pairs.js
new file mode 100644
index 0000000..4323f5b
--- /dev/null
+++ b/js/experimental/runtime/kernel/bool_test_pairs.js
@@ -0,0 +1,79 @@
+/**
+ * @fileoverview Test data for bool encoding and decoding.
+ */
+goog.module('protobuf.binary.boolTestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of boolean values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, boolValue: boolean, bufferDecoder:
+ * !BufferDecoder, error: ?boolean, skip_writer: ?boolean}>}
+ */
+function getBoolPairs() {
+ const boolPairs = [
+ {
+ name: 'true',
+ boolValue: true,
+ bufferDecoder: createBufferDecoder(0x01),
+ },
+ {
+ name: 'false',
+ boolValue: false,
+ bufferDecoder: createBufferDecoder(0x00),
+ },
+ {
+ name: 'two-byte true',
+ boolValue: true,
+ bufferDecoder: createBufferDecoder(0x80, 0x01),
+ skip_writer: true,
+ },
+ {
+ name: 'two-byte false',
+ boolValue: false,
+ bufferDecoder: createBufferDecoder(0x80, 0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'minus one',
+ boolValue: true,
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ skip_writer: true,
+ },
+ {
+ name: 'max signed int 2^63 - 1',
+ boolValue: true,
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F),
+ skip_writer: true,
+ },
+ {
+ name: 'min signed int -2^63',
+ boolValue: true,
+ bufferDecoder: createBufferDecoder(
+ 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01),
+ skip_writer: true,
+ },
+ {
+ name: 'overflowed but valid varint',
+ boolValue: false,
+ bufferDecoder: createBufferDecoder(
+ 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02),
+ skip_writer: true,
+ },
+ {
+ name: 'errors out for 11 bytes',
+ boolValue: true,
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF),
+ error: true,
+ skip_writer: true,
+ },
+ ];
+ return [...boolPairs];
+}
+
+exports = {getBoolPairs};
diff --git a/js/experimental/runtime/kernel/buffer_decoder.js b/js/experimental/runtime/kernel/buffer_decoder.js
new file mode 100644
index 0000000..b0c4535
--- /dev/null
+++ b/js/experimental/runtime/kernel/buffer_decoder.js
@@ -0,0 +1,343 @@
+/**
+ * @fileoverview A buffer implementation that can decode data for protobufs.
+ */
+
+goog.module('protobuf.binary.BufferDecoder');
+
+const ByteString = goog.require('protobuf.ByteString');
+const functions = goog.require('goog.functions');
+const {POLYFILL_TEXT_ENCODING, checkCriticalPositionIndex, checkCriticalState, checkState} = goog.require('protobuf.internal.checks');
+const {byteStringFromUint8ArrayUnsafe} = goog.require('protobuf.byteStringInternal');
+const {concatenateByteArrays} = goog.require('protobuf.binary.uint8arrays');
+const {decode} = goog.require('protobuf.binary.textencoding');
+
+/**
+ * Returns a valid utf-8 decoder function based on TextDecoder if available or
+ * a polyfill.
+ * Some of the environments we run in do not have TextDecoder defined.
+ * TextDecoder is faster than our polyfill so we prefer it over the polyfill.
+ * @return {function(!DataView): string}
+ */
+function getStringDecoderFunction() {
+ if (goog.global['TextDecoder']) {
+ const textDecoder = new goog.global['TextDecoder']('utf-8', {fatal: true});
+ return bytes => textDecoder.decode(bytes);
+ }
+ if (POLYFILL_TEXT_ENCODING) {
+ return decode;
+ } else {
+ throw new Error(
+ 'TextDecoder is missing. ' +
+ 'Enable protobuf.defines.POLYFILL_TEXT_ENCODING.');
+ }
+}
+
+/** @type {function(): function(!DataView): string} */
+const stringDecoderFunction =
+ functions.cacheReturnValue(() => getStringDecoderFunction());
+
+/** @type {function(): !DataView} */
+const emptyDataView =
+ functions.cacheReturnValue(() => new DataView(new ArrayBuffer(0)));
+
+class BufferDecoder {
+ /**
+ * @param {!Array<!BufferDecoder>} bufferDecoders
+ * @return {!BufferDecoder}
+ */
+ static merge(bufferDecoders) {
+ const uint8Arrays = bufferDecoders.map(b => b.asUint8Array());
+ const bytesArray = concatenateByteArrays(uint8Arrays);
+ return BufferDecoder.fromArrayBuffer(bytesArray.buffer);
+ }
+
+ /**
+ * @param {!ArrayBuffer} arrayBuffer
+ * @return {!BufferDecoder}
+ */
+ static fromArrayBuffer(arrayBuffer) {
+ return new BufferDecoder(
+ new DataView(arrayBuffer), 0, arrayBuffer.byteLength);
+ }
+
+ /**
+ * @param {!DataView} dataView
+ * @param {number} startIndex
+ * @param {number} length
+ * @private
+ */
+ constructor(dataView, startIndex, length) {
+ /** @private @const {!DataView} */
+ this.dataView_ = dataView;
+ /** @private @const {number} */
+ this.startIndex_ = startIndex;
+ /** @private @const {number} */
+ this.endIndex_ = startIndex + length;
+ /** @private {number} */
+ this.cursor_ = startIndex;
+ }
+
+ /**
+ * Returns the start index of the underlying buffer.
+ * @return {number}
+ */
+ startIndex() {
+ return this.startIndex_;
+ }
+
+ /**
+ * Returns the end index of the underlying buffer.
+ * @return {number}
+ */
+ endIndex() {
+ return this.endIndex_;
+ }
+
+ /**
+ * Returns the length of the underlying buffer.
+ * @return {number}
+ */
+ length() {
+ return this.endIndex_ - this.startIndex_;
+ }
+
+ /**
+ * Returns the start position of the next data, i.e. end position of the last
+ * read data + 1.
+ * @return {number}
+ */
+ cursor() {
+ return this.cursor_;
+ }
+
+ /**
+ * Sets the cursor to the specified position.
+ * @param {number} position
+ */
+ setCursor(position) {
+ this.cursor_ = position;
+ }
+
+ /**
+ * Returns if there is more data to read after the current cursor position.
+ * @return {boolean}
+ */
+ hasNext() {
+ return this.cursor_ < this.endIndex_;
+ }
+
+ /**
+ * Returns a float32 from a given index
+ * @param {number} index
+ * @return {number}
+ */
+ getFloat32(index) {
+ this.cursor_ = index + 4;
+ return this.dataView_.getFloat32(index, true);
+ }
+
+ /**
+ * Returns a float64 from a given index
+ * @param {number} index
+ * @return {number}
+ */
+ getFloat64(index) {
+ this.cursor_ = index + 8;
+ return this.dataView_.getFloat64(index, true);
+ }
+
+ /**
+ * Returns an int32 from a given index
+ * @param {number} index
+ * @return {number}
+ */
+ getInt32(index) {
+ this.cursor_ = index + 4;
+ return this.dataView_.getInt32(index, true);
+ }
+
+ /**
+ * Returns a uint32 from a given index
+ * @param {number} index
+ * @return {number}
+ */
+ getUint32(index) {
+ this.cursor_ = index + 4;
+ return this.dataView_.getUint32(index, true);
+ }
+
+ /**
+ * Returns two JS numbers each representing 32 bits of a 64 bit number. Also
+ * sets the cursor to the start of the next block of data.
+ * @param {number} index
+ * @return {{lowBits: number, highBits: number}}
+ */
+ getVarint(index) {
+ this.cursor_ = index;
+ let lowBits = 0;
+ let highBits = 0;
+
+ for (let shift = 0; shift < 28; shift += 7) {
+ const b = this.dataView_.getUint8(this.cursor_++);
+ lowBits |= (b & 0x7F) << shift;
+ if ((b & 0x80) === 0) {
+ return {lowBits, highBits};
+ }
+ }
+
+ const middleByte = this.dataView_.getUint8(this.cursor_++);
+
+ // last four bits of the first 32 bit number
+ lowBits |= (middleByte & 0x0F) << 28;
+
+ // 3 upper bits are part of the next 32 bit number
+ highBits = (middleByte & 0x70) >> 4;
+
+ if ((middleByte & 0x80) === 0) {
+ return {lowBits, highBits};
+ }
+
+
+ for (let shift = 3; shift <= 31; shift += 7) {
+ const b = this.dataView_.getUint8(this.cursor_++);
+ highBits |= (b & 0x7F) << shift;
+ if ((b & 0x80) === 0) {
+ return {lowBits, highBits};
+ }
+ }
+
+ checkCriticalState(false, 'Data is longer than 10 bytes');
+
+ return {lowBits, highBits};
+ }
+
+ /**
+ * Returns an unsigned int32 number at the current cursor position. The upper
+ * bits are discarded if the varint is longer than 32 bits. Also sets the
+ * cursor to the start of the next block of data.
+ * @return {number}
+ */
+ getUnsignedVarint32() {
+ let b = this.dataView_.getUint8(this.cursor_++);
+ let result = b & 0x7F;
+ if ((b & 0x80) === 0) {
+ return result;
+ }
+
+ b = this.dataView_.getUint8(this.cursor_++);
+ result |= (b & 0x7F) << 7;
+ if ((b & 0x80) === 0) {
+ return result;
+ }
+
+ b = this.dataView_.getUint8(this.cursor_++);
+ result |= (b & 0x7F) << 14;
+ if ((b & 0x80) === 0) {
+ return result;
+ }
+
+ b = this.dataView_.getUint8(this.cursor_++);
+ result |= (b & 0x7F) << 21;
+ if ((b & 0x80) === 0) {
+ return result;
+ }
+
+ // Extract only last 4 bits
+ b = this.dataView_.getUint8(this.cursor_++);
+ result |= (b & 0x0F) << 28;
+
+ for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++) {
+ b = this.dataView_.getUint8(this.cursor_++);
+ }
+
+ checkCriticalState((b & 0x80) === 0, 'Data is longer than 10 bytes');
+
+ // Result can be have 32 bits, convert it to unsigned
+ return result >>> 0;
+ }
+
+ /**
+ * Returns an unsigned int32 number at the specified index. The upper bits are
+ * discarded if the varint is longer than 32 bits. Also sets the cursor to the
+ * start of the next block of data.
+ * @param {number} index
+ * @return {number}
+ */
+ getUnsignedVarint32At(index) {
+ this.cursor_ = index;
+ return this.getUnsignedVarint32();
+ }
+
+ /**
+ * Seeks forward by the given amount.
+ * @param {number} skipAmount
+ * @package
+ */
+ skip(skipAmount) {
+ this.cursor_ += skipAmount;
+ checkCriticalPositionIndex(this.cursor_, this.endIndex_);
+ }
+
+ /**
+ * Skips over a varint from the current cursor position.
+ * @package
+ */
+ skipVarint() {
+ const startIndex = this.cursor_;
+ while (this.dataView_.getUint8(this.cursor_++) & 0x80) {
+ }
+ checkCriticalPositionIndex(this.cursor_, startIndex + 10);
+ }
+
+ /**
+ * @param {number} startIndex
+ * @param {number} length
+ * @return {!BufferDecoder}
+ */
+ subBufferDecoder(startIndex, length) {
+ checkState(
+ startIndex >= this.startIndex(),
+ `Current start: ${this.startIndex()}, subBufferDecoder start: ${
+ startIndex}`);
+ checkState(length >= 0, `Length: ${length}`);
+ checkState(
+ startIndex + length <= this.endIndex(),
+ `Current end: ${this.endIndex()}, subBufferDecoder start: ${
+ startIndex}, subBufferDecoder length: ${length}`);
+ return new BufferDecoder(this.dataView_, startIndex, length);
+ }
+
+ /**
+ * Returns the buffer as a string.
+ * @return {string}
+ */
+ asString() {
+ // TODO: Remove this check when we no longer need to support IE
+ const stringDataView = this.length() === 0 ?
+ emptyDataView() :
+ new DataView(this.dataView_.buffer, this.startIndex_, this.length());
+ return stringDecoderFunction()(stringDataView);
+ }
+
+ /**
+ * Returns the buffer as a ByteString.
+ * @return {!ByteString}
+ */
+ asByteString() {
+ return byteStringFromUint8ArrayUnsafe(this.asUint8Array());
+ }
+
+ /**
+ * Returns the DataView as an Uint8Array. DO NOT MODIFY or expose the
+ * underlying buffer.
+ *
+ * @package
+ * @return {!Uint8Array}
+ */
+ asUint8Array() {
+ return new Uint8Array(
+ this.dataView_.buffer, this.startIndex_, this.length());
+ }
+}
+
+exports = BufferDecoder;
diff --git a/js/experimental/runtime/kernel/buffer_decoder_helper.js b/js/experimental/runtime/kernel/buffer_decoder_helper.js
new file mode 100644
index 0000000..eed3c42
--- /dev/null
+++ b/js/experimental/runtime/kernel/buffer_decoder_helper.js
@@ -0,0 +1,18 @@
+/**
+ * @fileoverview Helper methods to create BufferDecoders.
+ */
+goog.module('protobuf.binary.bufferDecoderHelper');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+
+/**
+ * @param {...number} bytes
+ * @return {!BufferDecoder}
+ */
+function createBufferDecoder(...bytes) {
+ return BufferDecoder.fromArrayBuffer(new Uint8Array(bytes).buffer);
+}
+
+exports = {
+ createBufferDecoder,
+};
diff --git a/js/experimental/runtime/kernel/buffer_decoder_test.js b/js/experimental/runtime/kernel/buffer_decoder_test.js
new file mode 100644
index 0000000..17f2896
--- /dev/null
+++ b/js/experimental/runtime/kernel/buffer_decoder_test.js
@@ -0,0 +1,242 @@
+/**
+ * @fileoverview Tests for BufferDecoder.
+ */
+
+goog.module('protobuf.binary.varintsTest');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {CHECK_CRITICAL_STATE, CHECK_STATE} = goog.require('protobuf.internal.checks');
+
+goog.setTestOnly();
+
+/**
+ * @param {...number} bytes
+ * @return {!ArrayBuffer}
+ */
+function createArrayBuffer(...bytes) {
+ return new Uint8Array(bytes).buffer;
+}
+
+describe('setCursor does', () => {
+ it('set the cursor at the position specified', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x0, 0x1));
+ expect(bufferDecoder.cursor()).toBe(0);
+ bufferDecoder.setCursor(1);
+ expect(bufferDecoder.cursor()).toBe(1);
+ });
+});
+
+describe('skip does', () => {
+ it('advance the cursor', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x0, 0x1, 0x2));
+ bufferDecoder.setCursor(1);
+ bufferDecoder.skip(1);
+ expect(bufferDecoder.cursor()).toBe(2);
+ });
+});
+
+describe('Skip varint does', () => {
+ it('skip a varint', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x01));
+ bufferDecoder.skipVarint();
+ expect(bufferDecoder.cursor()).toBe(1);
+ });
+
+ it('fail when varint is larger than 10 bytes', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(createArrayBuffer(
+ 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => bufferDecoder.skipVarint()).toThrow();
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ bufferDecoder.skipVarint();
+ expect(bufferDecoder.cursor()).toBe(11);
+ }
+ });
+
+ it('fail when varint is beyond end of underlying array', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x80, 0x80));
+ expect(() => bufferDecoder.skipVarint()).toThrow();
+ });
+});
+
+describe('readVarint64 does', () => {
+ it('read zero', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x00));
+ const {lowBits, highBits} = bufferDecoder.getVarint(0);
+ expect(lowBits).toBe(0);
+ expect(highBits).toBe(0);
+ expect(bufferDecoder.cursor()).toBe(1);
+ });
+
+ it('read one', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x01));
+ const {lowBits, highBits} = bufferDecoder.getVarint(0);
+ expect(lowBits).toBe(1);
+ expect(highBits).toBe(0);
+ expect(bufferDecoder.cursor()).toBe(1);
+ });
+
+ it('read max value', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(createArrayBuffer(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01));
+ const {lowBits, highBits} = bufferDecoder.getVarint(0);
+ expect(lowBits).toBe(-1);
+ expect(highBits).toBe(-1);
+ expect(bufferDecoder.cursor()).toBe(10);
+ });
+});
+
+describe('readUnsignedVarint32 does', () => {
+ it('read zero', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x00));
+ const result = bufferDecoder.getUnsignedVarint32();
+ expect(result).toBe(0);
+ expect(bufferDecoder.cursor()).toBe(1);
+ });
+
+ it('read one', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x01));
+ const result = bufferDecoder.getUnsignedVarint32();
+ expect(result).toBe(1);
+ expect(bufferDecoder.cursor()).toBe(1);
+ });
+
+ it('read max int32', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0xFF, 0xFF, 0xFF, 0xFF, 0x0F));
+ const result = bufferDecoder.getUnsignedVarint32();
+ expect(result).toBe(4294967295);
+ expect(bufferDecoder.cursor()).toBe(5);
+ });
+
+ it('read max value', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(createArrayBuffer(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01));
+ const result = bufferDecoder.getUnsignedVarint32();
+ expect(result).toBe(4294967295);
+ expect(bufferDecoder.cursor()).toBe(10);
+ });
+
+ it('fail if data is longer than 10 bytes', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(createArrayBuffer(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => bufferDecoder.getUnsignedVarint32()).toThrow();
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const result = bufferDecoder.getUnsignedVarint32();
+ expect(result).toBe(4294967295);
+ expect(bufferDecoder.cursor()).toBe(10);
+ }
+ });
+});
+
+describe('readUnsignedVarint32At does', () => {
+ it('reads from a specific index', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x1, 0x2));
+ const result = bufferDecoder.getUnsignedVarint32At(1);
+ expect(result).toBe(2);
+ expect(bufferDecoder.cursor()).toBe(2);
+ });
+});
+
+describe('getFloat32 does', () => {
+ it('read one', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0x00, 0x00, 0x80, 0x3F));
+ const result = bufferDecoder.getFloat32(0);
+ expect(result).toBe(1);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+});
+
+describe('getFloat64 does', () => {
+ it('read one', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F));
+ const result = bufferDecoder.getFloat64(0);
+ expect(result).toBe(1);
+ expect(bufferDecoder.cursor()).toBe(8);
+ });
+});
+
+describe('getInt32 does', () => {
+ it('read one', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0x01, 0x00, 0x00, 0x00));
+ const result = bufferDecoder.getInt32(0);
+ expect(result).toBe(1);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+
+ it('read minus one', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0xFF, 0xFF, 0xFF, 0xFF));
+ const result = bufferDecoder.getInt32(0);
+ expect(result).toBe(-1);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+});
+
+describe('getUint32 does', () => {
+ it('read one', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x01, 0x00, 0x00, 0x0));
+ const result = bufferDecoder.getUint32(0);
+ expect(result).toBe(1);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+
+ it('read max uint32', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0xFF, 0xFF, 0xFF, 0xFF));
+ const result = bufferDecoder.getUint32(0);
+ expect(result).toBe(4294967295);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+});
+
+describe('subBufferDecoder does', () => {
+ it('can create valid sub buffers', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x00, 0x01, 0x02));
+
+ expect(bufferDecoder.subBufferDecoder(0, 0))
+ .toEqual(BufferDecoder.fromArrayBuffer(createArrayBuffer()));
+ expect(bufferDecoder.subBufferDecoder(0, 1))
+ .toEqual(BufferDecoder.fromArrayBuffer(createArrayBuffer(0x00)));
+ expect(bufferDecoder.subBufferDecoder(1, 0))
+ .toEqual(BufferDecoder.fromArrayBuffer(createArrayBuffer()));
+ expect(bufferDecoder.subBufferDecoder(1, 1))
+ .toEqual(BufferDecoder.fromArrayBuffer(createArrayBuffer(0x01)));
+ expect(bufferDecoder.subBufferDecoder(1, 2))
+ .toEqual(BufferDecoder.fromArrayBuffer(createArrayBuffer(0x01, 0x02)));
+ });
+
+ it('can not create invalid', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x00, 0x01, 0x02));
+ if (CHECK_STATE) {
+ expect(() => bufferDecoder.subBufferDecoder(-1, 1)).toThrow();
+ expect(() => bufferDecoder.subBufferDecoder(0, -4)).toThrow();
+ expect(() => bufferDecoder.subBufferDecoder(0, 4)).toThrow();
+ }
+ });
+});
diff --git a/js/experimental/runtime/kernel/conformance/conformance_request.js b/js/experimental/runtime/kernel/conformance/conformance_request.js
new file mode 100644
index 0000000..2d4f106
--- /dev/null
+++ b/js/experimental/runtime/kernel/conformance/conformance_request.js
@@ -0,0 +1,91 @@
+/**
+ * @fileoverview Handwritten code of ConformanceRequest.
+ */
+goog.module('proto.conformance.ConformanceRequest');
+
+const Kernel = goog.require('protobuf.runtime.Kernel');
+const WireFormat = goog.require('proto.conformance.WireFormat');
+
+/**
+ * Handwritten code of conformance.ConformanceRequest.
+ * This is used to send request from the conformance test runner to the testee.
+ * Check //third_party/protobuf/testing/protobuf/conformance/conformance.proto
+ * for more details.
+ * @final
+ */
+class ConformanceRequest {
+ /**
+ * @param {!ArrayBuffer} bytes
+ * @private
+ */
+ constructor(bytes) {
+ /** @private @const {!Kernel} */
+ this.accessor_ = Kernel.fromArrayBuffer(bytes);
+ }
+
+ /**
+ * Create a request instance with the given bytes data.
+ * @param {!ArrayBuffer} bytes
+ * @return {!ConformanceRequest}
+ */
+ static deserialize(bytes) {
+ return new ConformanceRequest(bytes);
+ }
+
+ /**
+ * Gets the protobuf_payload.
+ * @return {!ArrayBuffer}
+ */
+ getProtobufPayload() {
+ return this.accessor_.getBytesWithDefault(1).toArrayBuffer();
+ }
+
+ /**
+ * Gets the requested_output_format.
+ * @return {!WireFormat}
+ */
+ getRequestedOutputFormat() {
+ return /** @type {!WireFormat} */ (this.accessor_.getInt32WithDefault(3));
+ }
+
+ /**
+ * Gets the message_type.
+ * @return {string}
+ */
+ getMessageType() {
+ return this.accessor_.getStringWithDefault(4);
+ }
+
+ /**
+ * Gets the oneof case for payload field.
+ * This implementation assumes only one field in a oneof group is set.
+ * @return {!ConformanceRequest.PayloadCase}
+ */
+ getPayloadCase() {
+ if (this.accessor_.hasFieldNumber(1)) {
+ return /** @type {!ConformanceRequest.PayloadCase} */ (
+ ConformanceRequest.PayloadCase.PROTOBUF_PAYLOAD);
+ } else if (this.accessor_.hasFieldNumber(2)) {
+ return /** @type {!ConformanceRequest.PayloadCase} */ (
+ ConformanceRequest.PayloadCase.JSON_PAYLOAD);
+ } else if (this.accessor_.hasFieldNumber(8)) {
+ return /** @type {!ConformanceRequest.PayloadCase} */ (
+ ConformanceRequest.PayloadCase.TEXT_PAYLOAD);
+ } else {
+ return /** @type {!ConformanceRequest.PayloadCase} */ (
+ ConformanceRequest.PayloadCase.PAYLOAD_NOT_SET);
+ }
+ }
+}
+
+/**
+ * @enum {number}
+ */
+ConformanceRequest.PayloadCase = {
+ PAYLOAD_NOT_SET: 0,
+ PROTOBUF_PAYLOAD: 1,
+ JSON_PAYLOAD: 2,
+ TEXT_PAYLOAD: 8,
+};
+
+exports = ConformanceRequest;
diff --git a/js/experimental/runtime/kernel/conformance/conformance_response.js b/js/experimental/runtime/kernel/conformance/conformance_response.js
new file mode 100644
index 0000000..482f31b
--- /dev/null
+++ b/js/experimental/runtime/kernel/conformance/conformance_response.js
@@ -0,0 +1,76 @@
+/**
+ * @fileoverview Handwritten code of ConformanceResponse.
+ */
+goog.module('proto.conformance.ConformanceResponse');
+
+const ByteString = goog.require('protobuf.ByteString');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+
+/**
+ * Handwritten code of conformance.ConformanceResponse.
+ * This is used to send response from the conformance testee to the test runner.
+ * Check //third_party/protobuf/testing/protobuf/conformance/conformance.proto
+ * for more details.
+ * @final
+ */
+class ConformanceResponse {
+ /**
+ * @param {!ArrayBuffer} bytes
+ * @private
+ */
+ constructor(bytes) {
+ /** @private @const {!Kernel} */
+ this.accessor_ = Kernel.fromArrayBuffer(bytes);
+ }
+
+ /**
+ * Create an empty response instance.
+ * @return {!ConformanceResponse}
+ */
+ static createEmpty() {
+ return new ConformanceResponse(new ArrayBuffer(0));
+ }
+
+ /**
+ * Sets parse_error field.
+ * @param {string} value
+ */
+ setParseError(value) {
+ this.accessor_.setString(1, value);
+ }
+
+ /**
+ * Sets runtime_error field.
+ * @param {string} value
+ */
+ setRuntimeError(value) {
+ this.accessor_.setString(2, value);
+ }
+
+ /**
+ * Sets protobuf_payload field.
+ * @param {!ArrayBuffer} value
+ */
+ setProtobufPayload(value) {
+ const bytesString = ByteString.fromArrayBuffer(value);
+ this.accessor_.setBytes(3, bytesString);
+ }
+
+ /**
+ * Sets skipped field.
+ * @param {string} value
+ */
+ setSkipped(value) {
+ this.accessor_.setString(5, value);
+ }
+
+ /**
+ * Serializes into binary data.
+ * @return {!ArrayBuffer}
+ */
+ serialize() {
+ return this.accessor_.serialize();
+ }
+}
+
+exports = ConformanceResponse;
diff --git a/js/experimental/runtime/kernel/conformance/conformance_testee.js b/js/experimental/runtime/kernel/conformance/conformance_testee.js
new file mode 100755
index 0000000..2945228
--- /dev/null
+++ b/js/experimental/runtime/kernel/conformance/conformance_testee.js
@@ -0,0 +1,103 @@
+goog.module('javascript.protobuf.conformance');
+
+const ConformanceRequest = goog.require('proto.conformance.ConformanceRequest');
+const ConformanceResponse = goog.require('proto.conformance.ConformanceResponse');
+const TestAllTypesProto2 = goog.require('proto.conformance.TestAllTypesProto2');
+const TestAllTypesProto3 = goog.require('proto.conformance.TestAllTypesProto3');
+const WireFormat = goog.require('proto.conformance.WireFormat');
+const base64 = goog.require('goog.crypt.base64');
+
+/**
+ * Creates a `proto.conformance.ConformanceResponse` response according to the
+ * `proto.conformance.ConformanceRequest` request.
+ * @param {!ConformanceRequest} request
+ * @return {!ConformanceResponse} response
+ */
+function doTest(request) {
+ const response = ConformanceResponse.createEmpty();
+
+ if(request.getPayloadCase() === ConformanceRequest.PayloadCase.JSON_PAYLOAD) {
+ response.setSkipped('Json is not supported as input format.');
+ return response;
+ }
+
+ if(request.getPayloadCase() === ConformanceRequest.PayloadCase.TEXT_PAYLOAD) {
+ response.setSkipped('Text format is not supported as input format.');
+ return response;
+ }
+
+ if(request.getPayloadCase() === ConformanceRequest.PayloadCase.PAYLOAD_NOT_SET) {
+ response.setRuntimeError('Request didn\'t have payload.');
+ return response;
+ }
+
+ if(request.getPayloadCase() !== ConformanceRequest.PayloadCase.PROTOBUF_PAYLOAD) {
+ throw new Error('Request didn\'t have accepted input format.');
+ }
+
+ if (request.getRequestedOutputFormat() === WireFormat.JSON) {
+ response.setSkipped('Json is not supported as output format.');
+ return response;
+ }
+
+ if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) {
+ response.setSkipped('Text format is not supported as output format.');
+ return response;
+ }
+
+ if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) {
+ response.setRuntimeError('Unspecified output format');
+ return response;
+ }
+
+ if (request.getRequestedOutputFormat() !== WireFormat.PROTOBUF) {
+ throw new Error('Request didn\'t have accepted output format.');
+ }
+
+ if (request.getMessageType() === 'conformance.FailureSet') {
+ response.setProtobufPayload(new ArrayBuffer(0));
+ } else if (
+ request.getMessageType() ===
+ 'protobuf_test_messages.proto2.TestAllTypesProto2') {
+ try {
+ const testMessage =
+ TestAllTypesProto2.deserialize(request.getProtobufPayload());
+ response.setProtobufPayload(testMessage.serialize());
+ } catch (err) {
+ response.setParseError(err.toString());
+ }
+ } else if (
+ request.getMessageType() ===
+ 'protobuf_test_messages.proto3.TestAllTypesProto3') {
+ try {
+ const testMessage =
+ TestAllTypesProto3.deserialize(request.getProtobufPayload());
+ response.setProtobufPayload(testMessage.serialize());
+ } catch (err) {
+ response.setParseError(err.toString());
+ }
+ } else {
+ throw new Error(
+ `Payload message not supported: ${request.getMessageType()}.`);
+ }
+
+ return response;
+}
+
+/**
+ * Same as doTest, but both request and response are in base64.
+ * @param {string} base64Request
+ * @return {string} response
+ */
+function runConformanceTest(base64Request) {
+ const request =
+ ConformanceRequest.deserialize(
+ base64.decodeStringToUint8Array(base64Request).buffer);
+ const response = doTest(request);
+ return base64.encodeByteArray(new Uint8Array(response.serialize()));
+}
+
+// Needed for node test
+exports.doTest = doTest;
+// Needed for browser test
+goog.exportSymbol('runConformanceTest', runConformanceTest);
diff --git a/js/experimental/runtime/kernel/conformance/conformance_testee_runner_node.js b/js/experimental/runtime/kernel/conformance/conformance_testee_runner_node.js
new file mode 100755
index 0000000..c12f363
--- /dev/null
+++ b/js/experimental/runtime/kernel/conformance/conformance_testee_runner_node.js
@@ -0,0 +1,62 @@
+const ConformanceRequest = goog.require('proto.conformance.ConformanceRequest');
+const {doTest} = goog.require('javascript.protobuf.conformance');
+const fs = require('fs');
+
+
+/**
+ * Reads a buffer of N bytes.
+ * @param {number} bytes Number of bytes to read.
+ * @return {!Buffer} Buffer which contains data.
+ */
+function readBuffer(bytes) {
+ // Linux cannot use process.stdin.fd (which isn't set up as sync)
+ const buf = new Buffer.alloc(bytes);
+ const fd = fs.openSync('/dev/stdin', 'r');
+ fs.readSync(fd, buf, 0, bytes);
+ fs.closeSync(fd);
+ return buf;
+}
+
+/**
+ * Writes all data in buffer.
+ * @param {!Buffer} buffer Buffer which contains data.
+ */
+function writeBuffer(buffer) {
+ // Under linux, process.stdout.fd is async. Needs to open stdout in a synced
+ // way for sync write.
+ const fd = fs.openSync('/dev/stdout', 'w');
+ fs.writeSync(fd, buffer, 0, buffer.length);
+ fs.closeSync(fd);
+}
+
+/**
+ * Returns true if the test ran successfully, false on legitimate EOF.
+ * @return {boolean} Whether to continue test.
+ */
+function runConformanceTest() {
+ const requestLengthBuf = readBuffer(4);
+ const requestLength = requestLengthBuf.readInt32LE(0);
+ if (!requestLength) {
+ return false;
+ }
+
+ const serializedRequest = readBuffer(requestLength);
+ const array = new Uint8Array(serializedRequest);
+ const request = ConformanceRequest.deserialize(array.buffer);
+ const response = doTest(request);
+
+ const serializedResponse = response.serialize();
+
+ const responseLengthBuf = new Buffer.alloc(4);
+ responseLengthBuf.writeInt32LE(serializedResponse.byteLength, 0);
+ writeBuffer(responseLengthBuf);
+ writeBuffer(new Buffer.from(serializedResponse));
+
+ return true;
+}
+
+while (true) {
+ if (!runConformanceTest()) {
+ break;
+ }
+}
diff --git a/js/experimental/runtime/kernel/conformance/test_all_types_proto2.js b/js/experimental/runtime/kernel/conformance/test_all_types_proto2.js
new file mode 100644
index 0000000..3be1bee
--- /dev/null
+++ b/js/experimental/runtime/kernel/conformance/test_all_types_proto2.js
@@ -0,0 +1,309 @@
+/**
+ * @fileoverview Handwritten code of TestAllTypesProto2.
+ */
+goog.module('proto.conformance.TestAllTypesProto2');
+
+const InternalMessage = goog.require('protobuf.binary.InternalMessage');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+
+/**
+ * Handwritten code of conformance.TestAllTypesProto2.
+ * Check google/protobuf/test_messages_proto3.proto for more details.
+ * @implements {InternalMessage}
+ * @final
+ */
+class TestAllTypesProto2 {
+ /**
+ * @param {!Kernel=} accessor
+ * @private
+ */
+ constructor(accessor = Kernel.createEmpty()) {
+ /** @private @const {!Kernel} */
+ this.accessor_ = accessor;
+ }
+
+ /**
+ * @override
+ * @package
+ * @return {!Kernel}
+ */
+ internalGetKernel() {
+ return this.accessor_;
+ }
+
+ /**
+ * Create a request instance with the given bytes data.
+ * If we directly use the accessor created by the binary decoding, the
+ * Kernel instance will only copy the same data over for encoding. By
+ * explicitly fetching data from the previous accessor and setting all fields
+ * into a new accessor, we will actually test encoding/decoding for the binary
+ * format.
+ * @param {!ArrayBuffer} bytes
+ * @return {!TestAllTypesProto2}
+ */
+ static deserialize(bytes) {
+ const msg = new TestAllTypesProto2();
+ const requestAccessor = Kernel.fromArrayBuffer(bytes);
+
+ if (requestAccessor.hasFieldNumber(1)) {
+ const value = requestAccessor.getInt32WithDefault(1);
+ msg.accessor_.setInt32(1, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(2)) {
+ const value = requestAccessor.getInt64WithDefault(2);
+ msg.accessor_.setInt64(2, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(3)) {
+ const value = requestAccessor.getUint32WithDefault(3);
+ msg.accessor_.setUint32(3, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(4)) {
+ const value = requestAccessor.getUint64WithDefault(4);
+ msg.accessor_.setUint64(4, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(5)) {
+ const value = requestAccessor.getSint32WithDefault(5);
+ msg.accessor_.setSint32(5, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(6)) {
+ const value = requestAccessor.getSint64WithDefault(6);
+ msg.accessor_.setSint64(6, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(7)) {
+ const value = requestAccessor.getFixed32WithDefault(7);
+ msg.accessor_.setFixed32(7, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(8)) {
+ const value = requestAccessor.getFixed64WithDefault(8);
+ msg.accessor_.setFixed64(8, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(9)) {
+ const value = requestAccessor.getSfixed32WithDefault(9);
+ msg.accessor_.setSfixed32(9, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(10)) {
+ const value = requestAccessor.getSfixed64WithDefault(10);
+ msg.accessor_.setSfixed64(10, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(11)) {
+ const value = requestAccessor.getFloatWithDefault(11);
+ msg.accessor_.setFloat(11, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(12)) {
+ const value = requestAccessor.getDoubleWithDefault(12);
+ msg.accessor_.setDouble(12, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(13)) {
+ const value = requestAccessor.getBoolWithDefault(13);
+ msg.accessor_.setBool(13, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(14)) {
+ const value = requestAccessor.getStringWithDefault(14);
+ msg.accessor_.setString(14, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(15)) {
+ const value = requestAccessor.getBytesWithDefault(15);
+ msg.accessor_.setBytes(15, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(18)) {
+ const value = requestAccessor.getMessage(
+ 18, (accessor) => new TestAllTypesProto2(accessor));
+ msg.accessor_.setMessage(18, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(21)) {
+ // Unknown enum is not checked here, because even if an enum is unknown,
+ // it should be kept during encoding. For the purpose of wire format test,
+ // we can simplify the implementation by treating it as an int32 field,
+ // which has the same semantic except for the unknown value checking.
+ const value = requestAccessor.getInt32WithDefault(21);
+ msg.accessor_.setInt32(21, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(31)) {
+ const value = requestAccessor.getRepeatedInt32Iterable(31);
+ msg.accessor_.setUnpackedInt32Iterable(31, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(32)) {
+ const value = requestAccessor.getRepeatedInt64Iterable(32);
+ msg.accessor_.setUnpackedInt64Iterable(32, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(33)) {
+ const value = requestAccessor.getRepeatedUint32Iterable(33);
+ msg.accessor_.setUnpackedUint32Iterable(33, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(34)) {
+ const value = requestAccessor.getRepeatedUint64Iterable(34);
+ msg.accessor_.setUnpackedUint64Iterable(34, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(35)) {
+ const value = requestAccessor.getRepeatedSint32Iterable(35);
+ msg.accessor_.setUnpackedSint32Iterable(35, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(36)) {
+ const value = requestAccessor.getRepeatedSint64Iterable(36);
+ msg.accessor_.setUnpackedSint64Iterable(36, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(37)) {
+ const value = requestAccessor.getRepeatedFixed32Iterable(37);
+ msg.accessor_.setUnpackedFixed32Iterable(37, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(38)) {
+ const value = requestAccessor.getRepeatedFixed64Iterable(38);
+ msg.accessor_.setUnpackedFixed64Iterable(38, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(39)) {
+ const value = requestAccessor.getRepeatedSfixed32Iterable(39);
+ msg.accessor_.setUnpackedSfixed32Iterable(39, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(40)) {
+ const value = requestAccessor.getRepeatedSfixed64Iterable(40);
+ msg.accessor_.setUnpackedSfixed64Iterable(40, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(41)) {
+ const value = requestAccessor.getRepeatedFloatIterable(41);
+ msg.accessor_.setUnpackedFloatIterable(41, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(42)) {
+ const value = requestAccessor.getRepeatedDoubleIterable(42);
+ msg.accessor_.setUnpackedDoubleIterable(42, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(43)) {
+ const value = requestAccessor.getRepeatedBoolIterable(43);
+ msg.accessor_.setUnpackedBoolIterable(43, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(44)) {
+ const value = requestAccessor.getRepeatedStringIterable(44);
+ msg.accessor_.setRepeatedStringIterable(44, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(45)) {
+ const value = requestAccessor.getRepeatedBytesIterable(45);
+ msg.accessor_.setRepeatedBytesIterable(45, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(48)) {
+ const value = requestAccessor.getRepeatedMessageIterable(
+ 48, (accessor) => new TestAllTypesProto2(accessor));
+ msg.accessor_.setRepeatedMessageIterable(48, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(51)) {
+ // Unknown enum is not checked here, because even if an enum is unknown,
+ // it should be kept during encoding. For the purpose of wire format test,
+ // we can simplify the implementation by treating it as an int32 field,
+ // which has the same semantic except for the unknown value checking.
+ const value = requestAccessor.getRepeatedInt32Iterable(51);
+ msg.accessor_.setUnpackedInt32Iterable(51, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(75)) {
+ const value = requestAccessor.getRepeatedInt32Iterable(75);
+ msg.accessor_.setPackedInt32Iterable(75, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(76)) {
+ const value = requestAccessor.getRepeatedInt64Iterable(76);
+ msg.accessor_.setPackedInt64Iterable(76, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(77)) {
+ const value = requestAccessor.getRepeatedUint32Iterable(77);
+ msg.accessor_.setPackedUint32Iterable(77, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(78)) {
+ const value = requestAccessor.getRepeatedUint64Iterable(78);
+ msg.accessor_.setPackedUint64Iterable(78, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(79)) {
+ const value = requestAccessor.getRepeatedSint32Iterable(79);
+ msg.accessor_.setPackedSint32Iterable(79, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(80)) {
+ const value = requestAccessor.getRepeatedSint64Iterable(80);
+ msg.accessor_.setPackedSint64Iterable(80, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(81)) {
+ const value = requestAccessor.getRepeatedFixed32Iterable(81);
+ msg.accessor_.setPackedFixed32Iterable(81, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(82)) {
+ const value = requestAccessor.getRepeatedFixed64Iterable(82);
+ msg.accessor_.setPackedFixed64Iterable(82, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(83)) {
+ const value = requestAccessor.getRepeatedSfixed32Iterable(83);
+ msg.accessor_.setPackedSfixed32Iterable(83, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(84)) {
+ const value = requestAccessor.getRepeatedSfixed64Iterable(84);
+ msg.accessor_.setPackedSfixed64Iterable(84, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(85)) {
+ const value = requestAccessor.getRepeatedFloatIterable(85);
+ msg.accessor_.setPackedFloatIterable(85, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(86)) {
+ const value = requestAccessor.getRepeatedDoubleIterable(86);
+ msg.accessor_.setPackedDoubleIterable(86, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(87)) {
+ const value = requestAccessor.getRepeatedBoolIterable(87);
+ msg.accessor_.setPackedBoolIterable(87, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(88)) {
+ const value = requestAccessor.getRepeatedInt32Iterable(88);
+ msg.accessor_.setPackedInt32Iterable(88, value);
+ }
+ return msg;
+ }
+
+ /**
+ * Serializes into binary data.
+ * @return {!ArrayBuffer}
+ */
+ serialize() {
+ return this.accessor_.serialize();
+ }
+}
+
+exports = TestAllTypesProto2;
diff --git a/js/experimental/runtime/kernel/conformance/test_all_types_proto3.js b/js/experimental/runtime/kernel/conformance/test_all_types_proto3.js
new file mode 100644
index 0000000..c68d370
--- /dev/null
+++ b/js/experimental/runtime/kernel/conformance/test_all_types_proto3.js
@@ -0,0 +1,310 @@
+/**
+ * @fileoverview Handwritten code of TestAllTypesProto3.
+ */
+goog.module('proto.conformance.TestAllTypesProto3');
+
+const InternalMessage = goog.require('protobuf.binary.InternalMessage');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+
+/**
+ * Handwritten code of conformance.TestAllTypesProto3.
+ * Check google/protobuf/test_messages_proto3.proto for more details.
+ * @implements {InternalMessage}
+ * @final
+ */
+class TestAllTypesProto3 {
+ /**
+ * @param {!Kernel=} accessor
+ * @private
+ */
+ constructor(accessor = Kernel.createEmpty()) {
+ /** @private @const {!Kernel} */
+ this.accessor_ = accessor;
+ }
+
+ /**
+ * @override
+ * @package
+ * @return {!Kernel}
+ */
+ internalGetKernel() {
+ return this.accessor_;
+ }
+
+ /**
+ * Create a request instance with the given bytes data.
+ * If we directly use the accessor created by the binary decoding, the
+ * Kernel instance will only copy the same data over for encoding. By
+ * explicitly fetching data from the previous accessor and setting all fields
+ * into a new accessor, we will actually test encoding/decoding for the binary
+ * format.
+ * @param {!ArrayBuffer} bytes
+ * @return {!TestAllTypesProto3}
+ */
+ static deserialize(bytes) {
+ const msg = new TestAllTypesProto3();
+ const requestAccessor = Kernel.fromArrayBuffer(bytes);
+
+ if (requestAccessor.hasFieldNumber(1)) {
+ const value = requestAccessor.getInt32WithDefault(1);
+ msg.accessor_.setInt32(1, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(2)) {
+ const value = requestAccessor.getInt64WithDefault(2);
+ msg.accessor_.setInt64(2, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(3)) {
+ const value = requestAccessor.getUint32WithDefault(3);
+ msg.accessor_.setUint32(3, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(4)) {
+ const value = requestAccessor.getUint64WithDefault(4);
+ msg.accessor_.setUint64(4, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(5)) {
+ const value = requestAccessor.getSint32WithDefault(5);
+ msg.accessor_.setSint32(5, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(6)) {
+ const value = requestAccessor.getSint64WithDefault(6);
+ msg.accessor_.setSint64(6, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(7)) {
+ const value = requestAccessor.getFixed32WithDefault(7);
+ msg.accessor_.setFixed32(7, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(8)) {
+ const value = requestAccessor.getFixed64WithDefault(8);
+ msg.accessor_.setFixed64(8, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(9)) {
+ const value = requestAccessor.getSfixed32WithDefault(9);
+ msg.accessor_.setSfixed32(9, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(10)) {
+ const value = requestAccessor.getSfixed64WithDefault(10);
+ msg.accessor_.setSfixed64(10, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(11)) {
+ const value = requestAccessor.getFloatWithDefault(11);
+ msg.accessor_.setFloat(11, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(12)) {
+ const value = requestAccessor.getDoubleWithDefault(12);
+ msg.accessor_.setDouble(12, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(13)) {
+ const value = requestAccessor.getBoolWithDefault(13);
+ msg.accessor_.setBool(13, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(14)) {
+ const value = requestAccessor.getStringWithDefault(14);
+ msg.accessor_.setString(14, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(15)) {
+ const value = requestAccessor.getBytesWithDefault(15);
+ msg.accessor_.setBytes(15, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(18)) {
+ const value = requestAccessor.getMessage(
+ 18, (accessor) => new TestAllTypesProto3(accessor));
+ msg.accessor_.setMessage(18, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(21)) {
+ // Unknown enum is not checked here, because even if an enum is unknown,
+ // it should be kept during encoding. For the purpose of wire format test,
+ // we can simplify the implementation by treating it as an int32 field,
+ // which has the same semantic except for the unknown value checking.
+ const value = requestAccessor.getInt32WithDefault(21);
+ msg.accessor_.setInt32(21, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(31)) {
+ const value = requestAccessor.getRepeatedInt32Iterable(31);
+ msg.accessor_.setPackedInt32Iterable(31, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(32)) {
+ const value = requestAccessor.getRepeatedInt64Iterable(32);
+ msg.accessor_.setPackedInt64Iterable(32, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(33)) {
+ const value = requestAccessor.getRepeatedUint32Iterable(33);
+ msg.accessor_.setPackedUint32Iterable(33, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(34)) {
+ const value = requestAccessor.getRepeatedUint64Iterable(34);
+ msg.accessor_.setPackedUint64Iterable(34, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(35)) {
+ const value = requestAccessor.getRepeatedSint32Iterable(35);
+ msg.accessor_.setPackedSint32Iterable(35, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(36)) {
+ const value = requestAccessor.getRepeatedSint64Iterable(36);
+ msg.accessor_.setPackedSint64Iterable(36, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(37)) {
+ const value = requestAccessor.getRepeatedFixed32Iterable(37);
+ msg.accessor_.setPackedFixed32Iterable(37, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(38)) {
+ const value = requestAccessor.getRepeatedFixed64Iterable(38);
+ msg.accessor_.setPackedFixed64Iterable(38, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(39)) {
+ const value = requestAccessor.getRepeatedSfixed32Iterable(39);
+ msg.accessor_.setPackedSfixed32Iterable(39, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(40)) {
+ const value = requestAccessor.getRepeatedSfixed64Iterable(40);
+ msg.accessor_.setPackedSfixed64Iterable(40, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(41)) {
+ const value = requestAccessor.getRepeatedFloatIterable(41);
+ msg.accessor_.setPackedFloatIterable(41, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(42)) {
+ const value = requestAccessor.getRepeatedDoubleIterable(42);
+ msg.accessor_.setPackedDoubleIterable(42, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(43)) {
+ const value = requestAccessor.getRepeatedBoolIterable(43);
+ msg.accessor_.setPackedBoolIterable(43, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(44)) {
+ const value = requestAccessor.getRepeatedStringIterable(44);
+ msg.accessor_.setRepeatedStringIterable(44, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(45)) {
+ const value = requestAccessor.getRepeatedBytesIterable(45);
+ msg.accessor_.setRepeatedBytesIterable(45, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(48)) {
+ const value = requestAccessor.getRepeatedMessageIterable(
+ 48, (accessor) => new TestAllTypesProto3(accessor));
+ msg.accessor_.setRepeatedMessageIterable(48, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(51)) {
+ // Unknown enum is not checked here, because even if an enum is unknown,
+ // it should be kept during encoding. For the purpose of wire format test,
+ // we can simplify the implementation by treating it as an int32 field,
+ // which has the same semantic except for the unknown value checking.
+ const value = requestAccessor.getRepeatedInt32Iterable(51);
+ msg.accessor_.setPackedInt32Iterable(51, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(89)) {
+ const value = requestAccessor.getRepeatedInt32Iterable(89);
+ msg.accessor_.setUnpackedInt32Iterable(89, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(90)) {
+ const value = requestAccessor.getRepeatedInt64Iterable(90);
+ msg.accessor_.setUnpackedInt64Iterable(90, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(91)) {
+ const value = requestAccessor.getRepeatedUint32Iterable(91);
+ msg.accessor_.setUnpackedUint32Iterable(91, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(92)) {
+ const value = requestAccessor.getRepeatedUint64Iterable(92);
+ msg.accessor_.setUnpackedUint64Iterable(92, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(93)) {
+ const value = requestAccessor.getRepeatedSint32Iterable(93);
+ msg.accessor_.setUnpackedSint32Iterable(93, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(94)) {
+ const value = requestAccessor.getRepeatedSint64Iterable(94);
+ msg.accessor_.setUnpackedSint64Iterable(94, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(95)) {
+ const value = requestAccessor.getRepeatedFixed32Iterable(95);
+ msg.accessor_.setUnpackedFixed32Iterable(95, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(96)) {
+ const value = requestAccessor.getRepeatedFixed64Iterable(96);
+ msg.accessor_.setUnpackedFixed64Iterable(96, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(97)) {
+ const value = requestAccessor.getRepeatedSfixed32Iterable(97);
+ msg.accessor_.setUnpackedSfixed32Iterable(97, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(98)) {
+ const value = requestAccessor.getRepeatedSfixed64Iterable(98);
+ msg.accessor_.setUnpackedSfixed64Iterable(98, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(99)) {
+ const value = requestAccessor.getRepeatedFloatIterable(99);
+ msg.accessor_.setUnpackedFloatIterable(99, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(100)) {
+ const value = requestAccessor.getRepeatedDoubleIterable(100);
+ msg.accessor_.setUnpackedDoubleIterable(100, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(101)) {
+ const value = requestAccessor.getRepeatedBoolIterable(101);
+ msg.accessor_.setUnpackedBoolIterable(101, value);
+ }
+
+ if (requestAccessor.hasFieldNumber(102)) {
+ const value = requestAccessor.getRepeatedInt32Iterable(102);
+ msg.accessor_.setUnpackedInt32Iterable(102, value);
+ }
+
+ return msg;
+ }
+
+ /**
+ * Serializes into binary data.
+ * @return {!ArrayBuffer}
+ */
+ serialize() {
+ return this.accessor_.serialize();
+ }
+}
+
+exports = TestAllTypesProto3;
diff --git a/js/experimental/runtime/kernel/conformance/wire_format.js b/js/experimental/runtime/kernel/conformance/wire_format.js
new file mode 100644
index 0000000..636e827
--- /dev/null
+++ b/js/experimental/runtime/kernel/conformance/wire_format.js
@@ -0,0 +1,16 @@
+/**
+ * @fileoverview Handwritten code of WireFormat.
+ */
+goog.module('proto.conformance.WireFormat');
+
+/**
+ * @enum {number}
+ */
+const WireFormat = {
+ UNSPECIFIED: 0,
+ PROTOBUF: 1,
+ JSON: 2,
+ TEXT_FORMAT: 4,
+};
+
+exports = WireFormat;
diff --git a/js/experimental/runtime/kernel/double_test_pairs.js b/js/experimental/runtime/kernel/double_test_pairs.js
new file mode 100644
index 0000000..86e1f26
--- /dev/null
+++ b/js/experimental/runtime/kernel/double_test_pairs.js
@@ -0,0 +1,89 @@
+/**
+ * @fileoverview Test data for double encoding and decoding.
+ */
+goog.module('protobuf.binary.doubleTestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of double values and their bit representation.
+ * This is used to test encoding and decoding from the protobuf wire format.
+ * @return {!Array<{name: string, doubleValue:number, bufferDecoder:
+ * !BufferDecoder}>}
+ */
+function getDoublePairs() {
+ const doublePairs = [
+ {
+ name: 'zero',
+ doubleValue: 0,
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
+ },
+ {
+ name: 'minus zero',
+ doubleValue: -0,
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80)
+ },
+ {
+ name: 'one',
+ doubleValue: 1,
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F)
+ },
+ {
+ name: 'minus one',
+ doubleValue: -1,
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xBF)
+ },
+
+ {
+ name: 'PI',
+ doubleValue: Math.PI,
+ bufferDecoder:
+ createBufferDecoder(0x18, 0x2D, 0x44, 0x54, 0xFB, 0x21, 0x09, 0x40)
+
+ },
+ {
+ name: 'max value',
+ doubleValue: Number.MAX_VALUE,
+ bufferDecoder:
+ createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xEF, 0x7F)
+ },
+ {
+ name: 'min value',
+ doubleValue: Number.MIN_VALUE,
+ bufferDecoder:
+ createBufferDecoder(0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
+ },
+ {
+ name: 'Infinity',
+ doubleValue: Infinity,
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x7F)
+ },
+ {
+ name: 'minus Infinity',
+ doubleValue: -Infinity,
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF)
+ },
+ {
+ name: 'Number.MAX_SAFE_INTEGER',
+ doubleValue: Number.MAX_SAFE_INTEGER,
+ bufferDecoder:
+ createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x43)
+ },
+ {
+ name: 'Number.MIN_SAFE_INTEGER',
+ doubleValue: Number.MIN_SAFE_INTEGER,
+ bufferDecoder:
+ createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0xC3)
+ },
+ ];
+ return [...doublePairs];
+}
+
+exports = {getDoublePairs};
diff --git a/js/experimental/runtime/kernel/field.js b/js/experimental/runtime/kernel/field.js
new file mode 100644
index 0000000..46d6999
--- /dev/null
+++ b/js/experimental/runtime/kernel/field.js
@@ -0,0 +1,196 @@
+/**
+ * @fileoverview Contains classes that hold data for a protobuf field.
+ */
+
+goog.module('protobuf.binary.field');
+
+const WireType = goog.requireType('protobuf.binary.WireType');
+const Writer = goog.requireType('protobuf.binary.Writer');
+const {checkDefAndNotNull, checkState} = goog.require('protobuf.internal.checks');
+
+/**
+ * Number of bits taken to represent a wire type.
+ * @const {number}
+ */
+const WIRE_TYPE_LENGTH_BITS = 3;
+
+/** @const {number} */
+const WIRE_TYPE_EXTRACTOR = (1 << WIRE_TYPE_LENGTH_BITS) - 1;
+
+/**
+ * An IndexEntry consists of the wire type and the position of a field in the
+ * binary data. The wire type and the position are encoded into a single number
+ * to save memory, which can be decoded using Field.getWireType() and
+ * Field.getStartIndex() methods.
+ * @typedef {number}
+ */
+let IndexEntry;
+
+/**
+ * An entry containing the index into the binary data and/or the corresponding
+ * cached JS object(s) for a field.
+ * @template T
+ * @final
+ * @package
+ */
+class Field {
+ /**
+ * Creates a field and inserts the wireType and position of the first
+ * occurrence of a field.
+ * @param {!WireType} wireType
+ * @param {number} startIndex
+ * @return {!Field}
+ */
+ static fromFirstIndexEntry(wireType, startIndex) {
+ return new Field([Field.encodeIndexEntry(wireType, startIndex)]);
+ }
+
+ /**
+ * @param {T} decodedValue The cached JS object decoded from the binary data.
+ * @param {function(!Writer, number, T):void|undefined} encoder Write function
+ * to encode the cache into binary bytes.
+ * @return {!Field}
+ * @template T
+ */
+ static fromDecodedValue(decodedValue, encoder) {
+ return new Field(null, decodedValue, encoder);
+ }
+
+ /**
+ * @param {!WireType} wireType
+ * @param {number} startIndex
+ * @return {!IndexEntry}
+ */
+ static encodeIndexEntry(wireType, startIndex) {
+ return startIndex << WIRE_TYPE_LENGTH_BITS | wireType;
+ }
+
+ /**
+ * @param {!IndexEntry} indexEntry
+ * @return {!WireType}
+ */
+ static getWireType(indexEntry) {
+ return /** @type {!WireType} */ (indexEntry & WIRE_TYPE_EXTRACTOR);
+ }
+
+ /**
+ * @param {!IndexEntry} indexEntry
+ * @return {number}
+ */
+ static getStartIndex(indexEntry) {
+ return indexEntry >> WIRE_TYPE_LENGTH_BITS;
+ }
+
+ /**
+ * @param {?Array<!IndexEntry>} indexArray
+ * @param {T=} decodedValue
+ * @param {function(!Writer, number, T):void=} encoder
+ * @private
+ */
+ constructor(indexArray, decodedValue = undefined, encoder = undefined) {
+ checkState(
+ !!indexArray || decodedValue !== undefined,
+ 'At least one of indexArray and decodedValue must be set');
+
+ /** @private {?Array<!IndexEntry>} */
+ this.indexArray_ = indexArray;
+ /** @private {T|undefined} */
+ this.decodedValue_ = decodedValue;
+ // TODO: Consider storing an enum to represent encoder
+ /** @private {function(!Writer, number, T)|undefined} */
+ this.encoder_ = encoder;
+ }
+
+ /**
+ * Adds a new IndexEntry.
+ * @param {!WireType} wireType
+ * @param {number} startIndex
+ */
+ addIndexEntry(wireType, startIndex) {
+ checkDefAndNotNull(this.indexArray_)
+ .push(Field.encodeIndexEntry(wireType, startIndex));
+ }
+
+ /**
+ * Returns the array of IndexEntry.
+ * @return {?Array<!IndexEntry>}
+ */
+ getIndexArray() {
+ return this.indexArray_;
+ }
+
+ /**
+ * Caches the decoded value and sets the write function to encode cache into
+ * binary bytes.
+ * @param {T} decodedValue
+ * @param {function(!Writer, number, T):void|undefined} encoder
+ */
+ setCache(decodedValue, encoder) {
+ this.decodedValue_ = decodedValue;
+ this.encoder_ = encoder;
+ this.maybeRemoveIndexArray_();
+ }
+
+ /**
+ * If the decoded value has been set.
+ * @return {boolean}
+ */
+ hasDecodedValue() {
+ return this.decodedValue_ !== undefined;
+ }
+
+ /**
+ * Returns the cached decoded value. The value needs to be set when this
+ * method is called.
+ * @return {T}
+ */
+ getDecodedValue() {
+ // Makes sure that the decoded value in the cache has already been set. This
+ // prevents callers from doing `if (field.getDecodedValue()) {...}` to check
+ // if a value exist in the cache, because the check might return false even
+ // if the cache has a valid value set (e.g. 0 or empty string).
+ checkState(this.decodedValue_ !== undefined);
+ return this.decodedValue_;
+ }
+
+ /**
+ * Returns the write function to encode cache into binary bytes.
+ * @return {function(!Writer, number, T)|undefined}
+ */
+ getEncoder() {
+ return this.encoder_;
+ }
+
+ /**
+ * Returns a copy of the field, containing the original index entries and a
+ * shallow copy of the cache.
+ * @return {!Field}
+ */
+ shallowCopy() {
+ // Repeated fields are arrays in the cache.
+ // We have to copy the array to make sure that modifications to a repeated
+ // field (e.g. add) are not seen on a cloned accessor.
+ const copiedCache = this.hasDecodedValue() ?
+ (Array.isArray(this.getDecodedValue()) ? [...this.getDecodedValue()] :
+ this.getDecodedValue()) :
+ undefined;
+ return new Field(this.getIndexArray(), copiedCache, this.getEncoder());
+ }
+
+ /**
+ * @private
+ */
+ maybeRemoveIndexArray_() {
+ checkState(
+ this.encoder_ === undefined || this.decodedValue_ !== undefined,
+ 'Encoder exists but decoded value doesn\'t');
+ if (this.encoder_ !== undefined) {
+ this.indexArray_ = null;
+ }
+ }
+}
+
+exports = {
+ IndexEntry,
+ Field,
+};
diff --git a/js/experimental/runtime/kernel/fixed32_test_pairs.js b/js/experimental/runtime/kernel/fixed32_test_pairs.js
new file mode 100644
index 0000000..1bbab3e
--- /dev/null
+++ b/js/experimental/runtime/kernel/fixed32_test_pairs.js
@@ -0,0 +1,36 @@
+/**
+ * @fileoverview Test data for float encoding and decoding.
+ */
+goog.module('protobuf.binary.fixed32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, intValue: number, bufferDecoder:
+ * !BufferDecoder}>}
+ */
+function getFixed32Pairs() {
+ const fixed32Pairs = [
+ {
+ name: 'zero',
+ intValue: 0,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x00, 0x00),
+ },
+ {
+ name: 'one ',
+ intValue: 1,
+ bufferDecoder: createBufferDecoder(0x01, 0x00, 0x00, 0x00)
+ },
+ {
+ name: 'max int 2^32 -1',
+ intValue: Math.pow(2, 32) - 1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF)
+ },
+ ];
+ return [...fixed32Pairs];
+}
+
+exports = {getFixed32Pairs};
diff --git a/js/experimental/runtime/kernel/float_test_pairs.js b/js/experimental/runtime/kernel/float_test_pairs.js
new file mode 100644
index 0000000..816bdc2
--- /dev/null
+++ b/js/experimental/runtime/kernel/float_test_pairs.js
@@ -0,0 +1,78 @@
+/**
+ * @fileoverview Test data for float encoding and decoding.
+ */
+goog.module('protobuf.binary.floatTestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, floatValue:number, bufferDecoder:
+ * !BufferDecoder}>}
+ */
+function getFloatPairs() {
+ const floatPairs = [
+ {
+ name: 'zero',
+ floatValue: 0,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x00, 0x00),
+ },
+ {
+ name: 'minus zero',
+ floatValue: -0,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x00, 0x80)
+ },
+ {
+ name: 'one ',
+ floatValue: 1,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x80, 0x3F)
+ },
+ {
+ name: 'minus one',
+ floatValue: -1,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x80, 0xBF)
+ },
+ {
+ name: 'two',
+ floatValue: 2,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x00, 0x40)
+ },
+ {
+ name: 'max float32',
+ floatValue: Math.pow(2, 127) * (2 - 1 / Math.pow(2, 23)),
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0x7F, 0x7F)
+ },
+
+ {
+ name: 'min float32',
+ floatValue: 1 / Math.pow(2, 127 - 1),
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x80, 0x00)
+ },
+
+ {
+ name: 'Infinity',
+ floatValue: Infinity,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x80, 0x7F)
+ },
+ {
+ name: 'minus Infinity',
+ floatValue: -Infinity,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x80, 0xFF)
+ },
+ {
+ name: '1.5',
+ floatValue: 1.5,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0xC0, 0x3F)
+ },
+ {
+ name: '1.6',
+ floatValue: 1.6,
+ bufferDecoder: createBufferDecoder(0xCD, 0xCC, 0xCC, 0x3F)
+ },
+ ];
+ return [...floatPairs];
+}
+
+exports = {getFloatPairs};
diff --git a/js/experimental/runtime/kernel/indexer.js b/js/experimental/runtime/kernel/indexer.js
new file mode 100644
index 0000000..205a34e
--- /dev/null
+++ b/js/experimental/runtime/kernel/indexer.js
@@ -0,0 +1,55 @@
+/**
+ * @fileoverview Utilities to index a binary proto by fieldnumbers without
+ * relying on strutural proto information.
+ */
+goog.module('protobuf.binary.indexer');
+
+const BinaryStorage = goog.require('protobuf.runtime.BinaryStorage');
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const WireType = goog.require('protobuf.binary.WireType');
+const {Field} = goog.require('protobuf.binary.field');
+const {checkCriticalState} = goog.require('protobuf.internal.checks');
+const {skipField, tagToFieldNumber, tagToWireType} = goog.require('protobuf.binary.tag');
+
+/**
+ * Appends a new entry in the index array for the given field number.
+ * @param {!BinaryStorage<!Field>} storage
+ * @param {number} fieldNumber
+ * @param {!WireType} wireType
+ * @param {number} startIndex
+ */
+function addIndexEntry(storage, fieldNumber, wireType, startIndex) {
+ const field = storage.get(fieldNumber);
+ if (field !== undefined) {
+ field.addIndexEntry(wireType, startIndex);
+ } else {
+ storage.set(fieldNumber, Field.fromFirstIndexEntry(wireType, startIndex));
+ }
+}
+
+/**
+ * Creates an index of field locations in a given binary protobuf.
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {number|undefined} pivot
+ * @return {!BinaryStorage<!Field>}
+ * @package
+ */
+function buildIndex(bufferDecoder, pivot) {
+ bufferDecoder.setCursor(bufferDecoder.startIndex());
+
+ const storage = new BinaryStorage(pivot);
+ while (bufferDecoder.hasNext()) {
+ const tag = bufferDecoder.getUnsignedVarint32();
+ const wireType = tagToWireType(tag);
+ const fieldNumber = tagToFieldNumber(tag);
+ checkCriticalState(fieldNumber > 0, `Invalid field number ${fieldNumber}`);
+ addIndexEntry(storage, fieldNumber, wireType, bufferDecoder.cursor());
+ skipField(bufferDecoder, wireType, fieldNumber);
+ }
+ return storage;
+}
+
+exports = {
+ buildIndex,
+ tagToWireType,
+};
diff --git a/js/experimental/runtime/kernel/indexer_test.js b/js/experimental/runtime/kernel/indexer_test.js
new file mode 100644
index 0000000..ffb8807
--- /dev/null
+++ b/js/experimental/runtime/kernel/indexer_test.js
@@ -0,0 +1,334 @@
+/**
+ * @fileoverview Tests for indexer.js.
+ */
+goog.module('protobuf.binary.IndexerTest');
+
+goog.setTestOnly();
+
+// Note to the reader:
+// Since the index behavior changes with the checking level some of the tests
+// in this file have to know which checking level is enabled to make correct
+// assertions.
+// Test are run in all checking levels.
+const BinaryStorage = goog.require('protobuf.runtime.BinaryStorage');
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const WireType = goog.require('protobuf.binary.WireType');
+const {CHECK_CRITICAL_STATE} = goog.require('protobuf.internal.checks');
+const {Field, IndexEntry} = goog.require('protobuf.binary.field');
+const {buildIndex} = goog.require('protobuf.binary.indexer');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * Returns the number of fields stored.
+ *
+ * @param {!BinaryStorage} storage
+ * @return {number}
+ */
+function getStorageSize(storage) {
+ let size = 0;
+ storage.forEach(() => void size++);
+ return size;
+}
+
+/**
+ * @type {number}
+ */
+const PIVOT = 1;
+
+/**
+ * Asserts a single IndexEntry at a given field number.
+ * @param {!BinaryStorage} storage
+ * @param {number} fieldNumber
+ * @param {...!IndexEntry} expectedEntries
+ */
+function assertStorageEntries(storage, fieldNumber, ...expectedEntries) {
+ expect(getStorageSize(storage)).toBe(1);
+
+ const entryArray = storage.get(fieldNumber).getIndexArray();
+ expect(entryArray).not.toBeUndefined();
+ expect(entryArray.length).toBe(expectedEntries.length);
+
+ for (let i = 0; i < entryArray.length; i++) {
+ const storageEntry = entryArray[i];
+ const expectedEntry = expectedEntries[i];
+
+ expect(storageEntry).toBe(expectedEntry);
+ }
+}
+
+describe('Indexer does', () => {
+ it('return empty storage for empty array', () => {
+ const storage = buildIndex(createBufferDecoder(), PIVOT);
+ expect(storage).not.toBeNull();
+ expect(getStorageSize(storage)).toBe(0);
+ });
+
+ it('throw for null array', () => {
+ expect(
+ () => buildIndex(
+ /** @type {!BufferDecoder} */ (/** @type {*} */ (null)), PIVOT))
+ .toThrow();
+ });
+
+ it('fail for invalid wire type (6)', () => {
+ expect(() => buildIndex(createBufferDecoder(0x0E, 0x01), PIVOT))
+ .toThrowError('Unexpected wire type: 6');
+ });
+
+ it('fail for invalid wire type (7)', () => {
+ expect(() => buildIndex(createBufferDecoder(0x0F, 0x01), PIVOT))
+ .toThrowError('Unexpected wire type: 7');
+ });
+
+ it('index varint', () => {
+ const data = createBufferDecoder(0x08, 0x01, 0x08, 0x01);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 1),
+ Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 3));
+ });
+
+ it('index varint with two bytes field number', () => {
+ const data = createBufferDecoder(0xF8, 0x01, 0x01);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 31,
+ Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 2));
+ });
+
+ it('fail for varints that are longer than 10 bytes', () => {
+ const data = createBufferDecoder(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Index out of bounds: index: 12 size: 11');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 1));
+ }
+ });
+
+ it('fail for varints with no data', () => {
+ const data = createBufferDecoder(0x08);
+ expect(() => buildIndex(data, PIVOT)).toThrow();
+ });
+
+ it('index fixed64', () => {
+ const data = createBufferDecoder(
+ /* first= */ 0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ /* second= */ 0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 1),
+ Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 10));
+ });
+
+ it('fail for fixed64 data missing in input', () => {
+ const data =
+ createBufferDecoder(0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Index out of bounds: index: 9 size: 8');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 1));
+ }
+ });
+
+ it('fail for fixed64 tag that has no data after it', () => {
+ if (CHECK_CRITICAL_STATE) {
+ const data = createBufferDecoder(0x09);
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Index out of bounds: index: 9 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const data = createBufferDecoder(0x09);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 1));
+ }
+ });
+
+ it('index delimited', () => {
+ const data = createBufferDecoder(
+ /* first= */ 0x0A, 0x02, 0x00, 0x01, /* second= */ 0x0A, 0x02, 0x00,
+ 0x01);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.DELIMITED, /* startIndex= */ 1),
+ Field.encodeIndexEntry(WireType.DELIMITED, /* startIndex= */ 5));
+ });
+
+ it('fail for length deliimted field data missing in input', () => {
+ const data = createBufferDecoder(0x0A, 0x04, 0x00, 0x01);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Index out of bounds: index: 6 size: 4');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.DELIMITED, /* startIndex= */ 1));
+ }
+ });
+
+ it('fail for delimited tag that has no data after it', () => {
+ const data = createBufferDecoder(0x0A);
+ expect(() => buildIndex(data, PIVOT)).toThrow();
+ });
+
+ it('index fixed32', () => {
+ const data = createBufferDecoder(
+ /* first= */ 0x0D, 0x01, 0x02, 0x03, 0x04, /* second= */ 0x0D, 0x01,
+ 0x02, 0x03, 0x04);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 1),
+ Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 6));
+ });
+
+ it('fail for fixed32 data missing in input', () => {
+ const data = createBufferDecoder(0x0D, 0x01, 0x02, 0x03);
+
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Index out of bounds: index: 5 size: 4');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 1));
+ }
+ });
+
+ it('fail for fixed32 tag that has no data after it', () => {
+ if (CHECK_CRITICAL_STATE) {
+ const data = createBufferDecoder(0x0D);
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Index out of bounds: index: 5 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const data = createBufferDecoder(0x0D);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 1));
+ }
+ });
+
+ it('index group', () => {
+ const data = createBufferDecoder(
+ /* first= */ 0x0B, 0x08, 0x01, 0x0C, /* second= */ 0x0B, 0x08, 0x01,
+ 0x0C);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1),
+ Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 5));
+ });
+
+ it('index group and skips inner group', () => {
+ const data =
+ createBufferDecoder(0x0B, 0x0B, 0x08, 0x01, 0x0C, 0x08, 0x01, 0x0C);
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1));
+ });
+
+ it('fail on unmatched stop group', () => {
+ const data = createBufferDecoder(0x0C, 0x01);
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Unexpected wire type: 4');
+ });
+
+ it('fail for groups without matching stop group', () => {
+ const data = createBufferDecoder(0x0B, 0x08, 0x01, 0x1C);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => buildIndex(data, PIVOT))
+ .toThrowError('Expected stop group for fieldnumber 1 not found.');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1));
+ }
+ });
+
+ it('fail for groups without stop group', () => {
+ const data = createBufferDecoder(0x0B, 0x08, 0x01);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => buildIndex(data, PIVOT)).toThrowError('No end group found.');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1));
+ }
+ });
+
+ it('fail for group tag that has no data after it', () => {
+ const data = createBufferDecoder(0x0B);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => buildIndex(data, PIVOT)).toThrowError('No end group found.');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const storage = buildIndex(data, PIVOT);
+ assertStorageEntries(
+ storage, /* fieldNumber= */ 1,
+ Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1));
+ }
+ });
+
+ it('index too large tag', () => {
+ const data = createBufferDecoder(0xF8, 0xFF, 0xFF, 0xFF, 0xFF);
+ expect(() => buildIndex(data, PIVOT)).toThrow();
+ });
+
+ it('fail for varint tag that has no data after it', () => {
+ const data = createBufferDecoder(0x08);
+ expect(() => buildIndex(data, PIVOT)).toThrow();
+ });
+});
diff --git a/js/experimental/runtime/kernel/int32_test_pairs.js b/js/experimental/runtime/kernel/int32_test_pairs.js
new file mode 100644
index 0000000..ef4f2e9
--- /dev/null
+++ b/js/experimental/runtime/kernel/int32_test_pairs.js
@@ -0,0 +1,71 @@
+/**
+ * @fileoverview Test data for int32 encoding and decoding.
+ */
+goog.module('protobuf.binary.int32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, intValue:number, bufferDecoder:
+ * !BufferDecoder, error: ?boolean, skip_writer: ?boolean}>}
+ */
+function getInt32Pairs() {
+ const int32Pairs = [
+ {
+ name: 'zero',
+ intValue: 0,
+ bufferDecoder: createBufferDecoder(0x00),
+ },
+ {
+ name: 'one ',
+ intValue: 1,
+ bufferDecoder: createBufferDecoder(0x01),
+ },
+ {
+ name: 'minus one',
+ intValue: -1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0x0F),
+ // The writer will encode this with 64 bits, see below
+ skip_writer: true,
+ },
+ {
+ name: 'minus one (64bits)',
+ intValue: -1,
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ },
+ {
+ name: 'max signed int 2^31 - 1',
+ intValue: Math.pow(2, 31) - 1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0x07),
+
+ },
+ {
+ name: 'min signed int -2^31',
+ intValue: -Math.pow(2, 31),
+ bufferDecoder: createBufferDecoder(0x80, 0x80, 0x80, 0x80, 0x08),
+ // The writer will encode this with 64 bits, see below
+ skip_writer: true,
+ },
+ {
+ name: 'value min signed int -2^31 (64 bit)',
+ intValue: -Math.pow(2, 31),
+ bufferDecoder: createBufferDecoder(
+ 0x80, 0x80, 0x80, 0x80, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ },
+ {
+ name: 'errors out for 11 bytes',
+ intValue: -1,
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF),
+ error: true,
+ skip_writer: true,
+ },
+ ];
+ return [...int32Pairs];
+}
+
+exports = {getInt32Pairs};
diff --git a/js/experimental/runtime/kernel/int64_test_pairs.js b/js/experimental/runtime/kernel/int64_test_pairs.js
new file mode 100644
index 0000000..19ef46b
--- /dev/null
+++ b/js/experimental/runtime/kernel/int64_test_pairs.js
@@ -0,0 +1,59 @@
+/**
+ * @fileoverview Test data for int64 encoding and decoding.
+ */
+goog.module('protobuf.binary.int64TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const Int64 = goog.require('protobuf.Int64');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, longValue: !Int64, bufferDecoder:
+ * !BufferDecoder, error: ?boolean, skip_writer: ?boolean}>}
+ */
+function getInt64Pairs() {
+ const int64Pairs = [
+ {
+ name: 'zero',
+ longValue: Int64.fromInt(0),
+ bufferDecoder: createBufferDecoder(0x00),
+ },
+ {
+ name: 'one ',
+ longValue: Int64.fromInt(1),
+ bufferDecoder: createBufferDecoder(0x01),
+ },
+ {
+ name: 'minus one',
+ longValue: Int64.fromInt(-1),
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ },
+ {
+ name: 'max signed int 2^63 - 1',
+ longValue: Int64.fromBits(0xFFFFFFFF, 0x7FFFFFFF),
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F),
+
+ },
+ {
+ name: 'value min signed int -2^63 (64 bit)',
+ longValue: Int64.fromBits(0xFFFFFFFF, 0xFFFFFFFF),
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ },
+ {
+ name: 'errors out for 11 bytes',
+ longValue: Int64.fromInt(-1),
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF),
+ error: true,
+ skip_writer: true,
+ },
+ ];
+ return [...int64Pairs];
+}
+
+exports = {getInt64Pairs};
diff --git a/js/experimental/runtime/kernel/internal_message.js b/js/experimental/runtime/kernel/internal_message.js
new file mode 100644
index 0000000..1ba9ed9
--- /dev/null
+++ b/js/experimental/runtime/kernel/internal_message.js
@@ -0,0 +1,24 @@
+/**
+ * @fileoverview Internal interface for messages implemented with the binary
+ * kernel.
+ */
+goog.module('protobuf.binary.InternalMessage');
+
+const Kernel = goog.requireType('protobuf.runtime.Kernel');
+
+/**
+ * Interface that needs to be implemented by messages implemented with the
+ * binary kernel. This is an internal only interface and should be used only by
+ * the classes in binary kernel.
+ *
+ * @interface
+ */
+class InternalMessage {
+ /**
+ * @package
+ * @return {!Kernel}
+ */
+ internalGetKernel() {}
+}
+
+exports = InternalMessage;
\ No newline at end of file
diff --git a/js/experimental/runtime/kernel/kernel.js b/js/experimental/runtime/kernel/kernel.js
new file mode 100644
index 0000000..bb26083
--- /dev/null
+++ b/js/experimental/runtime/kernel/kernel.js
@@ -0,0 +1,4122 @@
+/**
+ * @fileoverview Kernel is a class to provide type-checked accessing
+ * (read/write bool/int32/string/...) on binary data.
+ *
+ * When creating the Kernel with the binary data, there is no deep
+ * decoding done (which requires full type information). The deep decoding is
+ * deferred until the first time accessing (when accessors can provide
+ * full type information).
+ *
+ * Because accessors can be statically analyzed and stripped, unlike eager
+ * binary decoding (which requires the full type information of all defined
+ * fields), Kernel will only need the full type information of used
+ * fields.
+ */
+goog.module('protobuf.runtime.Kernel');
+
+const BinaryStorage = goog.require('protobuf.runtime.BinaryStorage');
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const InternalMessage = goog.require('protobuf.binary.InternalMessage');
+const Storage = goog.require('protobuf.runtime.Storage');
+const WireType = goog.require('protobuf.binary.WireType');
+const Writer = goog.require('protobuf.binary.Writer');
+const reader = goog.require('protobuf.binary.reader');
+const {CHECK_TYPE, checkCriticalElementIndex, checkCriticalState, checkCriticalType, checkCriticalTypeBool, checkCriticalTypeBoolArray, checkCriticalTypeByteString, checkCriticalTypeByteStringArray, checkCriticalTypeDouble, checkCriticalTypeDoubleArray, checkCriticalTypeFloat, checkCriticalTypeFloatIterable, checkCriticalTypeMessageArray, checkCriticalTypeSignedInt32, checkCriticalTypeSignedInt32Array, checkCriticalTypeSignedInt64, checkCriticalTypeSignedInt64Array, checkCriticalTypeString, checkCriticalTypeStringArray, checkCriticalTypeUnsignedInt32, checkCriticalTypeUnsignedInt32Array, checkDefAndNotNull, checkElementIndex, checkFieldNumber, checkFunctionExists, checkState, checkTypeDouble, checkTypeFloat, checkTypeSignedInt32, checkTypeSignedInt64, checkTypeUnsignedInt32} = goog.require('protobuf.internal.checks');
+const {Field, IndexEntry} = goog.require('protobuf.binary.field');
+const {buildIndex} = goog.require('protobuf.binary.indexer');
+const {createTag, get32BitVarintLength, getTagLength} = goog.require('protobuf.binary.tag');
+
+
+/**
+ * Validates the index entry has the correct wire type.
+ * @param {!IndexEntry} indexEntry
+ * @param {!WireType} expected
+ */
+function validateWireType(indexEntry, expected) {
+ const wireType = Field.getWireType(indexEntry);
+ checkCriticalState(
+ wireType === expected,
+ `Expected wire type: ${expected} but found: ${wireType}`);
+}
+
+/**
+ * Checks if the object implements InternalMessage interface.
+ * @param {?} obj
+ * @return {!InternalMessage}
+ */
+function checkIsInternalMessage(obj) {
+ const message = /** @type {!InternalMessage} */ (obj);
+ checkFunctionExists(message.internalGetKernel);
+ return message;
+}
+
+/**
+ * Checks if the instanceCreator returns an instance that implements the
+ * InternalMessage interface.
+ * @param {function(!Kernel):T} instanceCreator
+ * @template T
+ */
+function checkInstanceCreator(instanceCreator) {
+ if (CHECK_TYPE) {
+ const emptyMessage = instanceCreator(Kernel.createEmpty());
+ checkFunctionExists(emptyMessage.internalGetKernel);
+ }
+}
+
+/**
+ * Reads the last entry of the index array using the given read function.
+ * This is used to implement parsing singular primitive fields.
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {function(!BufferDecoder, number):T} readFunc
+ * @param {!WireType} wireType
+ * @return {T}
+ * @template T
+ */
+function readOptional(indexArray, bufferDecoder, readFunc, wireType) {
+ const index = indexArray.length - 1;
+ checkElementIndex(index, indexArray.length);
+ const indexEntry = indexArray[index];
+ validateWireType(indexEntry, wireType);
+ return readFunc(bufferDecoder, Field.getStartIndex(indexEntry));
+}
+
+/**
+ * Converts all entries of the index array to the template type using given read
+ * methods and return an Iterable containing those converted values.
+ * Primitive repeated fields may be encoded either packed or unpacked. Thus, two
+ * read methods are needed for those two cases.
+ * This is used to implement parsing repeated primitive fields.
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {function(!BufferDecoder, number):T} singularReadFunc
+ * @param {function(!BufferDecoder, number):!Array<T>} packedReadFunc
+ * @param {!WireType} expectedWireType
+ * @return {!Array<T>}
+ * @template T
+ */
+function readRepeatedPrimitive(
+ indexArray, bufferDecoder, singularReadFunc, packedReadFunc,
+ expectedWireType) {
+ // Fast path when there is a single packed entry.
+ if (indexArray.length === 1 &&
+ Field.getWireType(indexArray[0]) === WireType.DELIMITED) {
+ return packedReadFunc(bufferDecoder, Field.getStartIndex(indexArray[0]));
+ }
+
+ let /** !Array<T> */ result = [];
+ for (const indexEntry of indexArray) {
+ const wireType = Field.getWireType(indexEntry);
+ const startIndex = Field.getStartIndex(indexEntry);
+ if (wireType === WireType.DELIMITED) {
+ result = result.concat(packedReadFunc(bufferDecoder, startIndex));
+ } else {
+ validateWireType(indexEntry, expectedWireType);
+ result.push(singularReadFunc(bufferDecoder, startIndex));
+ }
+ }
+ return result;
+}
+
+/**
+ * Converts all entries of the index array to the template type using the given
+ * read function and return an Array containing those converted values. This is
+ * used to implement parsing repeated non-primitive fields.
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {function(!BufferDecoder, number):T} singularReadFunc
+ * @return {!Array<T>}
+ * @template T
+ */
+function readRepeatedNonPrimitive(indexArray, bufferDecoder, singularReadFunc) {
+ const result = new Array(indexArray.length);
+ for (let i = 0; i < indexArray.length; i++) {
+ validateWireType(indexArray[i], WireType.DELIMITED);
+ result[i] =
+ singularReadFunc(bufferDecoder, Field.getStartIndex(indexArray[i]));
+ }
+ return result;
+}
+
+/**
+ * Converts all entries of the index array to the template type using the given
+ * read function and return an Array containing those converted values. This is
+ * used to implement parsing repeated non-primitive fields.
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {!Array<T>}
+ * @template T
+ */
+function readRepeatedGroup(
+ indexArray, bufferDecoder, fieldNumber, instanceCreator, pivot) {
+ const result = new Array(indexArray.length);
+ for (let i = 0; i < indexArray.length; i++) {
+ result[i] = doReadGroup(
+ bufferDecoder, indexArray[i], fieldNumber, instanceCreator, pivot);
+ }
+ return result;
+}
+
+/**
+ * Creates a new bytes array to contain all data of a submessage.
+ * When there are multiple entries, merge them together.
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @return {!BufferDecoder}
+ */
+function mergeMessageArrays(indexArray, bufferDecoder) {
+ const dataArrays = indexArray.map(
+ indexEntry =>
+ reader.readDelimited(bufferDecoder, Field.getStartIndex(indexEntry)));
+ return BufferDecoder.merge(dataArrays);
+}
+
+/**
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {number=} pivot
+ * @return {!Kernel}
+ */
+function readAccessor(indexArray, bufferDecoder, pivot = undefined) {
+ checkState(indexArray.length > 0);
+ let accessorBuffer;
+ // Faster access for one member.
+ if (indexArray.length === 1) {
+ const indexEntry = indexArray[0];
+ validateWireType(indexEntry, WireType.DELIMITED);
+ accessorBuffer =
+ reader.readDelimited(bufferDecoder, Field.getStartIndex(indexEntry));
+ } else {
+ indexArray.forEach(indexEntry => {
+ validateWireType(indexEntry, WireType.DELIMITED);
+ });
+ accessorBuffer = mergeMessageArrays(indexArray, bufferDecoder);
+ }
+ return Kernel.fromBufferDecoder_(accessorBuffer, pivot);
+}
+
+/**
+ * Merges all index entries of the index array using the given read function.
+ * This is used to implement parsing singular message fields.
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+function readMessage(indexArray, bufferDecoder, instanceCreator, pivot) {
+ checkInstanceCreator(instanceCreator);
+ const accessor = readAccessor(indexArray, bufferDecoder, pivot);
+ return instanceCreator(accessor);
+}
+
+/**
+ * Merges all index entries of the index array using the given read function.
+ * This is used to implement parsing singular group fields.
+ * @param {!Array<!IndexEntry>} indexArray
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+function readGroup(
+ indexArray, bufferDecoder, fieldNumber, instanceCreator, pivot) {
+ checkInstanceCreator(instanceCreator);
+ checkState(indexArray.length > 0);
+ return doReadGroup(
+ bufferDecoder, indexArray[indexArray.length - 1], fieldNumber,
+ instanceCreator, pivot);
+}
+
+/**
+ * Merges all index entries of the index array using the given read function.
+ * This is used to implement parsing singular message fields.
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {!IndexEntry} indexEntry
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+function doReadGroup(
+ bufferDecoder, indexEntry, fieldNumber, instanceCreator, pivot) {
+ validateWireType(indexEntry, WireType.START_GROUP);
+ const fieldStartIndex = Field.getStartIndex(indexEntry);
+ const tag = createTag(WireType.START_GROUP, fieldNumber);
+ const groupTagLength = get32BitVarintLength(tag);
+ const groupLength = getTagLength(
+ bufferDecoder, fieldStartIndex, WireType.START_GROUP, fieldNumber);
+ const accessorBuffer = bufferDecoder.subBufferDecoder(
+ fieldStartIndex, groupLength - groupTagLength);
+ const kernel = Kernel.fromBufferDecoder_(accessorBuffer, pivot);
+ return instanceCreator(kernel);
+}
+
+/**
+ * @param {!Writer} writer
+ * @param {number} fieldNumber
+ * @param {?InternalMessage} value
+ */
+function writeMessage(writer, fieldNumber, value) {
+ writer.writeDelimited(
+ fieldNumber, checkDefAndNotNull(value).internalGetKernel().serialize());
+}
+
+/**
+ * @param {!Writer} writer
+ * @param {number} fieldNumber
+ * @param {?InternalMessage} value
+ */
+function writeGroup(writer, fieldNumber, value) {
+ const kernel = checkDefAndNotNull(value).internalGetKernel();
+ writer.writeStartGroup(fieldNumber);
+ kernel.serializeToWriter(writer);
+ writer.writeEndGroup(fieldNumber);
+}
+
+/**
+ * Writes the array of Messages into the writer for the given field number.
+ * @param {!Writer} writer
+ * @param {number} fieldNumber
+ * @param {!Iterable<!InternalMessage>} values
+ */
+function writeRepeatedMessage(writer, fieldNumber, values) {
+ for (const value of values) {
+ writeMessage(writer, fieldNumber, value);
+ }
+}
+
+/**
+ * Writes the array of Messages into the writer for the given field number.
+ * @param {!Writer} writer
+ * @param {number} fieldNumber
+ * @param {!Array<!InternalMessage>} values
+ */
+function writeRepeatedGroup(writer, fieldNumber, values) {
+ for (const value of values) {
+ writeGroup(writer, fieldNumber, value);
+ }
+}
+
+/**
+ * Array.from has a weird type definition in google3/javascript/externs/es6.js
+ * and wants the mapping function accept strings.
+ * @const {function((string|number)): number}
+ */
+const fround = /** @type {function((string|number)): number} */ (Math.fround);
+
+/**
+ * Wraps an array and exposes it as an Iterable. This class is used to provide
+ * immutable access of the array to the caller.
+ * @implements {Iterable<T>}
+ * @template T
+ */
+class ArrayIterable {
+ /**
+ * @param {!Array<T>} array
+ */
+ constructor(array) {
+ /** @private @const {!Array<T>} */
+ this.array_ = array;
+ }
+
+ /** @return {!Iterator<T>} */
+ [Symbol.iterator]() {
+ return this.array_[Symbol.iterator]();
+ }
+}
+
+/**
+ * Accesses protobuf fields on binary format data. Binary data is decoded lazily
+ * at the first access.
+ * @final
+ */
+class Kernel {
+ /**
+ * Create a Kernel for the given binary bytes.
+ * The bytes array is kept by the Kernel. DON'T MODIFY IT.
+ * @param {!ArrayBuffer} arrayBuffer Binary bytes.
+ * @param {number=} pivot Fields with a field number no greater than the pivot
+ * value will be stored in an array for fast access. Other fields will be
+ * stored in a map. A higher pivot value can improve runtime performance
+ * at the expense of requiring more memory. It's recommended to set the
+ * value to the max field number of the message unless the field numbers
+ * are too sparse. If the value is not set, a default value specified in
+ * storage.js will be used.
+ * @return {!Kernel}
+ */
+ static fromArrayBuffer(arrayBuffer, pivot = undefined) {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(arrayBuffer);
+ return Kernel.fromBufferDecoder_(bufferDecoder, pivot);
+ }
+
+ /**
+ * Creates an empty Kernel.
+ * @param {number=} pivot Fields with a field number no greater than the pivot
+ * value will be stored in an array for fast access. Other fields will be
+ * stored in a map. A higher pivot value can improve runtime performance
+ * at the expense of requiring more memory. It's recommended to set the
+ * value to the max field number of the message unless the field numbers
+ * are too sparse. If the value is not set, a default value specified in
+ * storage.js will be used.
+ * @return {!Kernel}
+ */
+ static createEmpty(pivot = undefined) {
+ return new Kernel(/* bufferDecoder= */ null, new BinaryStorage(pivot));
+ }
+
+ /**
+ * Create a Kernel for the given binary bytes.
+ * The bytes array is kept by the Kernel. DON'T MODIFY IT.
+ * @param {!BufferDecoder} bufferDecoder Binary bytes.
+ * @param {number|undefined} pivot
+ * @return {!Kernel}
+ * @private
+ */
+ static fromBufferDecoder_(bufferDecoder, pivot) {
+ return new Kernel(bufferDecoder, buildIndex(bufferDecoder, pivot));
+ }
+
+ /**
+ * @param {?BufferDecoder} bufferDecoder Binary bytes. Accessor treats the
+ * bytes as immutable and will never attempt to write to it.
+ * @param {!Storage<!Field>} fields A map of field number to Field. The
+ * IndexEntry in each Field needs to be populated with the location of the
+ * field in the binary data.
+ * @private
+ */
+ constructor(bufferDecoder, fields) {
+ /** @private @const {?BufferDecoder} */
+ this.bufferDecoder_ = bufferDecoder;
+ /** @private @const {!Storage<!Field>} */
+ this.fields_ = fields;
+ }
+
+ /**
+ * Creates a shallow copy of the accessor.
+ * @return {!Kernel}
+ */
+ shallowCopy() {
+ return new Kernel(this.bufferDecoder_, this.fields_.shallowCopy());
+ }
+
+ /**
+ * See definition of the pivot parameter on the fromArrayBuffer() method.
+ * @return {number}
+ */
+ getPivot() {
+ return this.fields_.getPivot();
+ }
+
+ /**
+ * Clears the field for the given field number.
+ * @param {number} fieldNumber
+ */
+ clearField(fieldNumber) {
+ this.fields_.delete(fieldNumber);
+ }
+
+ /**
+ * Returns data for a field specified by the given field number. Also cache
+ * the data if it doesn't already exist in the cache. When no data is
+ * available, return the given default value.
+ * @param {number} fieldNumber
+ * @param {?T} defaultValue
+ * @param {function(!Array<!IndexEntry>, !BufferDecoder):T} readFunc
+ * @param {function(!Writer, number, T)=} encoder
+ * @return {T}
+ * @template T
+ * @private
+ */
+ getFieldWithDefault_(
+ fieldNumber, defaultValue, readFunc, encoder = undefined) {
+ checkFieldNumber(fieldNumber);
+
+ const field = this.fields_.get(fieldNumber);
+ if (field === undefined) {
+ return defaultValue;
+ }
+
+ if (field.hasDecodedValue()) {
+ checkState(!encoder || !!field.getEncoder());
+ return field.getDecodedValue();
+ }
+
+ const parsed = readFunc(
+ checkDefAndNotNull(field.getIndexArray()),
+ checkDefAndNotNull(this.bufferDecoder_));
+ field.setCache(parsed, encoder);
+ return parsed;
+ }
+
+ /**
+ * Sets data for a singular field specified by the given field number.
+ * @param {number} fieldNumber
+ * @param {T} value
+ * @param {function(!Writer, number, T)} encoder
+ * @return {T}
+ * @template T
+ * @private
+ */
+ setField_(fieldNumber, value, encoder) {
+ checkFieldNumber(fieldNumber);
+ this.fields_.set(fieldNumber, Field.fromDecodedValue(value, encoder));
+ }
+
+ /**
+ * Serializes internal contents to binary format bytes array to the
+ * given writer.
+ * @param {!Writer} writer
+ * @package
+ */
+ serializeToWriter(writer) {
+ // If we use for...of here, jscompiler returns an array of both types for
+ // fieldNumber and field without specifying which type is for
+ // field, which prevents us to use fieldNumber. Thus, we use
+ // forEach here.
+ this.fields_.forEach((field, fieldNumber) => {
+ // If encoder doesn't exist, there is no need to encode the value
+ // because the data in the index is still valid.
+ if (field.getEncoder() !== undefined) {
+ const encoder = checkDefAndNotNull(field.getEncoder());
+ encoder(writer, fieldNumber, field.getDecodedValue());
+ return;
+ }
+
+ const indexArr = field.getIndexArray();
+ if (indexArr) {
+ for (const indexEntry of indexArr) {
+ writer.writeTag(fieldNumber, Field.getWireType(indexEntry));
+ writer.writeBufferDecoder(
+ checkDefAndNotNull(this.bufferDecoder_),
+ Field.getStartIndex(indexEntry), Field.getWireType(indexEntry),
+ fieldNumber);
+ }
+ }
+ });
+ }
+
+ /**
+ * Serializes internal contents to binary format bytes array.
+ * @return {!ArrayBuffer}
+ */
+ serialize() {
+ const writer = new Writer();
+ this.serializeToWriter(writer);
+ return writer.getAndResetResultBuffer();
+ }
+
+ /**
+ * Returns whether data exists at the given field number.
+ * @param {number} fieldNumber
+ * @return {boolean}
+ */
+ hasFieldNumber(fieldNumber) {
+ checkFieldNumber(fieldNumber);
+ const field = this.fields_.get(fieldNumber);
+
+ if (field === undefined) {
+ return false;
+ }
+
+ if (field.getIndexArray() !== null) {
+ return true;
+ }
+
+ if (Array.isArray(field.getDecodedValue())) {
+ // For repeated fields, existence is decided by number of elements.
+ return (/** !Array<?> */ (field.getDecodedValue())).length > 0;
+ }
+ return true;
+ }
+
+ /***************************************************************************
+ * OPTIONAL GETTER METHODS
+ ***************************************************************************/
+
+ /**
+ * Returns data as boolean for the given field number.
+ * If no default is given, use false as the default.
+ * @param {number} fieldNumber
+ * @param {boolean=} defaultValue
+ * @return {boolean}
+ */
+ getBoolWithDefault(fieldNumber, defaultValue = false) {
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) =>
+ readOptional(indexArray, bytes, reader.readBool, WireType.VARINT));
+ }
+
+ /**
+ * Returns data as a ByteString for the given field number.
+ * If no default is given, use false as the default.
+ * @param {number} fieldNumber
+ * @param {!ByteString=} defaultValue
+ * @return {!ByteString}
+ */
+ getBytesWithDefault(fieldNumber, defaultValue = ByteString.EMPTY) {
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readBytes, WireType.DELIMITED));
+ }
+
+ /**
+ * Returns a double for the given field number.
+ * If no default is given uses zero as the default.
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getDoubleWithDefault(fieldNumber, defaultValue = 0) {
+ checkTypeDouble(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readDouble, WireType.FIXED64));
+ }
+
+ /**
+ * Returns a fixed32 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getFixed32WithDefault(fieldNumber, defaultValue = 0) {
+ checkTypeUnsignedInt32(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readFixed32, WireType.FIXED32));
+ }
+
+ /**
+ * Returns a fixed64 for the given field number.
+ * Note: Since g.m.Long does not support unsigned int64 values we are going
+ * the Java route here for now and simply output the number as a signed int64.
+ * Users can get to individual bits by themselves.
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getFixed64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ return this.getSfixed64WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * Returns a float for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getFloatWithDefault(fieldNumber, defaultValue = 0) {
+ checkTypeFloat(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readFloat, WireType.FIXED32));
+ }
+
+ /**
+ * Returns a int32 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getInt32WithDefault(fieldNumber, defaultValue = 0) {
+ checkTypeSignedInt32(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) =>
+ readOptional(indexArray, bytes, reader.readInt32, WireType.VARINT));
+ }
+
+ /**
+ * Returns a int64 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getInt64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ checkTypeSignedInt64(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) =>
+ readOptional(indexArray, bytes, reader.readInt64, WireType.VARINT));
+ }
+
+ /**
+ * Returns a sfixed32 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getSfixed32WithDefault(fieldNumber, defaultValue = 0) {
+ checkTypeSignedInt32(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readSfixed32, WireType.FIXED32));
+ }
+
+ /**
+ * Returns a sfixed64 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getSfixed64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ checkTypeSignedInt64(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readSfixed64, WireType.FIXED64));
+ }
+
+ /**
+ * Returns a sint32 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getSint32WithDefault(fieldNumber, defaultValue = 0) {
+ checkTypeSignedInt32(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readSint32, WireType.VARINT));
+ }
+
+ /**
+ * Returns a sint64 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getSint64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ checkTypeSignedInt64(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readSint64, WireType.VARINT));
+ }
+
+ /**
+ * Returns a string for the given field number.
+ * If no default is given uses empty string as the default.
+ * @param {number} fieldNumber
+ * @param {string=} defaultValue
+ * @return {string}
+ */
+ getStringWithDefault(fieldNumber, defaultValue = '') {
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readString, WireType.DELIMITED));
+ }
+
+ /**
+ * Returns a uint32 for the given field number.
+ * If no default is given zero as the default.
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getUint32WithDefault(fieldNumber, defaultValue = 0) {
+ checkTypeUnsignedInt32(defaultValue);
+ return this.getFieldWithDefault_(
+ fieldNumber, defaultValue,
+ (indexArray, bytes) => readOptional(
+ indexArray, bytes, reader.readUint32, WireType.VARINT));
+ }
+
+ /**
+ * Returns a uint64 for the given field number.
+ * Note: Since g.m.Long does not support unsigned int64 values we are going
+ * the Java route here for now and simply output the number as a signed int64.
+ * Users can get to individual bits by themselves.
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getUint64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ return this.getInt64WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * Returns data as a mutable proto Message for the given field number.
+ * If no value has been set, return null.
+ * If hasFieldNumber(fieldNumber) == false before calling, it remains false.
+ *
+ * This method should not be used along with getMessage, since calling
+ * getMessageOrNull after getMessage will not register the encoder.
+ *
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {?T}
+ * @template T
+ */
+ getMessageOrNull(fieldNumber, instanceCreator, pivot = undefined) {
+ return this.getFieldWithDefault_(
+ fieldNumber, null,
+ (indexArray, bytes) =>
+ readMessage(indexArray, bytes, instanceCreator, pivot),
+ writeMessage);
+ }
+
+ /**
+ * Returns data as a mutable proto Message for the given field number.
+ * If no value has been set, return null.
+ * If hasFieldNumber(fieldNumber) == false before calling, it remains false.
+ *
+ * This method should not be used along with getMessage, since calling
+ * getMessageOrNull after getMessage will not register the encoder.
+ *
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {?T}
+ * @template T
+ */
+ getGroupOrNull(fieldNumber, instanceCreator, pivot = undefined) {
+ return this.getFieldWithDefault_(
+ fieldNumber, null,
+ (indexArray, bytes) =>
+ readGroup(indexArray, bytes, fieldNumber, instanceCreator, pivot),
+ writeGroup);
+ }
+
+ /**
+ * Returns data as a mutable proto Message for the given field number.
+ * If no value has been set previously, creates and attaches an instance.
+ * Postcondition: hasFieldNumber(fieldNumber) == true.
+ *
+ * This method should not be used along with getMessage, since calling
+ * getMessageAttach after getMessage will not register the encoder.
+ *
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getMessageAttach(fieldNumber, instanceCreator, pivot = undefined) {
+ checkInstanceCreator(instanceCreator);
+ let instance = this.getMessageOrNull(fieldNumber, instanceCreator, pivot);
+ if (!instance) {
+ instance = instanceCreator(Kernel.createEmpty());
+ this.setField_(fieldNumber, instance, writeMessage);
+ }
+ return instance;
+ }
+
+ /**
+ * Returns data as a mutable proto Message for the given field number.
+ * If no value has been set previously, creates and attaches an instance.
+ * Postcondition: hasFieldNumber(fieldNumber) == true.
+ *
+ * This method should not be used along with getMessage, since calling
+ * getMessageAttach after getMessage will not register the encoder.
+ *
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getGroupAttach(fieldNumber, instanceCreator, pivot = undefined) {
+ checkInstanceCreator(instanceCreator);
+ let instance = this.getGroupOrNull(fieldNumber, instanceCreator, pivot);
+ if (!instance) {
+ instance = instanceCreator(Kernel.createEmpty());
+ this.setField_(fieldNumber, instance, writeGroup);
+ }
+ return instance;
+ }
+
+ /**
+ * Returns data as a proto Message for the given field number.
+ * If no value has been set, return a default instance.
+ * This default instance is guaranteed to be the same instance, unless this
+ * field is cleared.
+ * Does not register the encoder, so changes made to the returned
+ * sub-message will not be included when serializing the parent message.
+ * Use getMessageAttach() if the resulting sub-message should be mutable.
+ *
+ * This method should not be used along with getMessageOrNull or
+ * getMessageAttach, since these methods register the encoder.
+ *
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getMessage(fieldNumber, instanceCreator, pivot = undefined) {
+ checkInstanceCreator(instanceCreator);
+ const message = this.getFieldWithDefault_(
+ fieldNumber, null,
+ (indexArray, bytes) =>
+ readMessage(indexArray, bytes, instanceCreator, pivot));
+ // Returns an empty message as the default value if the field doesn't exist.
+ // We don't pass the default value to getFieldWithDefault_ to reduce object
+ // allocation.
+ return message === null ? instanceCreator(Kernel.createEmpty()) : message;
+ }
+
+ /**
+ * Returns data as a proto Message for the given field number.
+ * If no value has been set, return a default instance.
+ * This default instance is guaranteed to be the same instance, unless this
+ * field is cleared.
+ * Does not register the encoder, so changes made to the returned
+ * sub-message will not be included when serializing the parent message.
+ * Use getMessageAttach() if the resulting sub-message should be mutable.
+ *
+ * This method should not be used along with getMessageOrNull or
+ * getMessageAttach, since these methods register the encoder.
+ *
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getGroup(fieldNumber, instanceCreator, pivot = undefined) {
+ checkInstanceCreator(instanceCreator);
+ const message = this.getFieldWithDefault_(
+ fieldNumber, null,
+ (indexArray, bytes) =>
+ readGroup(indexArray, bytes, fieldNumber, instanceCreator, pivot));
+ // Returns an empty message as the default value if the field doesn't exist.
+ // We don't pass the default value to getFieldWithDefault_ to reduce object
+ // allocation.
+ return message === null ? instanceCreator(Kernel.createEmpty()) : message;
+ }
+
+ /**
+ * Returns the accessor for the given singular message, or returns null if
+ * it hasn't been set.
+ * @param {number} fieldNumber
+ * @param {number=} pivot
+ * @return {?Kernel}
+ */
+ getMessageAccessorOrNull(fieldNumber, pivot = undefined) {
+ checkFieldNumber(fieldNumber);
+ const field = this.fields_.get(fieldNumber);
+ if (field === undefined) {
+ return null;
+ }
+
+ if (field.hasDecodedValue()) {
+ return checkIsInternalMessage(field.getDecodedValue())
+ .internalGetKernel();
+ } else {
+ return readAccessor(
+ checkDefAndNotNull(field.getIndexArray()),
+ checkDefAndNotNull(this.bufferDecoder_), pivot);
+ }
+ }
+
+ /***************************************************************************
+ * REPEATED GETTER METHODS
+ ***************************************************************************/
+
+ /* Bool */
+
+ /**
+ * Returns an Array instance containing boolean values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<boolean>}
+ * @private
+ */
+ getRepeatedBoolArray_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readBool, reader.readPackedBool,
+ WireType.VARINT));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {boolean}
+ */
+ getRepeatedBoolElement(fieldNumber, index) {
+ const array = this.getRepeatedBoolArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing boolean values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<boolean>}
+ */
+ getRepeatedBoolIterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedBoolArray_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedBoolArray_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedBoolSize(fieldNumber) {
+ return this.getRepeatedBoolArray_(fieldNumber).length;
+ }
+
+ /* Double */
+
+ /**
+ * Returns an Array instance containing double values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<number>}
+ * @private
+ */
+ getRepeatedDoubleArray_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readDouble, reader.readPackedDouble,
+ WireType.FIXED64));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedDoubleElement(fieldNumber, index) {
+ const array = this.getRepeatedDoubleArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing double values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedDoubleIterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedDoubleArray_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedDoubleArray_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedDoubleSize(fieldNumber) {
+ return this.getRepeatedDoubleArray_(fieldNumber).length;
+ }
+
+ /* Fixed32 */
+
+ /**
+ * Returns an Array instance containing fixed32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<number>}
+ * @private
+ */
+ getRepeatedFixed32Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readFixed32, reader.readPackedFixed32,
+ WireType.FIXED32));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedFixed32Element(fieldNumber, index) {
+ const array = this.getRepeatedFixed32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing fixed32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedFixed32Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedFixed32Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedFixed32Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedFixed32Size(fieldNumber) {
+ return this.getRepeatedFixed32Array_(fieldNumber).length;
+ }
+
+ /* Fixed64 */
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedFixed64Element(fieldNumber, index) {
+ return this.getRepeatedSfixed64Element(fieldNumber, index);
+ }
+
+ /**
+ * Returns an Iterable instance containing fixed64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedFixed64Iterable(fieldNumber) {
+ return this.getRepeatedSfixed64Iterable(fieldNumber);
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedFixed64Size(fieldNumber) {
+ return this.getRepeatedSfixed64Size(fieldNumber);
+ }
+
+ /* Float */
+
+ /**
+ * Returns an Array instance containing float values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<number>}
+ * @private
+ */
+ getRepeatedFloatArray_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readFloat, reader.readPackedFloat,
+ WireType.FIXED32));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedFloatElement(fieldNumber, index) {
+ const array = this.getRepeatedFloatArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing float values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedFloatIterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedFloatArray_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedFloatArray_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedFloatSize(fieldNumber) {
+ return this.getRepeatedFloatArray_(fieldNumber).length;
+ }
+
+ /* Int32 */
+
+ /**
+ * Returns an Array instance containing int32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<number>}
+ * @private
+ */
+ getRepeatedInt32Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readInt32, reader.readPackedInt32,
+ WireType.VARINT));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedInt32Element(fieldNumber, index) {
+ const array = this.getRepeatedInt32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing int32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedInt32Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedInt32Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedInt32Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedInt32Size(fieldNumber) {
+ return this.getRepeatedInt32Array_(fieldNumber).length;
+ }
+
+ /* Int64 */
+
+ /**
+ * Returns an Array instance containing int64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<!Int64>}
+ * @private
+ */
+ getRepeatedInt64Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readInt64, reader.readPackedInt64,
+ WireType.VARINT));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedInt64Element(fieldNumber, index) {
+ const array = this.getRepeatedInt64Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing int64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedInt64Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedInt64Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedInt64Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedInt64Size(fieldNumber) {
+ return this.getRepeatedInt64Array_(fieldNumber).length;
+ }
+
+ /* Sfixed32 */
+
+ /**
+ * Returns an Array instance containing sfixed32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<number>}
+ * @private
+ */
+ getRepeatedSfixed32Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readSfixed32, reader.readPackedSfixed32,
+ WireType.FIXED32));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedSfixed32Element(fieldNumber, index) {
+ const array = this.getRepeatedSfixed32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing sfixed32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedSfixed32Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedSfixed32Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedSfixed32Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSfixed32Size(fieldNumber) {
+ return this.getRepeatedSfixed32Array_(fieldNumber).length;
+ }
+
+ /* Sfixed64 */
+
+ /**
+ * Returns an Array instance containing sfixed64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<!Int64>}
+ * @private
+ */
+ getRepeatedSfixed64Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readSfixed64, reader.readPackedSfixed64,
+ WireType.FIXED64));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedSfixed64Element(fieldNumber, index) {
+ const array = this.getRepeatedSfixed64Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing sfixed64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedSfixed64Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedSfixed64Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedSfixed64Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSfixed64Size(fieldNumber) {
+ return this.getRepeatedSfixed64Array_(fieldNumber).length;
+ }
+
+ /* Sint32 */
+
+ /**
+ * Returns an Array instance containing sint32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<number>}
+ * @private
+ */
+ getRepeatedSint32Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readSint32, reader.readPackedSint32,
+ WireType.VARINT));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedSint32Element(fieldNumber, index) {
+ const array = this.getRepeatedSint32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing sint32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedSint32Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedSint32Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedSint32Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSint32Size(fieldNumber) {
+ return this.getRepeatedSint32Array_(fieldNumber).length;
+ }
+
+ /* Sint64 */
+
+ /**
+ * Returns an Array instance containing sint64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<!Int64>}
+ * @private
+ */
+ getRepeatedSint64Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readSint64, reader.readPackedSint64,
+ WireType.VARINT));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedSint64Element(fieldNumber, index) {
+ const array = this.getRepeatedSint64Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing sint64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedSint64Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedSint64Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedSint64Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSint64Size(fieldNumber) {
+ return this.getRepeatedSint64Array_(fieldNumber).length;
+ }
+
+ /* Uint32 */
+
+ /**
+ * Returns an Array instance containing uint32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<number>}
+ * @private
+ */
+ getRepeatedUint32Array_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) => readRepeatedPrimitive(
+ indexArray, bytes, reader.readUint32, reader.readPackedUint32,
+ WireType.VARINT));
+ }
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedUint32Element(fieldNumber, index) {
+ const array = this.getRepeatedUint32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing uint32 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedUint32Iterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedUint32Array_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedUint32Array_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedUint32Size(fieldNumber) {
+ return this.getRepeatedUint32Array_(fieldNumber).length;
+ }
+
+ /* Uint64 */
+
+ /**
+ * Returns the element at index for the given field number.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedUint64Element(fieldNumber, index) {
+ return this.getRepeatedInt64Element(fieldNumber, index);
+ }
+
+ /**
+ * Returns an Iterable instance containing uint64 values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedUint64Iterable(fieldNumber) {
+ return this.getRepeatedInt64Iterable(fieldNumber);
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedUint64Size(fieldNumber) {
+ return this.getRepeatedInt64Size(fieldNumber);
+ }
+
+ /* Bytes */
+
+ /**
+ * Returns an array instance containing bytes values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<!ByteString>}
+ * @private
+ */
+ getRepeatedBytesArray_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bytes) =>
+ readRepeatedNonPrimitive(indexArray, bytes, reader.readBytes));
+ }
+
+ /**
+ * Returns the element at index for the given field number as a bytes.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!ByteString}
+ */
+ getRepeatedBytesElement(fieldNumber, index) {
+ const array = this.getRepeatedBytesArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing bytes values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<!ByteString>}
+ */
+ getRepeatedBytesIterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedBytesArray_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedBytesArray_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedBytesSize(fieldNumber) {
+ return this.getRepeatedBytesArray_(fieldNumber).length;
+ }
+
+ /* String */
+
+ /**
+ * Returns an array instance containing string values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Array<string>}
+ * @private
+ */
+ getRepeatedStringArray_(fieldNumber) {
+ return this.getFieldWithDefault_(
+ fieldNumber, /* defaultValue= */[],
+ (indexArray, bufferDecoder) => readRepeatedNonPrimitive(
+ indexArray, bufferDecoder, reader.readString));
+ }
+
+ /**
+ * Returns the element at index for the given field number as a string.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {string}
+ */
+ getRepeatedStringElement(fieldNumber, index) {
+ const array = this.getRepeatedStringArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing string values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @return {!Iterable<string>}
+ */
+ getRepeatedStringIterable(fieldNumber) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedStringArray_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(this.getRepeatedStringArray_(fieldNumber));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedStringSize(fieldNumber) {
+ return this.getRepeatedStringArray_(fieldNumber).length;
+ }
+
+ /* Message */
+
+ /**
+ * Returns an Array instance containing boolean values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number|undefined} pivot
+ * @return {!Array<T>}
+ * @template T
+ * @private
+ */
+ getRepeatedMessageArray_(fieldNumber, instanceCreator, pivot) {
+ // This method can be shortened using getFieldWithDefault and
+ // getRepeatedNonPrimitive methods. But that will require creating and
+ // passing a reader closure every time getRepeatedMessageArray_ is called,
+ // which is expensive.
+ checkInstanceCreator(instanceCreator);
+ checkFieldNumber(fieldNumber);
+
+ const field = this.fields_.get(fieldNumber);
+ if (field === undefined) {
+ return [];
+ }
+
+ if (field.hasDecodedValue()) {
+ return field.getDecodedValue();
+ }
+
+ const indexArray = checkDefAndNotNull(field.getIndexArray());
+ const result = new Array(indexArray.length);
+ for (let i = 0; i < indexArray.length; i++) {
+ validateWireType(indexArray[i], WireType.DELIMITED);
+ const subMessageBuffer = reader.readDelimited(
+ checkDefAndNotNull(this.bufferDecoder_),
+ Field.getStartIndex(indexArray[i]));
+ result[i] =
+ instanceCreator(Kernel.fromBufferDecoder_(subMessageBuffer, pivot));
+ }
+ field.setCache(result, writeRepeatedMessage);
+
+ return result;
+ }
+
+ /**
+ * Returns the element at index for the given field number as a message.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number} index
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getRepeatedMessageElement(
+ fieldNumber, instanceCreator, index, pivot = undefined) {
+ const array =
+ this.getRepeatedMessageArray_(fieldNumber, instanceCreator, pivot);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing message values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {!Iterable<T>}
+ * @template T
+ */
+ getRepeatedMessageIterable(fieldNumber, instanceCreator, pivot = undefined) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedMessageArray_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(
+ this.getRepeatedMessageArray_(fieldNumber, instanceCreator, pivot));
+ }
+
+ /**
+ * Returns an Iterable instance containing message accessors for the given
+ * field number.
+ * @param {number} fieldNumber
+ * @param {number=} pivot
+ * @return {!Iterable<!Kernel>}
+ */
+ getRepeatedMessageAccessorIterable(fieldNumber, pivot = undefined) {
+ checkFieldNumber(fieldNumber);
+
+ const field = this.fields_.get(fieldNumber);
+ if (!field) {
+ return [];
+ }
+
+ if (field.hasDecodedValue()) {
+ return new ArrayIterable(field.getDecodedValue().map(
+ value => checkIsInternalMessage(value).internalGetKernel()));
+ }
+
+ const readMessageFunc = (bufferDecoder, start) => Kernel.fromBufferDecoder_(
+ reader.readDelimited(bufferDecoder, start), pivot);
+ const array = readRepeatedNonPrimitive(
+ checkDefAndNotNull(field.getIndexArray()),
+ checkDefAndNotNull(this.bufferDecoder_), readMessageFunc);
+ return new ArrayIterable(array);
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @return {number}
+ * @param {number=} pivot
+ * @template T
+ */
+ getRepeatedMessageSize(fieldNumber, instanceCreator, pivot = undefined) {
+ return this.getRepeatedMessageArray_(fieldNumber, instanceCreator, pivot)
+ .length;
+ }
+
+ /**
+ * Returns an Array instance containing boolean values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number|undefined} pivot
+ * @return {!Array<T>}
+ * @template T
+ * @private
+ */
+ getRepeatedGroupArray_(fieldNumber, instanceCreator, pivot) {
+ return this.getFieldWithDefault_(
+ fieldNumber, [],
+ (indexArray, bufferDecoder) => readRepeatedGroup(
+ indexArray, bufferDecoder, fieldNumber, instanceCreator, pivot),
+ writeRepeatedGroup);
+ }
+
+ /**
+ * Returns the element at index for the given field number as a group.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number} index
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getRepeatedGroupElement(
+ fieldNumber, instanceCreator, index, pivot = undefined) {
+ const array =
+ this.getRepeatedGroupArray_(fieldNumber, instanceCreator, pivot);
+ checkCriticalElementIndex(index, array.length);
+ return array[index];
+ }
+
+ /**
+ * Returns an Iterable instance containing group values for the given field
+ * number.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {!Iterable<T>}
+ * @template T
+ */
+ getRepeatedGroupIterable(fieldNumber, instanceCreator, pivot = undefined) {
+ // Don't split this statement unless needed. JS compiler thinks
+ // getRepeatedMessageArray_ might have side effects and doesn't inline the
+ // call in the compiled code. See cl/293894484 for details.
+ return new ArrayIterable(
+ this.getRepeatedGroupArray_(fieldNumber, instanceCreator, pivot));
+ }
+
+ /**
+ * Returns the size of the repeated field.
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @return {number}
+ * @param {number=} pivot
+ * @template T
+ */
+ getRepeatedGroupSize(fieldNumber, instanceCreator, pivot = undefined) {
+ return this.getRepeatedGroupArray_(fieldNumber, instanceCreator, pivot)
+ .length;
+ }
+
+ /***************************************************************************
+ * OPTIONAL SETTER METHODS
+ ***************************************************************************/
+
+ /**
+ * Sets a boolean value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {boolean} value
+ */
+ setBool(fieldNumber, value) {
+ checkCriticalTypeBool(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeBool(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a boolean value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {!ByteString} value
+ */
+ setBytes(fieldNumber, value) {
+ checkCriticalTypeByteString(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeBytes(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a double value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setDouble(fieldNumber, value) {
+ checkCriticalTypeDouble(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeDouble(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a fixed32 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setFixed32(fieldNumber, value) {
+ checkCriticalTypeUnsignedInt32(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeFixed32(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a uint64 value to the field with the given field number.\
+ * Note: Since g.m.Long does not support unsigned int64 values we are going
+ * the Java route here for now and simply output the number as a signed int64.
+ * Users can get to individual bits by themselves.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setFixed64(fieldNumber, value) {
+ this.setSfixed64(fieldNumber, value);
+ }
+
+ /**
+ * Sets a float value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setFloat(fieldNumber, value) {
+ checkCriticalTypeFloat(value);
+ // Eagerly round to 32-bit precision so that reading back after set will
+ // yield the same value a reader will receive after serialization.
+ const floatValue = Math.fround(value);
+ this.setField_(fieldNumber, floatValue, (writer, fieldNumber, value) => {
+ writer.writeFloat(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a int32 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setInt32(fieldNumber, value) {
+ checkCriticalTypeSignedInt32(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeInt32(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a int64 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setInt64(fieldNumber, value) {
+ checkCriticalTypeSignedInt64(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeInt64(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a sfixed32 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setSfixed32(fieldNumber, value) {
+ checkCriticalTypeSignedInt32(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeSfixed32(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a sfixed64 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setSfixed64(fieldNumber, value) {
+ checkCriticalTypeSignedInt64(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeSfixed64(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a sint32 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setSint32(fieldNumber, value) {
+ checkCriticalTypeSignedInt32(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeSint32(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a sint64 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setSint64(fieldNumber, value) {
+ checkCriticalTypeSignedInt64(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeSint64(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a boolean value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {string} value
+ */
+ setString(fieldNumber, value) {
+ checkCriticalTypeString(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeString(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a uint32 value to the field with the given field number.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setUint32(fieldNumber, value) {
+ checkCriticalTypeUnsignedInt32(value);
+ this.setField_(fieldNumber, value, (writer, fieldNumber, value) => {
+ writer.writeUint32(fieldNumber, value);
+ });
+ }
+
+ /**
+ * Sets a uint64 value to the field with the given field number.\
+ * Note: Since g.m.Long does not support unsigned int64 values we are going
+ * the Java route here for now and simply output the number as a signed int64.
+ * Users can get to individual bits by themselves.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setUint64(fieldNumber, value) {
+ this.setInt64(fieldNumber, value);
+ }
+
+ /**
+ * Sets a proto Group to the field with the given field number.
+ * Instead of working with the Kernel inside of the message directly, we
+ * need the message instance to keep its reference equality for subsequent
+ * gettings.
+ * @param {number} fieldNumber
+ * @param {!InternalMessage} value
+ */
+ setGroup(fieldNumber, value) {
+ checkCriticalType(
+ value !== null, 'Given value is not a message instance: null');
+ this.setField_(fieldNumber, value, writeGroup);
+ }
+
+ /**
+ * Sets a proto Message to the field with the given field number.
+ * Instead of working with the Kernel inside of the message directly, we
+ * need the message instance to keep its reference equality for subsequent
+ * gettings.
+ * @param {number} fieldNumber
+ * @param {!InternalMessage} value
+ */
+ setMessage(fieldNumber, value) {
+ checkCriticalType(
+ value !== null, 'Given value is not a message instance: null');
+ this.setField_(fieldNumber, value, writeMessage);
+ }
+
+ /***************************************************************************
+ * REPEATED SETTER METHODS
+ ***************************************************************************/
+
+ /* Bool */
+
+ /**
+ * Adds all boolean values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ * @param {function(!Writer, number, !Array<boolean>): undefined} encoder
+ * @private
+ */
+ addRepeatedBoolIterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedBoolArray_(fieldNumber), ...values];
+ checkCriticalTypeBoolArray(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single boolean value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {boolean} value
+ */
+ addPackedBoolElement(fieldNumber, value) {
+ this.addRepeatedBoolIterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedBool(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all boolean values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ addPackedBoolIterable(fieldNumber, values) {
+ this.addRepeatedBoolIterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedBool(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single boolean value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {boolean} value
+ */
+ addUnpackedBoolElement(fieldNumber, value) {
+ this.addRepeatedBoolIterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedBool(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all boolean values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ addUnpackedBoolIterable(fieldNumber, values) {
+ this.addRepeatedBoolIterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedBool(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single boolean value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {boolean} value
+ * @param {function(!Writer, number, !Array<boolean>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedBoolElement_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeBool(value);
+ const array = this.getRepeatedBoolArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single boolean value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {boolean} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedBoolElement(fieldNumber, index, value) {
+ this.setRepeatedBoolElement_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedBool(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all boolean values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ setPackedBoolIterable(fieldNumber, values) {
+ const /** !Array<boolean> */ array = Array.from(values);
+ checkCriticalTypeBoolArray(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedBool(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single boolean value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {boolean} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedBoolElement(fieldNumber, index, value) {
+ this.setRepeatedBoolElement_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedBool(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all boolean values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ setUnpackedBoolIterable(fieldNumber, values) {
+ const /** !Array<boolean> */ array = Array.from(values);
+ checkCriticalTypeBoolArray(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedBool(fieldNumber, values);
+ });
+ }
+
+ /* Double */
+
+ /**
+ * Adds all double values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @private
+ */
+ addRepeatedDoubleIterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedDoubleArray_(fieldNumber), ...values];
+ checkCriticalTypeDoubleArray(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single double value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedDoubleElement(fieldNumber, value) {
+ this.addRepeatedDoubleIterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedDouble(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all double values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedDoubleIterable(fieldNumber, values) {
+ this.addRepeatedDoubleIterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedDouble(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single double value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedDoubleElement(fieldNumber, value) {
+ this.addRepeatedDoubleIterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedDouble(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all double values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedDoubleIterable(fieldNumber, values) {
+ this.addRepeatedDoubleIterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedDouble(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single double value into the field for the given field number at the
+ * given index.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedDoubleElement_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeDouble(value);
+ const array = this.getRepeatedDoubleArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single double value into the field for the given field number at the
+ * given index.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedDoubleElement(fieldNumber, index, value) {
+ this.setRepeatedDoubleElement_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedDouble(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all double values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedDoubleIterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeDoubleArray(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedDouble(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single double value into the field for the given field number at the
+ * given index.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedDoubleElement(fieldNumber, index, value) {
+ this.setRepeatedDoubleElement_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedDouble(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all double values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedDoubleIterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeDoubleArray(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedDouble(fieldNumber, values);
+ });
+ }
+
+ /* Fixed32 */
+
+ /**
+ * Adds all fixed32 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @private
+ */
+ addRepeatedFixed32Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedFixed32Array_(fieldNumber), ...values];
+ checkCriticalTypeUnsignedInt32Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single fixed32 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedFixed32Element(fieldNumber, value) {
+ this.addRepeatedFixed32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedFixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all fixed32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedFixed32Iterable(fieldNumber, values) {
+ this.addRepeatedFixed32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedFixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single fixed32 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedFixed32Element(fieldNumber, value) {
+ this.addRepeatedFixed32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedFixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all fixed32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedFixed32Iterable(fieldNumber, values) {
+ this.addRepeatedFixed32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedFixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single fixed32 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedFixed32Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeUnsignedInt32(value);
+ const array = this.getRepeatedFixed32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single fixed32 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedFixed32Element(fieldNumber, index, value) {
+ this.setRepeatedFixed32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedFixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all fixed32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedFixed32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeUnsignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedFixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single fixed32 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedFixed32Element(fieldNumber, index, value) {
+ this.setRepeatedFixed32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedFixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all fixed32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedFixed32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeUnsignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedFixed32(fieldNumber, values);
+ });
+ }
+
+ /* Fixed64 */
+
+ /**
+ * Adds a single fixed64 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedFixed64Element(fieldNumber, value) {
+ this.addPackedSfixed64Element(fieldNumber, value);
+ }
+
+ /**
+ * Adds all fixed64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedFixed64Iterable(fieldNumber, values) {
+ this.addPackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * Adds a single fixed64 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedFixed64Element(fieldNumber, value) {
+ this.addUnpackedSfixed64Element(fieldNumber, value);
+ }
+
+ /**
+ * Adds all fixed64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedFixed64Iterable(fieldNumber, values) {
+ this.addUnpackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * Sets a single fixed64 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedFixed64Element(fieldNumber, index, value) {
+ this.setPackedSfixed64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * Sets all fixed64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedFixed64Iterable(fieldNumber, values) {
+ this.setPackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * Sets a single fixed64 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedFixed64Element(fieldNumber, index, value) {
+ this.setUnpackedSfixed64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * Sets all fixed64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedFixed64Iterable(fieldNumber, values) {
+ this.setUnpackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /* Float */
+
+ /**
+ * Adds all float values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @private
+ */
+ addRepeatedFloatIterable_(fieldNumber, values, encoder) {
+ checkCriticalTypeFloatIterable(values);
+ // Eagerly round to 32-bit precision so that reading back after set will
+ // yield the same value a reader will receive after serialization.
+ const floatValues = Array.from(values, fround);
+ const array = [...this.getRepeatedFloatArray_(fieldNumber), ...floatValues];
+ checkCriticalTypeFloatIterable(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single float value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedFloatElement(fieldNumber, value) {
+ this.addRepeatedFloatIterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedFloat(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all float values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedFloatIterable(fieldNumber, values) {
+ this.addRepeatedFloatIterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedFloat(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single float value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedFloatElement(fieldNumber, value) {
+ this.addRepeatedFloatIterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedFloat(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all float values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedFloatIterable(fieldNumber, values) {
+ this.addRepeatedFloatIterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedFloat(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single float value into the field for the given field number at the
+ * given index.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedFloatElement_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeFloat(value);
+ // Eagerly round to 32-bit precision so that reading back after set will
+ // yield the same value a reader will receive after serialization.
+ const floatValue = Math.fround(value);
+ const array = this.getRepeatedFloatArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = floatValue;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single float value into the field for the given field number at the
+ * given index.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedFloatElement(fieldNumber, index, value) {
+ this.setRepeatedFloatElement_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedFloat(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all float values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedFloatIterable(fieldNumber, values) {
+ checkCriticalTypeFloatIterable(values);
+ // Eagerly round to 32-bit precision so that reading back after set will
+ // yield the same value a reader will receive after serialization.
+ const array = Array.from(values, fround);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedFloat(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single float value into the field for the given field number at the
+ * given index.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedFloatElement(fieldNumber, index, value) {
+ this.setRepeatedFloatElement_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedFloat(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all float values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedFloatIterable(fieldNumber, values) {
+ checkCriticalTypeFloatIterable(values);
+ // Eagerly round to 32-bit precision so that reading back after set will
+ // yield the same value a reader will receive after serialization.
+ const array = Array.from(values, fround);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedFloat(fieldNumber, values);
+ });
+ }
+
+ /* Int32 */
+
+ /**
+ * Adds all int32 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @private
+ */
+ addRepeatedInt32Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedInt32Array_(fieldNumber), ...values];
+ checkCriticalTypeSignedInt32Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single int32 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedInt32Element(fieldNumber, value) {
+ this.addRepeatedInt32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedInt32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all int32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedInt32Iterable(fieldNumber, values) {
+ this.addRepeatedInt32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedInt32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single int32 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedInt32Element(fieldNumber, value) {
+ this.addRepeatedInt32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all int32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedInt32Iterable(fieldNumber, values) {
+ this.addRepeatedInt32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single int32 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedInt32Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeSignedInt32(value);
+ const array = this.getRepeatedInt32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single int32 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedInt32Element(fieldNumber, index, value) {
+ this.setRepeatedInt32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedInt32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all int32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedInt32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedInt32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single int32 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedInt32Element(fieldNumber, index, value) {
+ this.setRepeatedInt32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all int32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedInt32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt32(fieldNumber, values);
+ });
+ }
+
+ /* Int64 */
+
+ /**
+ * Adds all int64 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ * @param {function(!Writer, number, !Array<!Int64>): undefined} encoder
+ * @private
+ */
+ addRepeatedInt64Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedInt64Array_(fieldNumber), ...values];
+ checkCriticalTypeSignedInt64Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single int64 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedInt64Element(fieldNumber, value) {
+ this.addRepeatedInt64Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedInt64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all int64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedInt64Iterable(fieldNumber, values) {
+ this.addRepeatedInt64Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedInt64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single int64 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedInt64Element(fieldNumber, value) {
+ this.addRepeatedInt64Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all int64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedInt64Iterable(fieldNumber, values) {
+ this.addRepeatedInt64Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single int64 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @param {function(!Writer, number, !Array<!Int64>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedInt64Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeSignedInt64(value);
+ const array = this.getRepeatedInt64Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single int64 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedInt64Element(fieldNumber, index, value) {
+ this.setRepeatedInt64Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedInt64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all int64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedInt64Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt64Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedInt64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single int64 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedInt64Element(fieldNumber, index, value) {
+ this.setRepeatedInt64Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all int64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedInt64Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt64Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedInt64(fieldNumber, values);
+ });
+ }
+
+ /* Sfixed32 */
+
+ /**
+ * Adds all sfixed32 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @private
+ */
+ addRepeatedSfixed32Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedSfixed32Array_(fieldNumber), ...values];
+ checkCriticalTypeSignedInt32Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single sfixed32 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedSfixed32Element(fieldNumber, value) {
+ this.addRepeatedSfixed32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sfixed32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedSfixed32Iterable(fieldNumber, values) {
+ this.addRepeatedSfixed32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single sfixed32 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedSfixed32Element(fieldNumber, value) {
+ this.addRepeatedSfixed32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sfixed32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedSfixed32Iterable(fieldNumber, values) {
+ this.addRepeatedSfixed32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sfixed32 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedSfixed32Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeSignedInt32(value);
+ const array = this.getRepeatedSfixed32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single sfixed32 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSfixed32Element(fieldNumber, index, value) {
+ this.setRepeatedSfixed32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sfixed32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedSfixed32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sfixed32 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSfixed32Element(fieldNumber, index, value) {
+ this.setRepeatedSfixed32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sfixed32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedSfixed32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed32(fieldNumber, values);
+ });
+ }
+
+ /* Sfixed64 */
+
+ /**
+ * Adds all sfixed64 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ * @param {function(!Writer, number, !Array<!Int64>): undefined} encoder
+ * @private
+ */
+ addRepeatedSfixed64Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedSfixed64Array_(fieldNumber), ...values];
+ checkCriticalTypeSignedInt64Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single sfixed64 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedSfixed64Element(fieldNumber, value) {
+ this.addRepeatedSfixed64Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sfixed64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedSfixed64Iterable(fieldNumber, values) {
+ this.addRepeatedSfixed64Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single sfixed64 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedSfixed64Element(fieldNumber, value) {
+ this.addRepeatedSfixed64Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sfixed64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedSfixed64Iterable(fieldNumber, values) {
+ this.addRepeatedSfixed64Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sfixed64 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @param {function(!Writer, number, !Array<!Int64>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedSfixed64Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeSignedInt64(value);
+ const array = this.getRepeatedSfixed64Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single sfixed64 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSfixed64Element(fieldNumber, index, value) {
+ this.setRepeatedSfixed64Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sfixed64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedSfixed64Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt64Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sfixed64 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSfixed64Element(fieldNumber, index, value) {
+ this.setRepeatedSfixed64Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sfixed64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedSfixed64Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt64Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSfixed64(fieldNumber, values);
+ });
+ }
+
+ /* Sint32 */
+
+ /**
+ * Adds all sint32 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @private
+ */
+ addRepeatedSint32Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedSint32Array_(fieldNumber), ...values];
+ checkCriticalTypeSignedInt32Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single sint32 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedSint32Element(fieldNumber, value) {
+ this.addRepeatedSint32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedSint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sint32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedSint32Iterable(fieldNumber, values) {
+ this.addRepeatedSint32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedSint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single sint32 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedSint32Element(fieldNumber, value) {
+ this.addRepeatedSint32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sint32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedSint32Iterable(fieldNumber, values) {
+ this.addRepeatedSint32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sint32 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedSint32Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeSignedInt32(value);
+ const array = this.getRepeatedSint32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single sint32 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSint32Element(fieldNumber, index, value) {
+ this.setRepeatedSint32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedSint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sint32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedSint32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedSint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sint32 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSint32Element(fieldNumber, index, value) {
+ this.setRepeatedSint32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sint32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedSint32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint32(fieldNumber, values);
+ });
+ }
+
+ /* Sint64 */
+
+ /**
+ * Adds all sint64 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ * @param {function(!Writer, number, !Array<!Int64>): undefined} encoder
+ * @private
+ */
+ addRepeatedSint64Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedSint64Array_(fieldNumber), ...values];
+ checkCriticalTypeSignedInt64Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single sint64 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedSint64Element(fieldNumber, value) {
+ this.addRepeatedSint64Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedSint64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sint64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedSint64Iterable(fieldNumber, values) {
+ this.addRepeatedSint64Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedSint64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single sint64 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedSint64Element(fieldNumber, value) {
+ this.addRepeatedSint64Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all sint64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedSint64Iterable(fieldNumber, values) {
+ this.addRepeatedSint64Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sint64 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @param {function(!Writer, number, !Array<!Int64>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedSint64Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeSignedInt64(value);
+ const array = this.getRepeatedSint64Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single sint64 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSint64Element(fieldNumber, index, value) {
+ this.setRepeatedSint64Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedSint64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sint64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedSint64Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt64Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedSint64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single sint64 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSint64Element(fieldNumber, index, value) {
+ this.setRepeatedSint64Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint64(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all sint64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedSint64Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeSignedInt64Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedSint64(fieldNumber, values);
+ });
+ }
+
+ /* Uint32 */
+
+ /**
+ * Adds all uint32 values into the field for the given field number.
+ * How these values are encoded depends on the given write function.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @private
+ */
+ addRepeatedUint32Iterable_(fieldNumber, values, encoder) {
+ const array = [...this.getRepeatedUint32Array_(fieldNumber), ...values];
+ checkCriticalTypeUnsignedInt32Array(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Adds a single uint32 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedUint32Element(fieldNumber, value) {
+ this.addRepeatedUint32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writePackedUint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all uint32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedUint32Iterable(fieldNumber, values) {
+ this.addRepeatedUint32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writePackedUint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single uint32 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedUint32Element(fieldNumber, value) {
+ this.addRepeatedUint32Iterable_(
+ fieldNumber, [value], (writer, fieldNumber, values) => {
+ writer.writeRepeatedUint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all uint32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedUint32Iterable(fieldNumber, values) {
+ this.addRepeatedUint32Iterable_(
+ fieldNumber, values, (writer, fieldNumber, values) => {
+ writer.writeRepeatedUint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single uint32 value into the field for the given field number at
+ * the given index. How these values are encoded depends on the given write
+ * function.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @param {function(!Writer, number, !Array<number>): undefined} encoder
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @private
+ */
+ setRepeatedUint32Element_(fieldNumber, index, value, encoder) {
+ checkCriticalTypeUnsignedInt32(value);
+ const array = this.getRepeatedUint32Array_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, encoder);
+ }
+
+ /**
+ * Sets a single uint32 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedUint32Element(fieldNumber, index, value) {
+ this.setRepeatedUint32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writePackedUint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all uint32 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedUint32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeUnsignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writePackedUint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single uint32 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedUint32Element(fieldNumber, index, value) {
+ this.setRepeatedUint32Element_(
+ fieldNumber, index, value, (writer, fieldNumber, values) => {
+ writer.writeRepeatedUint32(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets all uint32 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedUint32Iterable(fieldNumber, values) {
+ const array = Array.from(values);
+ checkCriticalTypeUnsignedInt32Array(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedUint32(fieldNumber, values);
+ });
+ }
+
+ /* Uint64 */
+
+ /**
+ * Adds a single uint64 value into the field for the given field number.
+ * All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedUint64Element(fieldNumber, value) {
+ this.addPackedInt64Element(fieldNumber, value);
+ }
+
+ /**
+ * Adds all uint64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedUint64Iterable(fieldNumber, values) {
+ this.addPackedInt64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * Adds a single uint64 value into the field for the given field number.
+ * All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedUint64Element(fieldNumber, value) {
+ this.addUnpackedInt64Element(fieldNumber, value);
+ }
+
+ /**
+ * Adds all uint64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedUint64Iterable(fieldNumber, values) {
+ this.addUnpackedInt64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * Sets a single uint64 value into the field for the given field number at
+ * the given index. All values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedUint64Element(fieldNumber, index, value) {
+ this.setPackedInt64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * Sets all uint64 values into the field for the given field number.
+ * All these values will be encoded as packed values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedUint64Iterable(fieldNumber, values) {
+ this.setPackedInt64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * Sets a single uint64 value into the field for the given field number at
+ * the given index. All values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedUint64Element(fieldNumber, index, value) {
+ this.setUnpackedInt64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * Sets all uint64 values into the field for the given field number.
+ * All these values will be encoded as unpacked values.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedUint64Iterable(fieldNumber, values) {
+ this.setUnpackedInt64Iterable(fieldNumber, values);
+ }
+
+ /* Bytes */
+
+ /**
+ * Sets all bytes values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!ByteString>} values
+ */
+ setRepeatedBytesIterable(fieldNumber, values) {
+ const /** !Array<!ByteString> */ array = Array.from(values);
+ checkCriticalTypeByteStringArray(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedBytes(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all bytes values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!ByteString>} values
+ */
+ addRepeatedBytesIterable(fieldNumber, values) {
+ const array = [...this.getRepeatedBytesArray_(fieldNumber), ...values];
+ checkCriticalTypeByteStringArray(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedBytes(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single bytes value into the field for the given field number at
+ * the given index.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!ByteString} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setRepeatedBytesElement(fieldNumber, index, value) {
+ checkCriticalTypeByteString(value);
+ const array = this.getRepeatedBytesArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedBytes(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single bytes value into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!ByteString} value
+ */
+ addRepeatedBytesElement(fieldNumber, value) {
+ this.addRepeatedBytesIterable(fieldNumber, [value]);
+ }
+
+ /* String */
+
+ /**
+ * Sets all string values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<string>} values
+ */
+ setRepeatedStringIterable(fieldNumber, values) {
+ const /** !Array<string> */ array = Array.from(values);
+ checkCriticalTypeStringArray(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedString(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all string values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<string>} values
+ */
+ addRepeatedStringIterable(fieldNumber, values) {
+ const array = [...this.getRepeatedStringArray_(fieldNumber), ...values];
+ checkCriticalTypeStringArray(array);
+ // Needs to set it back because the default empty array was not cached.
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedString(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Sets a single string value into the field for the given field number at
+ * the given index.
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {string} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setRepeatedStringElement(fieldNumber, index, value) {
+ checkCriticalTypeString(value);
+ const array = this.getRepeatedStringArray_(fieldNumber);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ // Needs to set it back to set encoder.
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writer.writeRepeatedString(fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds a single string value into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {string} value
+ */
+ addRepeatedStringElement(fieldNumber, value) {
+ this.addRepeatedStringIterable(fieldNumber, [value]);
+ }
+
+ /* Message */
+
+ /**
+ * Sets all message values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!InternalMessage>} values
+ */
+ setRepeatedMessageIterable(fieldNumber, values) {
+ const /** !Array<!InternalMessage> */ array = Array.from(values);
+ checkCriticalTypeMessageArray(array);
+ this.setField_(fieldNumber, array, (writer, fieldNumber, values) => {
+ writeRepeatedMessage(writer, fieldNumber, values);
+ });
+ }
+
+ /**
+ * Adds all message values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!InternalMessage>} values
+ * @param {function(!Kernel):!InternalMessage} instanceCreator
+ * @param {number=} pivot
+ */
+ addRepeatedMessageIterable(
+ fieldNumber, values, instanceCreator, pivot = undefined) {
+ const array = [
+ ...this.getRepeatedMessageArray_(fieldNumber, instanceCreator, pivot),
+ ...values,
+ ];
+ checkCriticalTypeMessageArray(array);
+ // Needs to set it back with the new array.
+ this.setField_(
+ fieldNumber, array,
+ (writer, fieldNumber, values) =>
+ writeRepeatedMessage(writer, fieldNumber, values));
+ }
+
+ /**
+ * Sets a single message value into the field for the given field number at
+ * the given index.
+ * @param {number} fieldNumber
+ * @param {!InternalMessage} value
+ * @param {function(!Kernel):!InternalMessage} instanceCreator
+ * @param {number} index
+ * @param {number=} pivot
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setRepeatedMessageElement(
+ fieldNumber, value, instanceCreator, index, pivot = undefined) {
+ checkInstanceCreator(instanceCreator);
+ checkCriticalType(
+ value !== null, 'Given value is not a message instance: null');
+ const array =
+ this.getRepeatedMessageArray_(fieldNumber, instanceCreator, pivot);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ }
+
+ /**
+ * Adds a single message value into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!InternalMessage} value
+ * @param {function(!Kernel):!InternalMessage} instanceCreator
+ * @param {number=} pivot
+ */
+ addRepeatedMessageElement(
+ fieldNumber, value, instanceCreator, pivot = undefined) {
+ this.addRepeatedMessageIterable(
+ fieldNumber, [value], instanceCreator, pivot);
+ }
+
+ // Groups
+ /**
+ * Sets all message values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!InternalMessage>} values
+ */
+ setRepeatedGroupIterable(fieldNumber, values) {
+ const /** !Array<!InternalMessage> */ array = Array.from(values);
+ checkCriticalTypeMessageArray(array);
+ this.setField_(fieldNumber, array, writeRepeatedGroup);
+ }
+
+ /**
+ * Adds all message values into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!Iterable<!InternalMessage>} values
+ * @param {function(!Kernel):!InternalMessage} instanceCreator
+ * @param {number=} pivot
+ */
+ addRepeatedGroupIterable(
+ fieldNumber, values, instanceCreator, pivot = undefined) {
+ const array = [
+ ...this.getRepeatedGroupArray_(fieldNumber, instanceCreator, pivot),
+ ...values,
+ ];
+ checkCriticalTypeMessageArray(array);
+ // Needs to set it back with the new array.
+ this.setField_(fieldNumber, array, writeRepeatedGroup);
+ }
+
+ /**
+ * Sets a single message value into the field for the given field number at
+ * the given index.
+ * @param {number} fieldNumber
+ * @param {!InternalMessage} value
+ * @param {function(!Kernel):!InternalMessage} instanceCreator
+ * @param {number} index
+ * @param {number=} pivot
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setRepeatedGroupElement(
+ fieldNumber, value, instanceCreator, index, pivot = undefined) {
+ checkInstanceCreator(instanceCreator);
+ checkCriticalType(
+ value !== null, 'Given value is not a message instance: null');
+ const array =
+ this.getRepeatedGroupArray_(fieldNumber, instanceCreator, pivot);
+ checkCriticalElementIndex(index, array.length);
+ array[index] = value;
+ }
+
+ /**
+ * Adds a single message value into the field for the given field number.
+ * @param {number} fieldNumber
+ * @param {!InternalMessage} value
+ * @param {function(!Kernel):!InternalMessage} instanceCreator
+ * @param {number=} pivot
+ */
+ addRepeatedGroupElement(
+ fieldNumber, value, instanceCreator, pivot = undefined) {
+ this.addRepeatedGroupIterable(fieldNumber, [value], instanceCreator, pivot);
+ }
+}
+
+exports = Kernel;
diff --git a/js/experimental/runtime/kernel/kernel_compatibility_test.js b/js/experimental/runtime/kernel/kernel_compatibility_test.js
new file mode 100644
index 0000000..155008f
--- /dev/null
+++ b/js/experimental/runtime/kernel/kernel_compatibility_test.js
@@ -0,0 +1,266 @@
+/**
+ * @fileoverview Tests to make sure Kernel can read data in a backward
+ * compatible way even when protobuf schema changes according to the rules
+ * defined in
+ * https://developers.google.com/protocol-buffers/docs/proto#updating and
+ * https://developers.google.com/protocol-buffers/docs/proto3#updating.
+ *
+ * third_party/protobuf/conformance/binary_json_conformance_suite.cc already
+ * covers many compatibility tests, this file covers only the tests not covered
+ * by binary_json_conformance_suite. Ultimately all of the tests in this file
+ * should be moved to binary_json_conformance_suite.
+ */
+goog.module('protobuf.runtime.KernelCompatibilityTest');
+
+goog.setTestOnly();
+
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
+const {CHECK_CRITICAL_STATE} = goog.require('protobuf.internal.checks');
+
+/**
+ * @param {...number} bytes
+ * @return {!ArrayBuffer}
+ */
+function createArrayBuffer(...bytes) {
+ return new Uint8Array(bytes).buffer;
+}
+
+/**
+ * Returns the Unicode character codes of a string.
+ * @param {string} str
+ * @return {!Array<number>}
+ */
+function getCharacterCodes(str) {
+ return Array.from(str, (c) => c.charCodeAt(0));
+}
+
+describe('optional -> repeated compatibility', () => {
+ it('is maintained for scalars', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setInt32(1, 1);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData).toEqual(createArrayBuffer(0x8, 0x1));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getRepeatedInt32Size(1)).toEqual(1);
+ expect(newAccessor.getRepeatedInt32Element(1, 0)).toEqual(1);
+ });
+
+ it('is maintained for messages', () => {
+ const message = new TestMessage(Kernel.createEmpty());
+ message.setInt32(1, 1);
+
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setMessage(1, message);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData).toEqual(createArrayBuffer(0xA, 0x2, 0x8, 0x1));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getRepeatedMessageSize(1, TestMessage.instanceCreator))
+ .toEqual(1);
+ expect(
+ newAccessor.getRepeatedMessageElement(1, TestMessage.instanceCreator, 0)
+ .serialize())
+ .toEqual(message.serialize());
+ });
+
+ it('is maintained for bytes', () => {
+ const message = new TestMessage(Kernel.createEmpty());
+ message.setInt32(1, 1);
+
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setBytes(
+ 1, ByteString.fromArrayBuffer(createArrayBuffer(0xA, 0xB)));
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData).toEqual(createArrayBuffer(0xA, 0x2, 0xA, 0xB));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getRepeatedBytesSize(1)).toEqual(1);
+ expect(newAccessor.getRepeatedBoolElement(1, 0))
+ .toEqual(ByteString.fromArrayBuffer(createArrayBuffer(0xA, 0xB)));
+ });
+
+ it('is maintained for strings', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setString(1, 'hello');
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(0xA, 0x5, 0x68, 0x65, 0x6C, 0x6C, 0x6F));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getRepeatedStringSize(1)).toEqual(1);
+ expect(newAccessor.getRepeatedStringElement(1, 0)).toEqual('hello');
+ });
+});
+
+describe('Kernel repeated -> optional compatibility', () => {
+ it('is maintained for unpacked scalars', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.addUnpackedInt32Element(1, 0);
+ oldAccessor.addUnpackedInt32Element(1, 1);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData).toEqual(createArrayBuffer(0x8, 0x0, 0x8, 0x1));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getInt32WithDefault(1)).toEqual(1);
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+
+ // repeated -> optional transformation is not supported for packed fields yet:
+ // go/proto-schema-repeated
+ it('is not maintained for packed scalars', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.addPackedInt32Element(1, 0);
+ oldAccessor.addPackedInt32Element(1, 1);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData).toEqual(createArrayBuffer(0xA, 0x2, 0x0, 0x1));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => newAccessor.getInt32WithDefault(1)).toThrow();
+ }
+ });
+
+ it('is maintained for messages', () => {
+ const message1 = new TestMessage(Kernel.createEmpty());
+ message1.setInt32(1, 1);
+ const message2 = new TestMessage(Kernel.createEmpty());
+ message2.setInt32(1, 2);
+ message2.setInt32(2, 3);
+
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.addRepeatedMessageElement(
+ 1, message1, TestMessage.instanceCreator);
+ oldAccessor.addRepeatedMessageElement(
+ 1, message2, TestMessage.instanceCreator);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(
+ 0xA, 0x2, 0x8, 0x1, 0xA, 0x4, 0x8, 0x2, 0x10, 0x3));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ // Values from message1 and message2 have been merged
+ const newMessage = newAccessor.getMessage(1, TestMessage.instanceCreator);
+ expect(newMessage.getRepeatedInt32Size(1)).toEqual(2);
+ expect(newMessage.getRepeatedInt32Element(1, 0)).toEqual(1);
+ expect(newMessage.getRepeatedInt32Element(1, 1)).toEqual(2);
+ expect(newMessage.getInt32WithDefault(2)).toEqual(3);
+ expect(newMessage.serialize())
+ .toEqual(createArrayBuffer(0x8, 0x1, 0x8, 0x2, 0x10, 0x3));
+ });
+
+ it('is maintained for bytes', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.addRepeatedBytesElement(
+ 1, ByteString.fromArrayBuffer(createArrayBuffer(0xA, 0xB)));
+ oldAccessor.addRepeatedBytesElement(
+ 1, ByteString.fromArrayBuffer(createArrayBuffer(0xC, 0xD)));
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(0xA, 0x2, 0xA, 0xB, 0xA, 0x2, 0xC, 0xD));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getBytesWithDefault(1))
+ .toEqual(ByteString.fromArrayBuffer(createArrayBuffer(0xC, 0xD)));
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+
+ it('is maintained for strings', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.addRepeatedStringElement(1, 'hello');
+ oldAccessor.addRepeatedStringElement(1, 'world');
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(
+ 0xA, 0x5, ...getCharacterCodes('hello'), 0xA, 0x5,
+ ...getCharacterCodes('world')));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getStringWithDefault(1)).toEqual('world');
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+});
+
+describe('Type change', () => {
+ it('is supported for fixed32 -> sfixed32', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setFixed32(1, 4294967295);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(0xD, 0xFF, 0xFF, 0xFF, 0xFF));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getSfixed32WithDefault(1)).toEqual(-1);
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+
+ it('is supported for sfixed32 -> fixed32', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setSfixed32(1, -1);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(0xD, 0xFF, 0xFF, 0xFF, 0xFF));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getFixed32WithDefault(1)).toEqual(4294967295);
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+
+ it('is supported for fixed64 -> sfixed64', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setFixed64(1, Int64.fromHexString('0xFFFFFFFFFFFFFFFF'));
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(
+ 0x9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getSfixed64WithDefault(1)).toEqual(Int64.fromInt(-1));
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+
+ it('is supported for sfixed64 -> fixed64', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setSfixed64(1, Int64.fromInt(-1));
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData)
+ .toEqual(createArrayBuffer(
+ 0x9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getFixed64WithDefault(1))
+ .toEqual(Int64.fromHexString('0xFFFFFFFFFFFFFFFF'));
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+
+ it('is supported for bytes -> message', () => {
+ const oldAccessor = Kernel.createEmpty();
+ oldAccessor.setBytes(
+ 1, ByteString.fromArrayBuffer(createArrayBuffer(0x8, 0x1)));
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData).toEqual(createArrayBuffer(0xA, 0x2, 0x8, 0x1));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ const message = newAccessor.getMessage(1, TestMessage.instanceCreator);
+ expect(message.getInt32WithDefault(1)).toEqual(1);
+ expect(message.serialize()).toEqual(createArrayBuffer(0x8, 0x1));
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+
+ it('is supported for message -> bytes', () => {
+ const oldAccessor = Kernel.createEmpty();
+ const message = new TestMessage(Kernel.createEmpty());
+ message.setInt32(1, 1);
+ oldAccessor.setMessage(1, message);
+ const serializedData = oldAccessor.serialize();
+ expect(serializedData).toEqual(createArrayBuffer(0xA, 0x2, 0x8, 0x1));
+
+ const newAccessor = Kernel.fromArrayBuffer(serializedData);
+ expect(newAccessor.getBytesWithDefault(1))
+ .toEqual(ByteString.fromArrayBuffer(createArrayBuffer(0x8, 0x1)));
+ expect(newAccessor.serialize()).toEqual(serializedData);
+ });
+});
diff --git a/js/experimental/runtime/kernel/kernel_repeated_test.js b/js/experimental/runtime/kernel/kernel_repeated_test.js
new file mode 100644
index 0000000..6a798b6
--- /dev/null
+++ b/js/experimental/runtime/kernel/kernel_repeated_test.js
@@ -0,0 +1,7807 @@
+/**
+ * @fileoverview Tests for repeated methods in kernel.js.
+ */
+goog.module('protobuf.runtime.KernelTest');
+
+goog.setTestOnly();
+
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const InternalMessage = goog.require('protobuf.binary.InternalMessage');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
+// Note to the reader:
+// Since the lazy accessor behavior changes with the checking level some of the
+// tests in this file have to know which checking level is enable to make
+// correct assertions.
+const {CHECK_CRITICAL_STATE} = goog.require('protobuf.internal.checks');
+
+/**
+ * @param {...number} bytes
+ * @return {!ArrayBuffer}
+ */
+function createArrayBuffer(...bytes) {
+ return new Uint8Array(bytes).buffer;
+}
+
+/**
+ * Expects the Iterable instance yield the same values as the expected array.
+ * @param {!Iterable<T>} iterable
+ * @param {!Array<T>} expected
+ * @template T
+ * TODO: Implement this as a custom matcher.
+ */
+function expectEqualToArray(iterable, expected) {
+ const array = Array.from(iterable);
+ expect(array).toEqual(expected);
+}
+
+/**
+ * Expects the Iterable instance yield qualified values.
+ * @param {!Iterable<T>} iterable
+ * @param {(function(T): boolean)=} verify
+ * @template T
+ */
+function expectQualifiedIterable(iterable, verify) {
+ if (verify) {
+ for (const value of iterable) {
+ expect(verify(value)).toBe(true);
+ }
+ }
+}
+
+/**
+ * Expects the Iterable instance yield the same values as the expected array of
+ * messages.
+ * @param {!Iterable<!TestMessage>} iterable
+ * @param {!Array<!TestMessage>} expected
+ * @template T
+ * TODO: Implement this as a custom matcher.
+ */
+function expectEqualToMessageArray(iterable, expected) {
+ const array = Array.from(iterable);
+ expect(array.length).toEqual(expected.length);
+ for (let i = 0; i < array.length; i++) {
+ const value = array[i].getBoolWithDefault(1, false);
+ const expectedValue = expected[i].getBoolWithDefault(1, false);
+ expect(value).toBe(expectedValue);
+ }
+}
+
+describe('Kernel for repeated boolean does', () => {
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ const list1 = accessor.getRepeatedBoolIterable(1);
+ const list2 = accessor.getRepeatedBoolIterable(1);
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.getRepeatedBoolSize(1)).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const list1 = accessor.getRepeatedBoolIterable(1);
+ const list2 = accessor.getRepeatedBoolIterable(1);
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return unpacked multibytes values from the input', () => {
+ const bytes = createArrayBuffer(0x08, 0x80, 0x01, 0x08, 0x80, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('return for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.addUnpackedBoolElement(1, true);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true]);
+ accessor.addUnpackedBoolElement(1, false);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('return for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.addUnpackedBoolIterable(1, [true]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true]);
+ accessor.addUnpackedBoolIterable(1, [false]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('return for setting single unpacked value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00, 0x08, 0x01));
+ accessor.setUnpackedBoolElement(1, 0, true);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, true]);
+ });
+
+ it('return for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setUnpackedBoolIterable(1, [true]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true]);
+ accessor.setUnpackedBoolIterable(1, [false]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [false]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ accessor.addUnpackedBoolElement(1, true);
+ accessor.addUnpackedBoolElement(1, false);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ accessor.addUnpackedBoolIterable(1, [true, false]);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x02, 0x00, 0x01));
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x01);
+ accessor.setUnpackedBoolElement(1, 0, true);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ accessor.setUnpackedBoolIterable(1, [true, false]);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('return packed values from the input', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const list1 = accessor.getRepeatedBoolIterable(1);
+ const list2 = accessor.getRepeatedBoolIterable(1);
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return packed multibytes values from the input', () => {
+ const bytes = createArrayBuffer(0x0A, 0x04, 0x80, 0x01, 0x80, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('return for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.addPackedBoolElement(1, true);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true]);
+ accessor.addPackedBoolElement(1, false);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('return for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.addPackedBoolIterable(1, [true]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true]);
+ accessor.addPackedBoolIterable(1, [false]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, false]);
+ });
+
+ it('return for setting single packed value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00, 0x08, 0x01));
+ accessor.setPackedBoolElement(1, 0, true);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true, true]);
+ });
+
+ it('return for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setPackedBoolIterable(1, [true]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true]);
+ accessor.setPackedBoolIterable(1, [false]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [false]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ accessor.addPackedBoolElement(1, true);
+ accessor.addPackedBoolElement(1, false);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ accessor.addPackedBoolIterable(1, [true, false]);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00, 0x08, 0x01));
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x01, 0x01);
+ accessor.setPackedBoolElement(1, 0, true);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ accessor.setPackedBoolIterable(1, [true, false]);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('return combined values from the input', () => {
+ const bytes =
+ createArrayBuffer(0x08, 0x01, 0x0A, 0x02, 0x01, 0x00, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expectEqualToArray(
+ accessor.getRepeatedBoolIterable(1), [true, true, false, false]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getRepeatedBoolElement(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toEqual(true);
+ expect(accessor.getRepeatedBoolElement(
+ /* fieldNumber= */ 1, /* index= */ 1))
+ .toEqual(false);
+ });
+
+ it('return the size from the input', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getRepeatedBoolSize(1)).toEqual(2);
+ });
+
+ it('fail when getting unpacked bool value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedBoolIterable(1);
+ }).toThrowError('Expected wire type: 0 but found: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [true]);
+ }
+ });
+
+ it('fail when adding unpacked bool values with number value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedBoolIterable(1, [fakeBoolean]))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedBoolIterable(1, [fakeBoolean]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when adding single unpacked bool value with number value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedBoolElement(1, fakeBoolean))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedBoolElement(1, fakeBoolean);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when setting unpacked bool values with number value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedBoolIterable(1, [fakeBoolean]))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedBoolIterable(1, [fakeBoolean]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when setting single unpacked bool value with number value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedBoolElement(1, 0, fakeBoolean))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedBoolElement(1, 0, fakeBoolean);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when adding packed bool values with number value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedBoolIterable(1, [fakeBoolean]))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedBoolIterable(1, [fakeBoolean]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when adding single packed bool value with number value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedBoolElement(1, fakeBoolean))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedBoolElement(1, fakeBoolean);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when setting packed bool values with number value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedBoolIterable(1, [fakeBoolean]))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedBoolIterable(1, [fakeBoolean]);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when setting single packed bool value with number value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedBoolElement(1, 0, fakeBoolean))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedBoolElement(1, 0, fakeBoolean);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [fakeBoolean]);
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedBoolElement(1, 1, true))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedBoolElement(1, 1, true);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [false, true]);
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedBoolElement(1, 1, true))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedBoolElement(1, 1, true);
+ expectEqualToArray(accessor.getRepeatedBoolIterable(1), [false, true]);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedBoolElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedBoolElement(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated double does', () => {
+ const value1 = 1;
+ const value2 = 0;
+
+ const unpackedValue1Value2 = createArrayBuffer(
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xF0,
+ 0x3F, // value1
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+ const unpackedValue2Value1 = createArrayBuffer(
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xF0,
+ 0x3F, // value2
+ );
+
+ const packedValue1Value2 = createArrayBuffer(
+ 0x0A,
+ 0x10, // tag
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xF0,
+ 0x3F, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+ const packedValue2Value1 = createArrayBuffer(
+ 0x0A,
+ 0x10, // tag
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xF0,
+ 0x3F, // value2
+ );
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedDoubleSize(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedDoubleElement(1, value1);
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ accessor.addUnpackedDoubleElement(1, value2);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedDoubleIterable(1, [value1]);
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ accessor.addUnpackedDoubleIterable(1, [value2]);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedDoubleElement(1, 1, value1);
+ const list = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedDoubleIterable(1, [value1]);
+ const list = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedDoubleElement(1, value1);
+ accessor.addUnpackedDoubleElement(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedDoubleIterable(1, [value1]);
+ accessor.addUnpackedDoubleIterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedDoubleElement(1, 0, value2);
+ accessor.setUnpackedDoubleElement(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedDoubleIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedDoubleElement(1, value1);
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ accessor.addPackedDoubleElement(1, value2);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedDoubleIterable(1, [value1]);
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ accessor.addPackedDoubleIterable(1, [value2]);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedDoubleElement(1, 1, value1);
+ const list = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedDoubleIterable(1, [value1]);
+ const list1 = accessor.getRepeatedDoubleIterable(1);
+ accessor.setPackedDoubleIterable(1, [value2]);
+ const list2 = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedDoubleElement(1, value1);
+ accessor.addPackedDoubleElement(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedDoubleIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedDoubleElement(1, 0, value2);
+ accessor.setPackedDoubleElement(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedDoubleIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xF0,
+ 0x3F, // value1
+ 0x0A,
+ 0x10, // tag
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xF0,
+ 0x3F, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ ));
+
+ const list = accessor.getRepeatedDoubleIterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedDoubleElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedDoubleElement(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedDoubleSize(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked double value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedDoubleIterable(1);
+ }).toThrowError('Expected wire type: 1 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectEqualToArray(
+ accessor.getRepeatedDoubleIterable(1), [2.937446524422997e-306]);
+ }
+ });
+
+ it('fail when adding unpacked double values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedDoubleIterable(1, [fakeDouble]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedDoubleIterable(1, [fakeDouble]);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when adding single unpacked double value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedDoubleElement(1, fakeDouble))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedDoubleElement(1, fakeDouble);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when setting unpacked double values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedDoubleIterable(1, [fakeDouble]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedDoubleIterable(1, [fakeDouble]);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when setting single unpacked double value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedDoubleElement(1, 0, fakeDouble))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedDoubleElement(1, 0, fakeDouble);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when adding packed double values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedDoubleIterable(1, [fakeDouble]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedDoubleIterable(1, [fakeDouble]);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when adding single packed double value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedDoubleElement(1, fakeDouble))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedDoubleElement(1, fakeDouble);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when setting packed double values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedDoubleIterable(1, [fakeDouble]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedDoubleIterable(1, [fakeDouble]);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when setting single packed double value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ const fakeDouble = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedDoubleElement(1, 0, fakeDouble))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedDoubleElement(1, 0, fakeDouble);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [fakeDouble]);
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedDoubleElement(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedDoubleElement(1, 1, 1);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [0, 1]);
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedDoubleElement(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedDoubleElement(1, 1, 1);
+ expectEqualToArray(accessor.getRepeatedDoubleIterable(1), [0, 1]);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedDoubleElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedDoubleElement(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated fixed32 does', () => {
+ const value1 = 1;
+ const value2 = 0;
+
+ const unpackedValue1Value2 = createArrayBuffer(
+ 0x0D, 0x01, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(
+ 0x0D, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x01, 0x00, 0x00, 0x00);
+
+ const packedValue1Value2 = createArrayBuffer(
+ 0x0A, 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const packedValue2Value1 = createArrayBuffer(
+ 0x0A, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedFixed32Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed32Element(1, value1);
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ accessor.addUnpackedFixed32Element(1, value2);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ accessor.addUnpackedFixed32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedFixed32Element(1, 1, value1);
+ const list = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedFixed32Iterable(1, [value1]);
+ const list = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed32Element(1, value1);
+ accessor.addUnpackedFixed32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed32Iterable(1, [value1]);
+ accessor.addUnpackedFixed32Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedFixed32Element(1, 0, value2);
+ accessor.setUnpackedFixed32Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedFixed32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed32Element(1, value1);
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ accessor.addPackedFixed32Element(1, value2);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ accessor.addPackedFixed32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedFixed32Element(1, 1, value1);
+ const list = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedFixed32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedFixed32Iterable(1);
+ accessor.setPackedFixed32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed32Element(1, value1);
+ accessor.addPackedFixed32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedFixed32Element(1, 0, value2);
+ accessor.setPackedFixed32Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedFixed32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x0D,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x0A,
+ 0x08, // tag
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ 0x0D,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ ));
+
+ const list = accessor.getRepeatedFixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedFixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedFixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedFixed32Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked fixed32 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedFixed32Iterable(1);
+ }).toThrowError('Expected wire type: 5 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedFixed32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when adding unpacked fixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedFixed32Iterable(1, [fakeFixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedFixed32Iterable(1, [fakeFixed32]);
+ expectQualifiedIterable(accessor.getRepeatedFixed32Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked fixed32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedFixed32Element(1, fakeFixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedFixed32Element(1, fakeFixed32);
+ expectQualifiedIterable(accessor.getRepeatedFixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked fixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFixed32Iterable(1, [fakeFixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFixed32Iterable(1, [fakeFixed32]);
+ expectQualifiedIterable(accessor.getRepeatedFixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked fixed32 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFixed32Element(1, 0, fakeFixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFixed32Element(1, 0, fakeFixed32);
+ expectQualifiedIterable(
+ accessor.getRepeatedFixed32Iterable(1),
+ );
+ }
+ });
+
+ it('fail when adding packed fixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedFixed32Iterable(1, [fakeFixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedFixed32Iterable(1, [fakeFixed32]);
+ expectQualifiedIterable(accessor.getRepeatedFixed32Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed fixed32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedFixed32Element(1, fakeFixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedFixed32Element(1, fakeFixed32);
+ expectQualifiedIterable(accessor.getRepeatedFixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting packed fixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFixed32Iterable(1, [fakeFixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFixed32Iterable(1, [fakeFixed32]);
+ expectQualifiedIterable(accessor.getRepeatedFixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed fixed32 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ const fakeFixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFixed32Element(1, 0, fakeFixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFixed32Element(1, 0, fakeFixed32);
+ expectQualifiedIterable(accessor.getRepeatedFixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(
+ createArrayBuffer(0x0A, 0x04, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFixed32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFixed32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedFixed32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFixed32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFixed32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedFixed32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedFixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedFixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated fixed64 does', () => {
+ const value1 = Int64.fromInt(1);
+ const value2 = Int64.fromInt(0);
+
+ const unpackedValue1Value2 = createArrayBuffer(
+ 0x09,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+ const unpackedValue2Value1 = createArrayBuffer(
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x09,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+
+ const packedValue1Value2 = createArrayBuffer(
+ 0x0A,
+ 0x10, // tag
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+ const packedValue2Value1 = createArrayBuffer(
+ 0x0A,
+ 0x10, // tag
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ );
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedFixed64Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed64Element(1, value1);
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ accessor.addUnpackedFixed64Element(1, value2);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ accessor.addUnpackedFixed64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedFixed64Element(1, 1, value1);
+ const list = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedFixed64Iterable(1, [value1]);
+ const list = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed64Element(1, value1);
+ accessor.addUnpackedFixed64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFixed64Iterable(1, [value1]);
+ accessor.addUnpackedFixed64Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedFixed64Element(1, 0, value2);
+ accessor.setUnpackedFixed64Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedFixed64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed64Element(1, value1);
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ accessor.addPackedFixed64Element(1, value2);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ accessor.addPackedFixed64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedFixed64Element(1, 1, value1);
+ const list = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedFixed64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedFixed64Iterable(1);
+ accessor.setPackedFixed64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed64Element(1, value1);
+ accessor.addPackedFixed64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFixed64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedFixed64Element(1, 0, value2);
+ accessor.setPackedFixed64Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedFixed64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value1
+ 0x0A, 0x10, // tag
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value1
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value2
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // value2
+ ));
+
+ const list = accessor.getRepeatedFixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedFixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedFixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedFixed64Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked fixed64 value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedFixed64Iterable(1);
+ }).toThrowError('Expected wire type: 1 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedFixed64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when adding unpacked fixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedFixed64Iterable(1, [fakeFixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedFixed64Iterable(1, [fakeFixed64]);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked fixed64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedFixed64Element(1, fakeFixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedFixed64Element(1, fakeFixed64);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked fixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFixed64Iterable(1, [fakeFixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFixed64Iterable(1, [fakeFixed64]);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked fixed64 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFixed64Element(1, 0, fakeFixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFixed64Element(1, 0, fakeFixed64);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when adding packed fixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedFixed64Iterable(1, [fakeFixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedFixed64Iterable(1, [fakeFixed64]);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed fixed64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedFixed64Element(1, fakeFixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedFixed64Element(1, fakeFixed64);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting packed fixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFixed64Iterable(1, [fakeFixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFixed64Iterable(1, [fakeFixed64]);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed fixed64 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ const fakeFixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFixed64Element(1, 0, fakeFixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFixed64Element(1, 0, fakeFixed64);
+ expectQualifiedIterable(accessor.getRepeatedFixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFixed64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFixed64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedFixed64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFixed64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFixed64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedFixed64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedFixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedFixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated float does', () => {
+ const value1 = 1.6;
+ const value1Float = Math.fround(1.6);
+ const value2 = 0;
+
+ const unpackedValue1Value2 = createArrayBuffer(
+ 0x0D, 0xCD, 0xCC, 0xCC, 0x3F, 0x0D, 0x00, 0x00, 0x00, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(
+ 0x0D, 0x00, 0x00, 0x00, 0x00, 0x0D, 0xCD, 0xCC, 0xCC, 0x3F);
+
+ const packedValue1Value2 = createArrayBuffer(
+ 0x0A, 0x08, 0xCD, 0xCC, 0xCC, 0x3F, 0x00, 0x00, 0x00, 0x00);
+ const packedValue2Value1 = createArrayBuffer(
+ 0x0A, 0x08, 0x00, 0x00, 0x00, 0x00, 0xCD, 0xCC, 0xCC, 0x3F);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedFloatSize(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list, [value1Float, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFloatElement(1, value1);
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ accessor.addUnpackedFloatElement(1, value2);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list1, [value1Float]);
+ expectEqualToArray(list2, [value1Float, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFloatIterable(1, [value1]);
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ accessor.addUnpackedFloatIterable(1, [value2]);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list1, [value1Float]);
+ expectEqualToArray(list2, [value1Float, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedFloatElement(1, 1, value1);
+ const list = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list, [value1Float, value1Float]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedFloatIterable(1, [value1]);
+ const list = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list, [value1Float]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFloatElement(1, value1);
+ accessor.addUnpackedFloatElement(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedFloatIterable(1, [value1]);
+ accessor.addUnpackedFloatIterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedFloatElement(1, 0, value2);
+ accessor.setUnpackedFloatElement(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedFloatIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list, [value1Float, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFloatElement(1, value1);
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ accessor.addPackedFloatElement(1, value2);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list1, [value1Float]);
+ expectEqualToArray(list2, [value1Float, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFloatIterable(1, [value1]);
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ accessor.addPackedFloatIterable(1, [value2]);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list1, [value1Float]);
+ expectEqualToArray(list2, [value1Float, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedFloatElement(1, 1, value1);
+ const list = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list, [value1Float, value1Float]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedFloatIterable(1, [value1]);
+ const list1 = accessor.getRepeatedFloatIterable(1);
+ accessor.setPackedFloatIterable(1, [value2]);
+ const list2 = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list1, [value1Float]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFloatElement(1, value1);
+ accessor.addPackedFloatElement(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedFloatIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedFloatElement(1, 0, value2);
+ accessor.setPackedFloatElement(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedFloatIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x0D,
+ 0xCD,
+ 0xCC,
+ 0xCC,
+ 0x3F, // value1
+ 0x0A,
+ 0x08, // tag
+ 0xCD,
+ 0xCC,
+ 0xCC,
+ 0x3F, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ 0x0D,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ ));
+
+ const list = accessor.getRepeatedFloatIterable(1);
+
+ expectEqualToArray(list, [value1Float, value1Float, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedFloatElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedFloatElement(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1Float);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedFloatSize(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked float value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedFloatIterable(1);
+ }).toThrowError('Expected wire type: 5 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedFloatIterable(1),
+ (value) => typeof value === 'number');
+ }
+ });
+
+ it('fail when adding unpacked float values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedFloatIterable(1, [fakeFloat]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedFloatIterable(1, [fakeFloat]);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked float value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedFloatElement(1, fakeFloat))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedFloatElement(1, fakeFloat);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when setting unpacked float values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFloatIterable(1, [fakeFloat]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFloatIterable(1, [fakeFloat]);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked float value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFloatElement(1, 0, fakeFloat))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFloatElement(1, 0, fakeFloat);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when adding packed float values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedFloatIterable(1, [fakeFloat]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedFloatIterable(1, [fakeFloat]);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when adding single packed float value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedFloatElement(1, fakeFloat))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedFloatElement(1, fakeFloat);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when setting packed float values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFloatIterable(1, [fakeFloat]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFloatIterable(1, [fakeFloat]);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when setting single packed float value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ const fakeFloat = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFloatElement(1, 0, fakeFloat))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFloatElement(1, 0, fakeFloat);
+ expectQualifiedIterable(accessor.getRepeatedFloatIterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedFloatElement(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedFloatElement(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedFloatIterable(1),
+ (value) => typeof value === 'number');
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedFloatElement(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedFloatElement(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedFloatIterable(1),
+ (value) => typeof value === 'number');
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedFloatElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedFloatElement(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated int32 does', () => {
+ const value1 = 1;
+ const value2 = 0;
+
+ const unpackedValue1Value2 = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(0x08, 0x00, 0x08, 0x01);
+
+ const packedValue1Value2 = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const packedValue2Value1 = createArrayBuffer(0x0A, 0x02, 0x00, 0x01);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedInt32Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt32Element(1, value1);
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ accessor.addUnpackedInt32Element(1, value2);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ accessor.addUnpackedInt32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedInt32Element(1, 1, value1);
+ const list = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedInt32Iterable(1, [value1]);
+ const list = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt32Element(1, value1);
+ accessor.addUnpackedInt32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt32Iterable(1, [value1]);
+ accessor.addUnpackedInt32Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedInt32Element(1, 0, value2);
+ accessor.setUnpackedInt32Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedInt32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt32Element(1, value1);
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ accessor.addPackedInt32Element(1, value2);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ accessor.addPackedInt32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedInt32Element(1, 1, value1);
+ const list = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedInt32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedInt32Iterable(1);
+ accessor.setPackedInt32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt32Element(1, value1);
+ accessor.addPackedInt32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedInt32Element(1, 0, value2);
+ accessor.setPackedInt32Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedInt32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08,
+ 0x01, // unpacked value1
+ 0x0A,
+ 0x02,
+ 0x01,
+ 0x00, // packed value1 and value2
+ 0x08,
+ 0x00, // unpacked value2
+ ));
+
+ const list = accessor.getRepeatedInt32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedInt32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedInt32Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedInt32Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked int32 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedInt32Iterable(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedInt32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when adding unpacked int32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedInt32Iterable(1, [fakeInt32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedInt32Iterable(1, [fakeInt32]);
+ expectQualifiedIterable(accessor.getRepeatedInt32Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked int32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedInt32Element(1, fakeInt32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedInt32Element(1, fakeInt32);
+ expectQualifiedIterable(accessor.getRepeatedInt32Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked int32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedInt32Iterable(1, [fakeInt32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedInt32Iterable(1, [fakeInt32]);
+ expectQualifiedIterable(accessor.getRepeatedInt32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked int32 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedInt32Element(1, 0, fakeInt32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedInt32Element(1, 0, fakeInt32);
+ expectQualifiedIterable(
+ accessor.getRepeatedInt32Iterable(1),
+ );
+ }
+ });
+
+ it('fail when adding packed int32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedInt32Iterable(1, [fakeInt32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedInt32Iterable(1, [fakeInt32]);
+ expectQualifiedIterable(accessor.getRepeatedInt32Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed int32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedInt32Element(1, fakeInt32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedInt32Element(1, fakeInt32);
+ expectQualifiedIterable(accessor.getRepeatedInt32Iterable(1));
+ }
+ });
+
+ it('fail when setting packed int32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedInt32Iterable(1, [fakeInt32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedInt32Iterable(1, [fakeInt32]);
+ expectQualifiedIterable(accessor.getRepeatedInt32Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed int32 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeInt32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedInt32Element(1, 0, fakeInt32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedInt32Element(1, 0, fakeInt32);
+ expectQualifiedIterable(accessor.getRepeatedInt32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedInt32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedInt32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedInt32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedInt32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedInt32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedInt32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedInt32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedInt32Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated int64 does', () => {
+ const value1 = Int64.fromInt(1);
+ const value2 = Int64.fromInt(0);
+
+ const unpackedValue1Value2 = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(0x08, 0x00, 0x08, 0x01);
+
+ const packedValue1Value2 = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const packedValue2Value1 = createArrayBuffer(0x0A, 0x02, 0x00, 0x01);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedInt64Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt64Element(1, value1);
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ accessor.addUnpackedInt64Element(1, value2);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ accessor.addUnpackedInt64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedInt64Element(1, 1, value1);
+ const list = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedInt64Iterable(1, [value1]);
+ const list = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt64Element(1, value1);
+ accessor.addUnpackedInt64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedInt64Iterable(1, [value1]);
+ accessor.addUnpackedInt64Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedInt64Element(1, 0, value2);
+ accessor.setUnpackedInt64Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedInt64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt64Element(1, value1);
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ accessor.addPackedInt64Element(1, value2);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ accessor.addPackedInt64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedInt64Element(1, 1, value1);
+ const list = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedInt64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedInt64Iterable(1);
+ accessor.setPackedInt64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt64Element(1, value1);
+ accessor.addPackedInt64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedInt64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedInt64Element(1, 0, value2);
+ accessor.setPackedInt64Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedInt64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08,
+ 0x01, // unpacked value1
+ 0x0A,
+ 0x02,
+ 0x01,
+ 0x00, // packed value1 and value2
+ 0x08,
+ 0x00, // unpacked value2
+ ));
+
+ const list = accessor.getRepeatedInt64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedInt64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedInt64Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedInt64Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked int64 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedInt64Iterable(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedInt64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when adding unpacked int64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedInt64Iterable(1, [fakeInt64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedInt64Iterable(1, [fakeInt64]);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked int64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedInt64Element(1, fakeInt64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedInt64Element(1, fakeInt64);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked int64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedInt64Iterable(1, [fakeInt64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedInt64Iterable(1, [fakeInt64]);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked int64 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedInt64Element(1, 0, fakeInt64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedInt64Element(1, 0, fakeInt64);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when adding packed int64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedInt64Iterable(1, [fakeInt64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedInt64Iterable(1, [fakeInt64]);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed int64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedInt64Element(1, fakeInt64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedInt64Element(1, fakeInt64);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when setting packed int64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedInt64Iterable(1, [fakeInt64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedInt64Iterable(1, [fakeInt64]);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed int64 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeInt64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedInt64Element(1, 0, fakeInt64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedInt64Element(1, 0, fakeInt64);
+ expectQualifiedIterable(accessor.getRepeatedInt64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedInt64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedInt64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedInt64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedInt64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedInt64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedInt64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedInt64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedInt64Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated sfixed32 does', () => {
+ const value1 = 1;
+ const value2 = 0;
+
+ const unpackedValue1Value2 = createArrayBuffer(
+ 0x0D, 0x01, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(
+ 0x0D, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x01, 0x00, 0x00, 0x00);
+
+ const packedValue1Value2 = createArrayBuffer(
+ 0x0A, 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const packedValue2Value1 = createArrayBuffer(
+ 0x0A, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedSfixed32Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed32Element(1, value1);
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ accessor.addUnpackedSfixed32Element(1, value2);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ accessor.addUnpackedSfixed32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedSfixed32Element(1, 1, value1);
+ const list = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSfixed32Iterable(1, [value1]);
+ const list = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed32Element(1, value1);
+ accessor.addUnpackedSfixed32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed32Iterable(1, [value1]);
+ accessor.addUnpackedSfixed32Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedSfixed32Element(1, 0, value2);
+ accessor.setUnpackedSfixed32Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSfixed32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed32Element(1, value1);
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ accessor.addPackedSfixed32Element(1, value2);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ accessor.addPackedSfixed32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSfixed32Element(1, 1, value1);
+ const list = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSfixed32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSfixed32Iterable(1);
+ accessor.setPackedSfixed32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed32Element(1, value1);
+ accessor.addPackedSfixed32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSfixed32Element(1, 0, value2);
+ accessor.setPackedSfixed32Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSfixed32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x0D,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x0A,
+ 0x08, // tag
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ 0x0D,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ ));
+
+ const list = accessor.getRepeatedSfixed32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedSfixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedSfixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedSfixed32Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked sfixed32 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSfixed32Iterable(1);
+ }).toThrowError('Expected wire type: 5 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedSfixed32Iterable(1),
+ (value) => typeof value === 'number');
+ }
+ });
+
+ it('fail when adding unpacked sfixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSfixed32Iterable(1, [fakeSfixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSfixed32Iterable(1, [fakeSfixed32]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked sfixed32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSfixed32Element(1, fakeSfixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSfixed32Element(1, fakeSfixed32);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked sfixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSfixed32Iterable(1, [fakeSfixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSfixed32Iterable(1, [fakeSfixed32]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked sfixed32 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSfixed32Element(1, 0, fakeSfixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSfixed32Element(1, 0, fakeSfixed32);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when adding packed sfixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSfixed32Iterable(1, [fakeSfixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSfixed32Iterable(1, [fakeSfixed32]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed sfixed32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSfixed32Element(1, fakeSfixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSfixed32Element(1, fakeSfixed32);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting packed sfixed32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSfixed32Iterable(1, [fakeSfixed32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSfixed32Iterable(1, [fakeSfixed32]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed sfixed32 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ const fakeSfixed32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSfixed32Element(1, 0, fakeSfixed32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSfixed32Element(1, 0, fakeSfixed32);
+ expectQualifiedIterable(accessor.getRepeatedSfixed32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSfixed32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSfixed32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedSfixed32Iterable(1),
+ (value) => typeof value === 'number');
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSfixed32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSfixed32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedSfixed32Iterable(1),
+ (value) => typeof value === 'number');
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSfixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedSfixed32Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated sfixed64 does', () => {
+ const value1 = Int64.fromInt(1);
+ const value2 = Int64.fromInt(0);
+
+ const unpackedValue1Value2 = createArrayBuffer(
+ 0x09,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+ const unpackedValue2Value1 = createArrayBuffer(
+ 0x09,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x09,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+
+ const packedValue1Value2 = createArrayBuffer(
+ 0x0A,
+ 0x10, // tag
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ );
+ const packedValue2Value1 = createArrayBuffer(
+ 0x0A,
+ 0x10, // tag
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value2
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // value1
+ );
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedSfixed64Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed64Element(1, value1);
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ accessor.addUnpackedSfixed64Element(1, value2);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ accessor.addUnpackedSfixed64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedSfixed64Element(1, 1, value1);
+ const list = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSfixed64Iterable(1, [value1]);
+ const list = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed64Element(1, value1);
+ accessor.addUnpackedSfixed64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSfixed64Iterable(1, [value1]);
+ accessor.addUnpackedSfixed64Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedSfixed64Element(1, 0, value2);
+ accessor.setUnpackedSfixed64Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSfixed64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed64Element(1, value1);
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ accessor.addPackedSfixed64Element(1, value2);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ accessor.addPackedSfixed64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSfixed64Element(1, 1, value1);
+ const list = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSfixed64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSfixed64Iterable(1);
+ accessor.setPackedSfixed64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed64Element(1, value1);
+ accessor.addPackedSfixed64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSfixed64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSfixed64Element(1, 0, value2);
+ accessor.setPackedSfixed64Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSfixed64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value1
+ 0x0A, 0x10, // tag
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value1
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // value2
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // value2
+ ));
+
+ const list = accessor.getRepeatedSfixed64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedSfixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedSfixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedSfixed64Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked sfixed64 value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSfixed64Iterable(1);
+ }).toThrowError('Expected wire type: 1 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedSfixed64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when adding unpacked sfixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSfixed64Iterable(1, [fakeSfixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSfixed64Iterable(1, [fakeSfixed64]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked sfixed64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSfixed64Element(1, fakeSfixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSfixed64Element(1, fakeSfixed64);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked sfixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSfixed64Iterable(1, [fakeSfixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSfixed64Iterable(1, [fakeSfixed64]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked sfixed64 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSfixed64Element(1, 0, fakeSfixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSfixed64Element(1, 0, fakeSfixed64);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when adding packed sfixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSfixed64Iterable(1, [fakeSfixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSfixed64Iterable(1, [fakeSfixed64]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed sfixed64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSfixed64Element(1, fakeSfixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSfixed64Element(1, fakeSfixed64);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting packed sfixed64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSfixed64Iterable(1, [fakeSfixed64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSfixed64Iterable(1, [fakeSfixed64]);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed sfixed64 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ const fakeSfixed64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSfixed64Element(1, 0, fakeSfixed64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSfixed64Element(1, 0, fakeSfixed64);
+ expectQualifiedIterable(accessor.getRepeatedSfixed64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSfixed64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSfixed64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedSfixed64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSfixed64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSfixed64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedSfixed64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSfixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedSfixed64Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated sint32 does', () => {
+ const value1 = -1;
+ const value2 = 0;
+
+ const unpackedValue1Value2 = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(0x08, 0x00, 0x08, 0x01);
+
+ const packedValue1Value2 = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const packedValue2Value1 = createArrayBuffer(0x0A, 0x02, 0x00, 0x01);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedSint32Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint32Element(1, value1);
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ accessor.addUnpackedSint32Element(1, value2);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ accessor.addUnpackedSint32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedSint32Element(1, 1, value1);
+ const list = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSint32Iterable(1, [value1]);
+ const list = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint32Element(1, value1);
+ accessor.addUnpackedSint32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint32Iterable(1, [value1]);
+ accessor.addUnpackedSint32Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedSint32Element(1, 0, value2);
+ accessor.setUnpackedSint32Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSint32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint32Element(1, value1);
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ accessor.addPackedSint32Element(1, value2);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ accessor.addPackedSint32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSint32Element(1, 1, value1);
+ const list = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSint32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSint32Iterable(1);
+ accessor.setPackedSint32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint32Element(1, value1);
+ accessor.addPackedSint32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSint32Element(1, 0, value2);
+ accessor.setPackedSint32Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSint32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08,
+ 0x01, // unpacked value1
+ 0x0A,
+ 0x02,
+ 0x01,
+ 0x00, // packed value1 and value2
+ 0x08,
+ 0x00, // unpacked value2
+ ));
+
+ const list = accessor.getRepeatedSint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedSint32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedSint32Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedSint32Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked sint32 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSint32Iterable(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedSint32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when adding unpacked sint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSint32Iterable(1, [fakeSint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSint32Iterable(1, [fakeSint32]);
+ expectQualifiedIterable(accessor.getRepeatedSint32Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked sint32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSint32Element(1, fakeSint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSint32Element(1, fakeSint32);
+ expectQualifiedIterable(accessor.getRepeatedSint32Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked sint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSint32Iterable(1, [fakeSint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSint32Iterable(1, [fakeSint32]);
+ expectQualifiedIterable(accessor.getRepeatedSint32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked sint32 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSint32Element(1, 0, fakeSint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSint32Element(1, 0, fakeSint32);
+ expectQualifiedIterable(
+ accessor.getRepeatedSint32Iterable(1),
+ );
+ }
+ });
+
+ it('fail when adding packed sint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSint32Iterable(1, [fakeSint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSint32Iterable(1, [fakeSint32]);
+ expectQualifiedIterable(accessor.getRepeatedSint32Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed sint32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSint32Element(1, fakeSint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSint32Element(1, fakeSint32);
+ expectQualifiedIterable(accessor.getRepeatedSint32Iterable(1));
+ }
+ });
+
+ it('fail when setting packed sint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSint32Iterable(1, [fakeSint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSint32Iterable(1, [fakeSint32]);
+ expectQualifiedIterable(accessor.getRepeatedSint32Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed sint32 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeSint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSint32Element(1, 0, fakeSint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSint32Element(1, 0, fakeSint32);
+ expectQualifiedIterable(accessor.getRepeatedSint32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSint32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSint32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedSint32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSint32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSint32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedSint32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSint32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedSint32Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated sint64 does', () => {
+ const value1 = Int64.fromInt(-1);
+ const value2 = Int64.fromInt(0);
+
+ const unpackedValue1Value2 = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(0x08, 0x00, 0x08, 0x01);
+
+ const packedValue1Value2 = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const packedValue2Value1 = createArrayBuffer(0x0A, 0x02, 0x00, 0x01);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedSint64Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint64Element(1, value1);
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ accessor.addUnpackedSint64Element(1, value2);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ accessor.addUnpackedSint64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedSint64Element(1, 1, value1);
+ const list = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSint64Iterable(1, [value1]);
+ const list = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint64Element(1, value1);
+ accessor.addUnpackedSint64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedSint64Iterable(1, [value1]);
+ accessor.addUnpackedSint64Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedSint64Element(1, 0, value2);
+ accessor.setUnpackedSint64Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedSint64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint64Element(1, value1);
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ accessor.addPackedSint64Element(1, value2);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ accessor.addPackedSint64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSint64Element(1, 1, value1);
+ const list = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSint64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedSint64Iterable(1);
+ accessor.setPackedSint64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint64Element(1, value1);
+ accessor.addPackedSint64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedSint64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedSint64Element(1, 0, value2);
+ accessor.setPackedSint64Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedSint64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08,
+ 0x01, // unpacked value1
+ 0x0A,
+ 0x02,
+ 0x01,
+ 0x00, // packed value1 and value2
+ 0x08,
+ 0x00, // unpacked value2
+ ));
+
+ const list = accessor.getRepeatedSint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedSint64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedSint64Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedSint64Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked sint64 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSint64Iterable(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedSint64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when adding unpacked sint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSint64Iterable(1, [fakeSint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSint64Iterable(1, [fakeSint64]);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked sint64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedSint64Element(1, fakeSint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedSint64Element(1, fakeSint64);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked sint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSint64Iterable(1, [fakeSint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSint64Iterable(1, [fakeSint64]);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked sint64 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSint64Element(1, 0, fakeSint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSint64Element(1, 0, fakeSint64);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when adding packed sint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSint64Iterable(1, [fakeSint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSint64Iterable(1, [fakeSint64]);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed sint64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedSint64Element(1, fakeSint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedSint64Element(1, fakeSint64);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when setting packed sint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSint64Iterable(1, [fakeSint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSint64Iterable(1, [fakeSint64]);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed sint64 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeSint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSint64Element(1, 0, fakeSint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSint64Element(1, 0, fakeSint64);
+ expectQualifiedIterable(accessor.getRepeatedSint64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedSint64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedSint64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedSint64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedSint64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedSint64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedSint64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedSint64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedSint64Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated uint32 does', () => {
+ const value1 = 1;
+ const value2 = 0;
+
+ const unpackedValue1Value2 = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(0x08, 0x00, 0x08, 0x01);
+
+ const packedValue1Value2 = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const packedValue2Value1 = createArrayBuffer(0x0A, 0x02, 0x00, 0x01);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedUint32Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint32Element(1, value1);
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ accessor.addUnpackedUint32Element(1, value2);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ accessor.addUnpackedUint32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedUint32Element(1, 1, value1);
+ const list = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedUint32Iterable(1, [value1]);
+ const list = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint32Element(1, value1);
+ accessor.addUnpackedUint32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint32Iterable(1, [value1]);
+ accessor.addUnpackedUint32Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedUint32Element(1, 0, value2);
+ accessor.setUnpackedUint32Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedUint32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint32Element(1, value1);
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ accessor.addPackedUint32Element(1, value2);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ accessor.addPackedUint32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedUint32Element(1, 1, value1);
+ const list = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedUint32Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedUint32Iterable(1);
+ accessor.setPackedUint32Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint32Element(1, value1);
+ accessor.addPackedUint32Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedUint32Element(1, 0, value2);
+ accessor.setPackedUint32Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedUint32Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08,
+ 0x01, // unpacked value1
+ 0x0A,
+ 0x02,
+ 0x01,
+ 0x00, // packed value1 and value2
+ 0x08,
+ 0x00, // unpacked value2
+ ));
+
+ const list = accessor.getRepeatedUint32Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedUint32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedUint32Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedUint32Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked uint32 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedUint32Iterable(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedUint32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when adding unpacked uint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedUint32Iterable(1, [fakeUint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedUint32Iterable(1, [fakeUint32]);
+ expectQualifiedIterable(accessor.getRepeatedUint32Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked uint32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedUint32Element(1, fakeUint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedUint32Element(1, fakeUint32);
+ expectQualifiedIterable(accessor.getRepeatedUint32Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked uint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedUint32Iterable(1, [fakeUint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedUint32Iterable(1, [fakeUint32]);
+ expectQualifiedIterable(accessor.getRepeatedUint32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked uint32 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedUint32Element(1, 0, fakeUint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedUint32Element(1, 0, fakeUint32);
+ expectQualifiedIterable(
+ accessor.getRepeatedUint32Iterable(1),
+ );
+ }
+ });
+
+ it('fail when adding packed uint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedUint32Iterable(1, [fakeUint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedUint32Iterable(1, [fakeUint32]);
+ expectQualifiedIterable(accessor.getRepeatedUint32Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed uint32 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedUint32Element(1, fakeUint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedUint32Element(1, fakeUint32);
+ expectQualifiedIterable(accessor.getRepeatedUint32Iterable(1));
+ }
+ });
+
+ it('fail when setting packed uint32 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedUint32Iterable(1, [fakeUint32]))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedUint32Iterable(1, [fakeUint32]);
+ expectQualifiedIterable(accessor.getRepeatedUint32Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed uint32 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeUint32 = /** @type {number} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedUint32Element(1, 0, fakeUint32))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedUint32Element(1, 0, fakeUint32);
+ expectQualifiedIterable(accessor.getRepeatedUint32Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedUint32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedUint32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedUint32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedUint32Element(1, 1, 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedUint32Element(1, 1, 1);
+ expectQualifiedIterable(
+ accessor.getRepeatedUint32Iterable(1),
+ (value) => Number.isInteger(value));
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedUint32Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedUint32Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated uint64 does', () => {
+ const value1 = Int64.fromInt(1);
+ const value2 = Int64.fromInt(0);
+
+ const unpackedValue1Value2 = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const unpackedValue2Value1 = createArrayBuffer(0x08, 0x00, 0x08, 0x01);
+
+ const packedValue1Value2 = createArrayBuffer(0x0A, 0x02, 0x01, 0x00);
+ const packedValue2Value1 = createArrayBuffer(0x0A, 0x02, 0x00, 0x01);
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedUint64Size(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return unpacked values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for unpacked values', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint64Element(1, value1);
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ accessor.addUnpackedUint64Element(1, value2);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ accessor.addUnpackedUint64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ accessor.setUnpackedUint64Element(1, 1, value1);
+ const list = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedUint64Iterable(1, [value1]);
+ const list = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single unpacked value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint64Element(1, value1);
+ accessor.addUnpackedUint64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for adding unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedUint64Iterable(1, [value1]);
+ accessor.addUnpackedUint64Iterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('encode for setting single unpacked value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setUnpackedUint64Element(1, 0, value2);
+ accessor.setUnpackedUint64Element(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue2Value1);
+ });
+
+ it('encode for setting unpacked values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setUnpackedUint64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(unpackedValue1Value2);
+ });
+
+ it('return packed values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for packed values', () => {
+ const accessor = Kernel.fromArrayBuffer(packedValue1Value2);
+
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint64Element(1, value1);
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ accessor.addPackedUint64Element(1, value2);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ accessor.addPackedUint64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedUint64Element(1, 1, value1);
+ const list = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedUint64Iterable(1, [value1]);
+ const list1 = accessor.getRepeatedUint64Iterable(1);
+ accessor.setPackedUint64Iterable(1, [value2]);
+ const list2 = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value2]);
+ });
+
+ it('encode for adding single packed value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint64Element(1, value1);
+ accessor.addPackedUint64Element(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for adding packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addPackedUint64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('encode for setting single packed value', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ accessor.setPackedUint64Element(1, 0, value2);
+ accessor.setPackedUint64Element(1, 1, value1);
+
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue2Value1);
+ });
+
+ it('encode for setting packed values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setPackedUint64Iterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(packedValue1Value2);
+ });
+
+ it('return combined values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08,
+ 0x01, // unpacked value1
+ 0x0A,
+ 0x02,
+ 0x01,
+ 0x00, // packed value1 and value2
+ 0x08,
+ 0x00, // unpacked value2
+ ));
+
+ const list = accessor.getRepeatedUint64Iterable(1);
+
+ expectEqualToArray(list, [value1, value1, value2, value2]);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const result1 = accessor.getRepeatedUint64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedUint64Element(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(unpackedValue1Value2);
+
+ const size = accessor.getRepeatedUint64Size(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting unpacked uint64 value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedUint64Iterable(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedUint64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when adding unpacked uint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedUint64Iterable(1, [fakeUint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedUint64Iterable(1, [fakeUint64]);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when adding single unpacked uint64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addUnpackedUint64Element(1, fakeUint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addUnpackedUint64Element(1, fakeUint64);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when setting unpacked uint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedUint64Iterable(1, [fakeUint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedUint64Iterable(1, [fakeUint64]);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked uint64 value with null value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x80, 0x80, 0x80, 0x00));
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedUint64Element(1, 0, fakeUint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedUint64Element(1, 0, fakeUint64);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when adding packed uint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedUint64Iterable(1, [fakeUint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedUint64Iterable(1, [fakeUint64]);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when adding single packed uint64 value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addPackedUint64Element(1, fakeUint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addPackedUint64Element(1, fakeUint64);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when setting packed uint64 values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedUint64Iterable(1, [fakeUint64]))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedUint64Iterable(1, [fakeUint64]);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when setting single packed uint64 value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ const fakeUint64 = /** @type {!Int64} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedUint64Element(1, 0, fakeUint64))
+ .toThrowError('Must be Int64 instance, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedUint64Element(1, 0, fakeUint64);
+ expectQualifiedIterable(accessor.getRepeatedUint64Iterable(1));
+ }
+ });
+
+ it('fail when setting single unpacked with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setUnpackedUint64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setUnpackedUint64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedUint64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when setting single packed with out-of-bound index', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setPackedUint64Element(1, 1, Int64.fromInt(1)))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setPackedUint64Element(1, 1, Int64.fromInt(1));
+ expectQualifiedIterable(
+ accessor.getRepeatedUint64Iterable(1),
+ (value) => value instanceof Int64);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedUint64Element(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedUint64Element(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated bytes does', () => {
+ const value1 = ByteString.fromArrayBuffer((createArrayBuffer(0x61)));
+ const value2 = ByteString.fromArrayBuffer((createArrayBuffer(0x62)));
+
+ const repeatedValue1Value2 = createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x61, // value1
+ 0x0A,
+ 0x01,
+ 0x62, // value2
+ );
+ const repeatedValue2Value1 = createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x62, // value2
+ 0x0A,
+ 0x01,
+ 0x61, // value1
+ );
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedBytesIterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedBytesIterable(1);
+ const list2 = accessor.getRepeatedBytesIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedBytesSize(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const list = accessor.getRepeatedBytesIterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for values', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const list1 = accessor.getRepeatedBytesIterable(1);
+ const list2 = accessor.getRepeatedBytesIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedBytesElement(1, value1);
+ const list1 = accessor.getRepeatedBytesIterable(1);
+ accessor.addRepeatedBytesElement(1, value2);
+ const list2 = accessor.getRepeatedBytesIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedBytesIterable(1, [value1]);
+ const list1 = accessor.getRepeatedBytesIterable(1);
+ accessor.addRepeatedBytesIterable(1, [value2]);
+ const list2 = accessor.getRepeatedBytesIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single value', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ accessor.setRepeatedBytesElement(1, 1, value1);
+ const list = accessor.getRepeatedBytesIterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setRepeatedBytesIterable(1, [value1]);
+ const list = accessor.getRepeatedBytesIterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedBytesElement(1, value1);
+ accessor.addRepeatedBytesElement(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue1Value2);
+ });
+
+ it('encode for adding values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedBytesIterable(1, [value1]);
+ accessor.addRepeatedBytesIterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue1Value2);
+ });
+
+ it('encode for setting single value', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ accessor.setRepeatedBytesElement(1, 0, value2);
+ accessor.setRepeatedBytesElement(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue2Value1);
+ });
+
+ it('encode for setting values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setRepeatedBytesIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue1Value2);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const result1 = accessor.getRepeatedBytesElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedBytesElement(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const size = accessor.getRepeatedBytesSize(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting bytes value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedBytesIterable(1);
+ }).toThrowError('Expected wire type: 2 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedBytesIterable(1),
+ (value) => value instanceof ByteString);
+ }
+ });
+
+ it('fail when adding bytes values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBytes = /** @type {!ByteString} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addRepeatedBytesIterable(1, [fakeBytes]))
+ .toThrowError('Must be a ByteString, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedBytesIterable(1, [fakeBytes]);
+ expectQualifiedIterable(accessor.getRepeatedBytesIterable(1));
+ }
+ });
+
+ it('fail when adding single bytes value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBytes = /** @type {!ByteString} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addRepeatedBytesElement(1, fakeBytes))
+ .toThrowError('Must be a ByteString, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedBytesElement(1, fakeBytes);
+ expectQualifiedIterable(accessor.getRepeatedBytesIterable(1));
+ }
+ });
+
+ it('fail when setting bytes values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeBytes = /** @type {!ByteString} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedBytesIterable(1, [fakeBytes]))
+ .toThrowError('Must be a ByteString, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedBytesIterable(1, [fakeBytes]);
+ expectQualifiedIterable(accessor.getRepeatedBytesIterable(1));
+ }
+ });
+
+ it('fail when setting single bytes value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ const fakeBytes = /** @type {!ByteString} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedBytesElement(1, 0, fakeBytes))
+ .toThrowError('Must be a ByteString, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedBytesElement(1, 0, fakeBytes);
+ expectQualifiedIterable(accessor.getRepeatedBytesIterable(1));
+ }
+ });
+
+ it('fail when setting single with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x61));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedBytesElement(1, 1, value1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedBytesElement(1, 1, value1);
+ expectQualifiedIterable(
+ accessor.getRepeatedBytesIterable(1),
+ (value) => value instanceof ByteString);
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedBytesElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedBytesElement(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated string does', () => {
+ const value1 = 'a';
+ const value2 = 'b';
+
+ const repeatedValue1Value2 = createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x61, // value1
+ 0x0A,
+ 0x01,
+ 0x62, // value2
+ );
+ const repeatedValue2Value1 = createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x62, // value2
+ 0x0A,
+ 0x01,
+ 0x61, // value1
+ );
+
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list = accessor.getRepeatedStringIterable(1);
+
+ expectEqualToArray(list, []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const list1 = accessor.getRepeatedStringIterable(1);
+ const list2 = accessor.getRepeatedStringIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+
+ const size = accessor.getRepeatedStringSize(1);
+
+ expect(size).toEqual(0);
+ });
+
+ it('return values from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const list = accessor.getRepeatedStringIterable(1);
+
+ expectEqualToArray(list, [value1, value2]);
+ });
+
+ it('ensure not the same instance returned for values', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const list1 = accessor.getRepeatedStringIterable(1);
+ const list2 = accessor.getRepeatedStringIterable(1);
+
+ expect(list1).not.toBe(list2);
+ });
+
+ it('add single value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedStringElement(1, value1);
+ const list1 = accessor.getRepeatedStringIterable(1);
+ accessor.addRepeatedStringElement(1, value2);
+ const list2 = accessor.getRepeatedStringIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('add values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedStringIterable(1, [value1]);
+ const list1 = accessor.getRepeatedStringIterable(1);
+ accessor.addRepeatedStringIterable(1, [value2]);
+ const list2 = accessor.getRepeatedStringIterable(1);
+
+ expectEqualToArray(list1, [value1]);
+ expectEqualToArray(list2, [value1, value2]);
+ });
+
+ it('set a single value', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ accessor.setRepeatedStringElement(1, 1, value1);
+ const list = accessor.getRepeatedStringIterable(1);
+
+ expectEqualToArray(list, [value1, value1]);
+ });
+
+ it('set values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setRepeatedStringIterable(1, [value1]);
+ const list = accessor.getRepeatedStringIterable(1);
+
+ expectEqualToArray(list, [value1]);
+ });
+
+ it('encode for adding single value', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedStringElement(1, value1);
+ accessor.addRepeatedStringElement(1, value2);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue1Value2);
+ });
+
+ it('encode for adding values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addRepeatedStringIterable(1, [value1]);
+ accessor.addRepeatedStringIterable(1, [value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue1Value2);
+ });
+
+ it('encode for setting single value', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ accessor.setRepeatedStringElement(1, 0, value2);
+ accessor.setRepeatedStringElement(1, 1, value1);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue2Value1);
+ });
+
+ it('encode for setting values', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.setRepeatedStringIterable(1, [value1, value2]);
+ const serialized = accessor.serialize();
+
+ expect(serialized).toEqual(repeatedValue1Value2);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const result1 = accessor.getRepeatedStringElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ const result2 = accessor.getRepeatedStringElement(
+ /* fieldNumber= */ 1, /* index= */ 1);
+
+ expect(result1).toEqual(value1);
+ expect(result2).toEqual(value2);
+ });
+
+ it('return the size from the input', () => {
+ const accessor = Kernel.fromArrayBuffer(repeatedValue1Value2);
+
+ const size = accessor.getRepeatedStringSize(1);
+
+ expect(size).toEqual(2);
+ });
+
+ it('fail when getting string value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedStringIterable(1);
+ }).toThrowError('Expected wire type: 2 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expectQualifiedIterable(
+ accessor.getRepeatedStringIterable(1),
+ (value) => typeof value === 'string');
+ }
+ });
+
+ it('fail when adding string values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeString = /** @type {string} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addRepeatedStringIterable(1, [fakeString]))
+ .toThrowError('Must be string, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedStringIterable(1, [fakeString]);
+ expectQualifiedIterable(accessor.getRepeatedStringIterable(1));
+ }
+ });
+
+ it('fail when adding single string value with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeString = /** @type {string} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.addRepeatedStringElement(1, fakeString))
+ .toThrowError('Must be string, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedStringElement(1, fakeString);
+ expectQualifiedIterable(accessor.getRepeatedStringIterable(1));
+ }
+ });
+
+ it('fail when setting string values with null value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeString = /** @type {string} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedStringIterable(1, [fakeString]))
+ .toThrowError('Must be string, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedStringIterable(1, [fakeString]);
+ expectQualifiedIterable(accessor.getRepeatedStringIterable(1));
+ }
+ });
+
+ it('fail when setting single string value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ const fakeString = /** @type {string} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedStringElement(1, 0, fakeString))
+ .toThrowError('Must be string, but got: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedStringElement(1, 0, fakeString);
+ expectQualifiedIterable(accessor.getRepeatedStringIterable(1));
+ }
+ });
+
+ it('fail when setting single with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x61));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedStringElement(1, 1, value1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedStringElement(1, 1, value1);
+ expectQualifiedIterable(
+ accessor.getRepeatedStringIterable(1),
+ (value) => typeof value === 'string');
+ }
+ });
+
+ it('fail when getting element with out-of-range index', () => {
+ const accessor = Kernel.createEmpty();
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedStringElement(
+ /* fieldNumber= */ 1, /* index= */ 0);
+ }).toThrowError('Index out of bounds: index: 0 size: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getRepeatedStringElement(
+ /* fieldNumber= */ 1, /* index= */ 0))
+ .toBe(undefined);
+ }
+ });
+});
+
+describe('Kernel for repeated message does', () => {
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ expectEqualToArray(
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator),
+ []);
+ });
+
+ it('return empty accessor array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ expectEqualToArray(accessor.getRepeatedMessageAccessorIterable(1), []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ const list1 =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ const list2 =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.getRepeatedMessageSize(1, TestMessage.instanceCreator))
+ .toEqual(0);
+ });
+
+ it('return values from the input', () => {
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expectEqualToMessageArray(
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator),
+ [msg1, msg2]);
+ });
+
+ it('ensure not the same array instance returned', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const list1 =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ const list2 =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ expect(list1).not.toBe(list2);
+ });
+
+ it('ensure the same array element returned for get iterable', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const list1 =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ const list2 = accessor.getRepeatedMessageIterable(
+ 1, TestMessage.instanceCreator, /* pivot= */ 0);
+ const array1 = Array.from(list1);
+ const array2 = Array.from(list2);
+ for (let i = 0; i < array1.length; i++) {
+ expect(array1[i]).toBe(array2[i]);
+ }
+ });
+
+ it('return accessors from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const [accessor1, accessor2] =
+ [...accessor.getRepeatedMessageAccessorIterable(1)];
+ expect(accessor1.getInt32WithDefault(1)).toEqual(1);
+ expect(accessor2.getInt32WithDefault(1)).toEqual(0);
+ });
+
+ it('return accessors from the input when pivot is set', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const [accessor1, accessor2] =
+ [...accessor.getRepeatedMessageAccessorIterable(1, /* pivot= */ 0)];
+ expect(accessor1.getInt32WithDefault(1)).toEqual(1);
+ expect(accessor2.getInt32WithDefault(1)).toEqual(0);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg1 = accessor.getRepeatedMessageElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const msg2 = accessor.getRepeatedMessageElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 1, /* pivot= */ 0);
+ expect(msg1.getBoolWithDefault(
+ /* fieldNumber= */ 1, /* default= */ false))
+ .toEqual(true);
+ expect(msg2.getBoolWithDefault(
+ /* fieldNumber= */ 1, /* default= */ false))
+ .toEqual(false);
+ });
+
+ it('ensure the same array element returned', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg1 = accessor.getRepeatedMessageElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const msg2 = accessor.getRepeatedMessageElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ expect(msg1).toBe(msg2);
+ });
+
+ it('return the size from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getRepeatedMessageSize(1, TestMessage.instanceCreator))
+ .toEqual(2);
+ });
+
+ it('encode repeated message from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('add a single value', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+
+ accessor.addRepeatedMessageElement(1, msg1, TestMessage.instanceCreator);
+ accessor.addRepeatedMessageElement(1, msg2, TestMessage.instanceCreator);
+ const result =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([msg1, msg2]);
+ });
+
+ it('add values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+
+ accessor.addRepeatedMessageIterable(1, [msg1], TestMessage.instanceCreator);
+ accessor.addRepeatedMessageIterable(1, [msg2], TestMessage.instanceCreator);
+ const result =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([msg1, msg2]);
+ });
+
+ it('set a single value', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+
+ accessor.setRepeatedMessageElement(
+ /* fieldNumber= */ 1, submsg, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const result =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([submsg]);
+ });
+
+ it('write submessage changes made via getRepeatedMessagElement', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x05);
+ const expected = createArrayBuffer(0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const submsg = accessor.getRepeatedMessageElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ expect(submsg.getInt32WithDefault(1, 0)).toEqual(5);
+ submsg.setInt32(1, 0);
+
+ expect(accessor.serialize()).toEqual(expected);
+ });
+
+ it('set values', () => {
+ const accessor = Kernel.createEmpty();
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+
+ accessor.setRepeatedMessageIterable(1, [submsg]);
+ const result =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([submsg]);
+ });
+
+ it('encode for adding single value', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+ const expected =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+
+ accessor.addRepeatedMessageElement(1, msg1, TestMessage.instanceCreator);
+ accessor.addRepeatedMessageElement(1, msg2, TestMessage.instanceCreator);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('encode for adding values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+ const expected =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x08, 0x00);
+
+ accessor.addRepeatedMessageIterable(
+ 1, [msg1, msg2], TestMessage.instanceCreator);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('encode for setting single value', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+ const expected = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+
+ accessor.setRepeatedMessageElement(
+ /* fieldNumber= */ 1, submsg, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('encode for setting values', () => {
+ const accessor = Kernel.createEmpty();
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+ const expected = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+
+ accessor.setRepeatedMessageIterable(1, [submsg]);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('get accessors from set values.', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+
+ accessor.addRepeatedMessageIterable(
+ 1, [msg1, msg2], TestMessage.instanceCreator);
+
+ const [accessor1, accessor2] =
+ [...accessor.getRepeatedMessageAccessorIterable(1)];
+ expect(accessor1.getInt32WithDefault(1)).toEqual(1);
+ expect(accessor2.getInt32WithDefault(1)).toEqual(0);
+
+ // Retrieved accessors are the exact same accessors as the added messages.
+ expect(accessor1).toBe(
+ (/** @type {!InternalMessage} */ (msg1)).internalGetKernel());
+ expect(accessor2).toBe(
+ (/** @type {!InternalMessage} */ (msg2)).internalGetKernel());
+ });
+
+ it('fail when getting message value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ }).toThrow();
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const [msg1] =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ expect(msg1.serialize()).toEqual(createArrayBuffer());
+ }
+ });
+
+ it('fail when adding message values with wrong type value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.addRepeatedMessageIterable(
+ 1, [fakeValue], TestMessage.instanceCreator))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedMessageIterable(
+ 1, [fakeValue], TestMessage.instanceCreator);
+ const list =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list)).toEqual([null]);
+ }
+ });
+
+ it('fail when adding single message value with wrong type value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.addRepeatedMessageElement(
+ 1, fakeValue, TestMessage.instanceCreator))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedMessageElement(
+ 1, fakeValue, TestMessage.instanceCreator);
+ const list =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list)).toEqual([null]);
+ }
+ });
+
+ it('fail when setting message values with wrong type value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedMessageIterable(1, [fakeValue]))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedMessageIterable(1, [fakeValue]);
+ const list =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list)).toEqual([null]);
+ }
+ });
+
+ it('fail when setting single value with wrong type value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x02, 0x08, 0x00));
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.setRepeatedMessageElement(
+ /* fieldNumber= */ 1, fakeValue, TestMessage.instanceCreator,
+ /* index= */ 0))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedMessageElement(
+ /* fieldNumber= */ 1, fakeValue, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const list =
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list).length).toEqual(1);
+ }
+ });
+
+ it('fail when setting single value with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x02, 0x08, 0x00));
+ const msg1 =
+ accessor.getRepeatedMessageElement(1, TestMessage.instanceCreator, 0);
+ const bytes2 = createArrayBuffer(0x08, 0x01);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.setRepeatedMessageElement(
+ /* fieldNumber= */ 1, msg2, TestMessage.instanceCreator,
+ /* index= */ 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedMessageElement(
+ /* fieldNumber= */ 1, msg2, TestMessage.instanceCreator,
+ /* index= */ 1);
+ expectEqualToArray(
+ accessor.getRepeatedMessageIterable(1, TestMessage.instanceCreator),
+ [msg1, msg2]);
+ }
+ });
+});
+
+describe('Kernel for repeated groups does', () => {
+ it('return empty array for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ expectEqualToArray(
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator), []);
+ });
+
+ it('ensure not the same instance returned for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ const list1 =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ const list2 =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ expect(list1).not.toBe(list2);
+ });
+
+ it('return size for the empty input', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.getRepeatedGroupSize(1, TestMessage.instanceCreator))
+ .toEqual(0);
+ });
+
+ it('return values from the input', () => {
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const bytes2 = createArrayBuffer(0x08, 0x02);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expectEqualToMessageArray(
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator),
+ [msg1, msg2]);
+ });
+
+ it('ensure not the same array instance returned', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const list1 =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ const list2 =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ expect(list1).not.toBe(list2);
+ });
+
+ it('ensure the same array element returned for get iterable', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const list1 =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ const list2 = accessor.getRepeatedGroupIterable(
+ 1, TestMessage.instanceCreator, /* pivot= */ 0);
+ const array1 = Array.from(list1);
+ const array2 = Array.from(list2);
+ for (let i = 0; i < array1.length; i++) {
+ expect(array1[i]).toBe(array2[i]);
+ }
+ });
+
+ it('return accessors from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const [accessor1, accessor2] =
+ [...accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator)];
+ expect(accessor1.getInt32WithDefault(1)).toEqual(1);
+ expect(accessor2.getInt32WithDefault(1)).toEqual(2);
+ });
+
+ it('return accessors from the input when pivot is set', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const [accessor1, accessor2] = [...accessor.getRepeatedGroupIterable(
+ 1, TestMessage.instanceCreator, /* pivot= */ 0)];
+ expect(accessor1.getInt32WithDefault(1)).toEqual(1);
+ expect(accessor2.getInt32WithDefault(1)).toEqual(2);
+ });
+
+ it('return the repeated field element from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg1 = accessor.getRepeatedGroupElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const msg2 = accessor.getRepeatedGroupElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 1, /* pivot= */ 0);
+ expect(msg1.getInt32WithDefault(
+ /* fieldNumber= */ 1, /* default= */ 0))
+ .toEqual(1);
+ expect(msg2.getInt32WithDefault(
+ /* fieldNumber= */ 1, /* default= */ 0))
+ .toEqual(2);
+ });
+
+ it('ensure the same array element returned', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg1 = accessor.getRepeatedGroupElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const msg2 = accessor.getRepeatedGroupElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ expect(msg1).toBe(msg2);
+ });
+
+ it('return the size from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getRepeatedGroupSize(1, TestMessage.instanceCreator))
+ .toEqual(2);
+ });
+
+ it('encode repeated message from the input', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('add a single value', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x02);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+
+ accessor.addRepeatedGroupElement(1, msg1, TestMessage.instanceCreator);
+ accessor.addRepeatedGroupElement(1, msg2, TestMessage.instanceCreator);
+ const result =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([msg1, msg2]);
+ });
+
+ it('add values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x02);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+
+ accessor.addRepeatedGroupIterable(1, [msg1], TestMessage.instanceCreator);
+ accessor.addRepeatedGroupIterable(1, [msg2], TestMessage.instanceCreator);
+ const result =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([msg1, msg2]);
+ });
+
+ it('set a single value', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+
+ accessor.setRepeatedGroupElement(
+ /* fieldNumber= */ 1, submsg, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const result =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([submsg]);
+ });
+
+ it('write submessage changes made via getRepeatedGroupElement', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x05, 0x0C);
+ const expected = createArrayBuffer(0x0B, 0x08, 0x00, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const submsg = accessor.getRepeatedGroupElement(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator,
+ /* index= */ 0);
+ expect(submsg.getInt32WithDefault(1, 0)).toEqual(5);
+ submsg.setInt32(1, 0);
+
+ expect(accessor.serialize()).toEqual(expected);
+ });
+
+ it('set values', () => {
+ const accessor = Kernel.createEmpty();
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+
+ accessor.setRepeatedGroupIterable(1, [submsg]);
+ const result =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+
+ expect(Array.from(result)).toEqual([submsg]);
+ });
+
+ it('encode for adding single value', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+ const expected =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x00, 0x0C);
+
+ accessor.addRepeatedGroupElement(1, msg1, TestMessage.instanceCreator);
+ accessor.addRepeatedGroupElement(1, msg2, TestMessage.instanceCreator);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('encode for adding values', () => {
+ const accessor = Kernel.createEmpty();
+ const bytes1 = createArrayBuffer(0x08, 0x01);
+ const msg1 = new TestMessage(Kernel.fromArrayBuffer(bytes1));
+ const bytes2 = createArrayBuffer(0x08, 0x00);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+ const expected =
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C, 0x0B, 0x08, 0x00, 0x0C);
+
+ accessor.addRepeatedGroupIterable(
+ 1, [msg1, msg2], TestMessage.instanceCreator);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('encode for setting single value', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x00, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+ const expected = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+
+ accessor.setRepeatedGroupElement(
+ /* fieldNumber= */ 1, submsg, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('encode for setting values', () => {
+ const accessor = Kernel.createEmpty();
+ const subbytes = createArrayBuffer(0x08, 0x01);
+ const submsg = new TestMessage(Kernel.fromArrayBuffer(subbytes));
+ const expected = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+
+ accessor.setRepeatedGroupIterable(1, [submsg]);
+ const result = accessor.serialize();
+
+ expect(result).toEqual(expected);
+ });
+
+ it('fail when getting groups value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => {
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ }).toThrow();
+ }
+ });
+
+ it('fail when adding group values with wrong type value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.addRepeatedGroupIterable(
+ 1, [fakeValue], TestMessage.instanceCreator))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedGroupIterable(
+ 1, [fakeValue], TestMessage.instanceCreator);
+ const list =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list)).toEqual([null]);
+ }
+ });
+
+ it('fail when adding single group value with wrong type value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.addRepeatedGroupElement(
+ 1, fakeValue, TestMessage.instanceCreator))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.addRepeatedGroupElement(
+ 1, fakeValue, TestMessage.instanceCreator);
+ const list =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list)).toEqual([null]);
+ }
+ });
+
+ it('fail when setting message values with wrong type value', () => {
+ const accessor = Kernel.createEmpty();
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => accessor.setRepeatedGroupIterable(1, [fakeValue]))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedGroupIterable(1, [fakeValue]);
+ const list =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list)).toEqual([null]);
+ }
+ });
+
+ it('fail when setting single value with wrong type value', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0B, 0x08, 0x00, 0x0C));
+ const fakeValue = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.setRepeatedGroupElement(
+ /* fieldNumber= */ 1, fakeValue, TestMessage.instanceCreator,
+ /* index= */ 0))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedGroupElement(
+ /* fieldNumber= */ 1, fakeValue, TestMessage.instanceCreator,
+ /* index= */ 0);
+ const list =
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator);
+ expect(Array.from(list).length).toEqual(1);
+ }
+ });
+
+ it('fail when setting single value with out-of-bound index', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0B, 0x08, 0x00, 0x0C));
+ const msg1 =
+ accessor.getRepeatedGroupElement(1, TestMessage.instanceCreator, 0);
+ const bytes2 = createArrayBuffer(0x08, 0x01);
+ const msg2 = new TestMessage(Kernel.fromArrayBuffer(bytes2));
+ if (CHECK_CRITICAL_STATE) {
+ expect(
+ () => accessor.setRepeatedGroupElement(
+ /* fieldNumber= */ 1, msg2, TestMessage.instanceCreator,
+ /* index= */ 1))
+ .toThrowError('Index out of bounds: index: 1 size: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setRepeatedGroupElement(
+ /* fieldNumber= */ 1, msg2, TestMessage.instanceCreator,
+ /* index= */ 1);
+ expectEqualToArray(
+ accessor.getRepeatedGroupIterable(1, TestMessage.instanceCreator),
+ [msg1, msg2]);
+ }
+ });
+});
diff --git a/js/experimental/runtime/kernel/kernel_test.js b/js/experimental/runtime/kernel/kernel_test.js
new file mode 100644
index 0000000..e72be4f
--- /dev/null
+++ b/js/experimental/runtime/kernel/kernel_test.js
@@ -0,0 +1,2329 @@
+/**
+ * @fileoverview Tests for kernel.js.
+ */
+goog.module('protobuf.runtime.KernelTest');
+
+goog.setTestOnly();
+
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const InternalMessage = goog.require('protobuf.binary.InternalMessage');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
+// Note to the reader:
+// Since the lazy accessor behavior changes with the checking level some of the
+// tests in this file have to know which checking level is enable to make
+// correct assertions.
+const {CHECK_BOUNDS, CHECK_CRITICAL_STATE, CHECK_CRITICAL_TYPE, CHECK_TYPE, MAX_FIELD_NUMBER} = goog.require('protobuf.internal.checks');
+
+/**
+ * @param {...number} bytes
+ * @return {!ArrayBuffer}
+ */
+function createArrayBuffer(...bytes) {
+ return new Uint8Array(bytes).buffer;
+}
+
+describe('Kernel', () => {
+ it('encodes none for the empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ expect(accessor.serialize()).toEqual(new ArrayBuffer(0));
+ });
+
+ it('encodes and decodes max field number', () => {
+ const accessor = Kernel.fromArrayBuffer(
+ createArrayBuffer(0xF8, 0xFF, 0xFF, 0xFF, 0x0F, 0x01));
+ expect(accessor.getBoolWithDefault(MAX_FIELD_NUMBER)).toBe(true);
+ accessor.setBool(MAX_FIELD_NUMBER, false);
+ expect(accessor.serialize())
+ .toEqual(createArrayBuffer(0xF8, 0xFF, 0xFF, 0xFF, 0x0F, 0x00));
+ });
+
+ it('uses the default pivot point', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ expect(accessor.getPivot()).toBe(24);
+ });
+
+ it('makes the pivot point configurable', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0), 50);
+ expect(accessor.getPivot()).toBe(50);
+ });
+});
+
+describe('Kernel hasFieldNumber', () => {
+ it('returns false for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ });
+
+ it('returns true for non-empty input', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.hasFieldNumber(1)).toBe(true);
+ });
+
+ it('returns false for empty array', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setPackedBoolIterable(1, []);
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ });
+
+ it('returns true for non-empty array', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setPackedBoolIterable(1, [true]);
+ expect(accessor.hasFieldNumber(1)).toBe(true);
+ });
+
+ it('updates value after write', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ accessor.setBool(1, false);
+ expect(accessor.hasFieldNumber(1)).toBe(true);
+ });
+});
+
+describe('Kernel clear field does', () => {
+ it('clear the field set', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setBool(1, true);
+ accessor.clearField(1);
+
+ expect(accessor.hasFieldNumber(1)).toEqual(false);
+ expect(accessor.serialize()).toEqual(new ArrayBuffer(0));
+ expect(accessor.getBoolWithDefault(1)).toEqual(false);
+ });
+
+ it('clear the field decoded', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.clearField(1);
+
+ expect(accessor.hasFieldNumber(1)).toEqual(false);
+ expect(accessor.serialize()).toEqual(new ArrayBuffer(0));
+ expect(accessor.getBoolWithDefault(1)).toEqual(false);
+ });
+
+ it('clear the field read', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getBoolWithDefault(1)).toEqual(true);
+ accessor.clearField(1);
+
+ expect(accessor.hasFieldNumber(1)).toEqual(false);
+ expect(accessor.serialize()).toEqual(new ArrayBuffer(0));
+ expect(accessor.getBoolWithDefault(1)).toEqual(false);
+ });
+
+ it('clear set and copied fields without affecting the old', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setBool(1, true);
+
+ const clonedAccessor = accessor.shallowCopy();
+ clonedAccessor.clearField(1);
+
+ expect(accessor.hasFieldNumber(1)).toEqual(true);
+ expect(accessor.getBoolWithDefault(1)).toEqual(true);
+ expect(clonedAccessor.hasFieldNumber(1)).toEqual(false);
+ expect(clonedAccessor.serialize()).toEqual(new ArrayBuffer(0));
+ expect(clonedAccessor.getBoolWithDefault(1)).toEqual(false);
+ });
+
+ it('clear decoded and copied fields without affecting the old', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+
+ const clonedAccessor = accessor.shallowCopy();
+ clonedAccessor.clearField(1);
+
+ expect(accessor.hasFieldNumber(1)).toEqual(true);
+ expect(accessor.getBoolWithDefault(1)).toEqual(true);
+ expect(clonedAccessor.hasFieldNumber(1)).toEqual(false);
+ expect(clonedAccessor.serialize()).toEqual(new ArrayBuffer(0));
+ expect(clonedAccessor.getBoolWithDefault(1)).toEqual(false);
+ });
+
+ it('clear read and copied fields without affecting the old', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getBoolWithDefault(1)).toEqual(true);
+
+ const clonedAccessor = accessor.shallowCopy();
+ clonedAccessor.clearField(1);
+
+ expect(accessor.hasFieldNumber(1)).toEqual(true);
+ expect(accessor.getBoolWithDefault(1)).toEqual(true);
+ expect(clonedAccessor.hasFieldNumber(1)).toEqual(false);
+ expect(clonedAccessor.serialize()).toEqual(new ArrayBuffer(0));
+ expect(clonedAccessor.getBoolWithDefault(1)).toEqual(false);
+ });
+
+ it('clear the max field number', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setBool(MAX_FIELD_NUMBER, true);
+
+ accessor.clearField(MAX_FIELD_NUMBER);
+
+ expect(accessor.hasFieldNumber(MAX_FIELD_NUMBER)).toEqual(false);
+ expect(accessor.getBoolWithDefault(MAX_FIELD_NUMBER)).toEqual(false);
+ });
+});
+
+describe('Kernel shallow copy does', () => {
+ it('work for singular fields', () => {
+ const accessor = Kernel.createEmpty();
+ accessor.setBool(1, true);
+ accessor.setBool(MAX_FIELD_NUMBER, true);
+ const clonedAccessor = accessor.shallowCopy();
+ expect(clonedAccessor.getBoolWithDefault(1)).toEqual(true);
+ expect(clonedAccessor.getBoolWithDefault(MAX_FIELD_NUMBER)).toEqual(true);
+
+ accessor.setBool(1, false);
+ accessor.setBool(MAX_FIELD_NUMBER, false);
+ expect(clonedAccessor.getBoolWithDefault(1)).toEqual(true);
+ expect(clonedAccessor.getBoolWithDefault(MAX_FIELD_NUMBER)).toEqual(true);
+ });
+
+ it('work for repeated fields', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedBoolIterable(2, [true, true]);
+
+ const clonedAccessor = accessor.shallowCopy();
+
+ // Modify a repeated field after clone
+ accessor.addUnpackedBoolElement(2, true);
+
+ const array = Array.from(clonedAccessor.getRepeatedBoolIterable(2));
+ expect(array).toEqual([true, true]);
+ });
+
+ it('work for repeated fields', () => {
+ const accessor = Kernel.createEmpty();
+
+ accessor.addUnpackedBoolIterable(2, [true, true]);
+
+ const clonedAccessor = accessor.shallowCopy();
+
+ // Modify a repeated field after clone
+ accessor.addUnpackedBoolElement(2, true);
+
+ const array = Array.from(clonedAccessor.getRepeatedBoolIterable(2));
+ expect(array).toEqual([true, true]);
+ });
+
+ it('return the correct bytes after serialization', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x10, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes, /* pivot= */ 1);
+ const clonedAccessor = accessor.shallowCopy();
+
+ accessor.setBool(1, false);
+
+ expect(clonedAccessor.getBoolWithDefault(1)).toEqual(true);
+ expect(clonedAccessor.serialize()).toEqual(bytes);
+ });
+});
+
+describe('Kernel for singular boolean does', () => {
+ it('return false for the empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(false);
+ });
+
+ it('return the value from the input', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(true);
+ });
+
+ it('encode the value from the input', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode the value from the input after read', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('return the value from multiple inputs', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(false);
+ });
+
+ it('encode the value from multiple inputs', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode the value from multiple inputs after read', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.getBoolWithDefault(/* fieldNumber= */ 1);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('return the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setBool(1, true);
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(true);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01, 0x08, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x08, 0x01);
+ accessor.setBool(1, true);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('return the bool value from cache', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(true);
+ // Make sure the value is cached.
+ bytes[1] = 0x00;
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(true);
+ });
+
+ it('fail when getting bool value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getBoolWithDefault(/* fieldNumber= */ 1);
+ }).toThrowError('Expected wire type: 0 but found: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(true);
+ }
+ });
+
+ it('fail when setting bool value with out-of-range field number', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ if (CHECK_TYPE) {
+ expect(() => accessor.setBool(MAX_FIELD_NUMBER + 1, false))
+ .toThrowError('Field number is out of range: 536870912');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setBool(MAX_FIELD_NUMBER + 1, false);
+ expect(accessor.getBoolWithDefault(MAX_FIELD_NUMBER + 1)).toBe(false);
+ }
+ });
+
+ it('fail when setting bool value with number value', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const fakeBoolean = /** @type {boolean} */ (/** @type {*} */ (2));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => accessor.setBool(1, fakeBoolean))
+ .toThrowError('Must be a boolean, but got: 2');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setBool(1, fakeBoolean);
+ expect(accessor.getBoolWithDefault(
+ /* fieldNumber= */ 1))
+ .toBe(2);
+ }
+ });
+});
+
+describe('Kernel for singular message does', () => {
+ it('return message from the input', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg = accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ expect(msg.getBoolWithDefault(1, false)).toBe(true);
+ });
+
+ it('return message from the input when pivot is set', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes, /* pivot= */ 0);
+ const msg = accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ expect(msg.getBoolWithDefault(1, false)).toBe(true);
+ });
+
+ it('encode message from the input', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode message from the input after read', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('return message from multiple inputs', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x10, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg = accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ expect(msg.getBoolWithDefault(1, false)).toBe(true);
+ expect(msg.getBoolWithDefault(2, false)).toBe(true);
+ });
+
+ it('encode message from multiple inputs', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x10, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode message merged from multiple inputs after read', () => {
+ const bytes =
+ createArrayBuffer(0x0A, 0x02, 0x08, 0x01, 0x0A, 0x02, 0x10, 0x01);
+ const expected = createArrayBuffer(0x0A, 0x04, 0x08, 0x01, 0x10, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ expect(accessor.serialize()).toEqual(expected);
+ });
+
+ it('return null for generic accessor', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const accessor1 = accessor.getMessageAccessorOrNull(7);
+ expect(accessor1).toBe(null);
+ });
+
+ it('return null for generic accessor when pivot is set', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const accessor1 = accessor.getMessageAccessorOrNull(7, /* pivot= */ 0);
+ expect(accessor1).toBe(null);
+ });
+
+ it('return generic accessor from the input', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const accessor1 = accessor.getMessageAccessorOrNull(1);
+ expect(accessor1.getBoolWithDefault(1, false)).toBe(true);
+ // Second call returns a new instance, isn't cached.
+ const accessor2 = accessor.getMessageAccessorOrNull(1);
+ expect(accessor2.getBoolWithDefault(1, false)).toBe(true);
+ expect(accessor2).not.toBe(accessor1);
+ });
+
+ it('return generic accessor from the cached input', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const wrappedMessage =
+ accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+
+ // Returns accessor from the cached wrapper instance.
+ const accessor1 = accessor.getMessageAccessorOrNull(1);
+ expect(accessor1.getBoolWithDefault(1, false)).toBe(true);
+ expect(accessor1).toBe(
+ (/** @type {!InternalMessage} */ (wrappedMessage)).internalGetKernel());
+
+ // Second call returns exact same instance.
+ const accessor2 = accessor.getMessageAccessorOrNull(1);
+ expect(accessor2.getBoolWithDefault(1, false)).toBe(true);
+ expect(accessor2).toBe(
+ (/** @type {!InternalMessage} */ (wrappedMessage)).internalGetKernel());
+ expect(accessor2).toBe(accessor1);
+ });
+
+ it('return message from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const subaccessor = Kernel.fromArrayBuffer(bytes);
+ const submsg1 = new TestMessage(subaccessor);
+ accessor.setMessage(1, submsg1);
+ const submsg2 = accessor.getMessage(1, TestMessage.instanceCreator);
+ expect(submsg1).toBe(submsg2);
+ });
+
+ it('encode message from setter', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const subaccessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const subsubaccessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ const subsubmsg = new TestMessage(subsubaccessor);
+ subaccessor.setMessage(1, subsubmsg);
+ const submsg = new TestMessage(subaccessor);
+ accessor.setMessage(1, submsg);
+ const expected = createArrayBuffer(0x0A, 0x04, 0x0A, 0x02, 0x08, 0x01);
+ expect(accessor.serialize()).toEqual(expected);
+ });
+
+ it('encode message with multiple submessage from setter', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const subaccessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const subsubaccessor1 =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ const subsubaccessor2 =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x02));
+
+ const subsubmsg1 = new TestMessage(subsubaccessor1);
+ const subsubmsg2 = new TestMessage(subsubaccessor2);
+
+ subaccessor.setMessage(1, subsubmsg1);
+ subaccessor.setMessage(2, subsubmsg2);
+
+ const submsg = new TestMessage(subaccessor);
+ accessor.setMessage(1, submsg);
+
+ const expected = createArrayBuffer(
+ 0x0A, 0x08, 0x0A, 0x02, 0x08, 0x01, 0x12, 0x02, 0x08, 0x02);
+ expect(accessor.serialize()).toEqual(expected);
+ });
+
+ it('leave hasFieldNumber unchanged after getMessageOrNull', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ expect(accessor.getMessageOrNull(1, TestMessage.instanceCreator))
+ .toBe(null);
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ });
+
+ it('serialize changes to submessages made with getMessageOrNull', () => {
+ const intTwoBytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x02);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+ const mutableSubMessage =
+ accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ mutableSubMessage.setInt32(1, 10);
+ const intTenBytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x0A);
+ expect(accessor.serialize()).toEqual(intTenBytes);
+ });
+
+ it('serialize additions to submessages made with getMessageOrNull', () => {
+ const intTwoBytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x02);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+ const mutableSubMessage =
+ accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ mutableSubMessage.setInt32(2, 3);
+ // Sub message contains the original field, plus the new one.
+ expect(accessor.serialize())
+ .toEqual(createArrayBuffer(0x0A, 0x04, 0x08, 0x02, 0x10, 0x03));
+ });
+
+ it('fail with getMessageOrNull if immutable message exist in cache', () => {
+ const intTwoBytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x02);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+
+ const readOnly = accessor.getMessage(1, TestMessage.instanceCreator);
+ if (CHECK_TYPE) {
+ expect(() => accessor.getMessageOrNull(1, TestMessage.instanceCreator))
+ .toThrow();
+ } else {
+ const mutableSubMessage =
+ accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ // The instance returned by getMessageOrNull is the exact same instance.
+ expect(mutableSubMessage).toBe(readOnly);
+
+ // Serializing the submessage does not write the changes
+ mutableSubMessage.setInt32(1, 0);
+ expect(accessor.serialize()).toEqual(intTwoBytes);
+ }
+ });
+
+ it('change hasFieldNumber after getMessageAttach', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ expect(accessor.getMessageAttach(1, TestMessage.instanceCreator))
+ .not.toBe(null);
+ expect(accessor.hasFieldNumber(1)).toBe(true);
+ });
+
+ it('change hasFieldNumber after getMessageAttach when pivot is set', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ expect(accessor.getMessageAttach(
+ 1, TestMessage.instanceCreator, /* pivot= */ 1))
+ .not.toBe(null);
+ expect(accessor.hasFieldNumber(1)).toBe(true);
+ });
+
+ it('serialize submessages made with getMessageAttach', () => {
+ const accessor = Kernel.createEmpty();
+ const mutableSubMessage =
+ accessor.getMessageAttach(1, TestMessage.instanceCreator);
+ mutableSubMessage.setInt32(1, 10);
+ const intTenBytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x0A);
+ expect(accessor.serialize()).toEqual(intTenBytes);
+ });
+
+ it('serialize additions to submessages using getMessageAttach', () => {
+ const intTwoBytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x02);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+ const mutableSubMessage =
+ accessor.getMessageAttach(1, TestMessage.instanceCreator);
+ mutableSubMessage.setInt32(2, 3);
+ // Sub message contains the original field, plus the new one.
+ expect(accessor.serialize())
+ .toEqual(createArrayBuffer(0x0A, 0x04, 0x08, 0x02, 0x10, 0x03));
+ });
+
+ it('fail with getMessageAttach if immutable message exist in cache', () => {
+ const intTwoBytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x02);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+
+ const readOnly = accessor.getMessage(1, TestMessage.instanceCreator);
+ if (CHECK_TYPE) {
+ expect(() => accessor.getMessageAttach(1, TestMessage.instanceCreator))
+ .toThrow();
+ } else {
+ const mutableSubMessage =
+ accessor.getMessageAttach(1, TestMessage.instanceCreator);
+ // The instance returned by getMessageOrNull is the exact same instance.
+ expect(mutableSubMessage).toBe(readOnly);
+
+ // Serializing the submessage does not write the changes
+ mutableSubMessage.setInt32(1, 0);
+ expect(accessor.serialize()).toEqual(intTwoBytes);
+ }
+ });
+
+ it('read default message return empty message with getMessage', () => {
+ const bytes = new ArrayBuffer(0);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getMessage(1, TestMessage.instanceCreator)).toBeTruthy();
+ expect(accessor.getMessage(1, TestMessage.instanceCreator).serialize())
+ .toEqual(bytes);
+ });
+
+ it('read default message return null with getMessageOrNull', () => {
+ const bytes = new ArrayBuffer(0);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getMessageOrNull(1, TestMessage.instanceCreator))
+ .toBe(null);
+ });
+
+ it('read message preserve reference equality', () => {
+ const bytes = createArrayBuffer(0x0A, 0x02, 0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg1 = accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ const msg2 = accessor.getMessageOrNull(1, TestMessage.instanceCreator);
+ const msg3 = accessor.getMessageAttach(1, TestMessage.instanceCreator);
+ expect(msg1).toBe(msg2);
+ expect(msg1).toBe(msg3);
+ });
+
+ it('fail when getting message with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ expect(() => accessor.getMessageOrNull(1, TestMessage.instanceCreator))
+ .toThrow();
+ });
+
+ it('fail when submessage has incomplete data', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x08));
+ expect(() => accessor.getMessageOrNull(1, TestMessage.instanceCreator))
+ .toThrow();
+ });
+
+ it('fail when mutable submessage has incomplete data', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x08));
+ expect(() => accessor.getMessageAttach(1, TestMessage.instanceCreator))
+ .toThrow();
+ });
+
+ it('fail when getting message with null instance constructor', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x02, 0x08, 0x01));
+ const nullMessage = /** @type {function(!Kernel):!TestMessage} */
+ (/** @type {*} */ (null));
+ expect(() => accessor.getMessageOrNull(1, nullMessage)).toThrow();
+ });
+
+ it('fail when setting message value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const fakeMessage = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => accessor.setMessage(1, fakeMessage))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setMessage(1, fakeMessage);
+ expect(accessor.getMessageOrNull(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator))
+ .toBeNull();
+ }
+ });
+});
+
+describe('Bytes access', () => {
+ const simpleByteString = ByteString.fromArrayBuffer(createArrayBuffer(1));
+
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getBytesWithDefault(1)).toEqual(ByteString.EMPTY);
+ });
+
+ it('returns the default from parameter', () => {
+ const defaultByteString = ByteString.fromArrayBuffer(createArrayBuffer(1));
+ const returnValue = ByteString.fromArrayBuffer(createArrayBuffer(1));
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getBytesWithDefault(1, defaultByteString))
+ .toEqual(returnValue);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x01));
+ expect(accessor.getBytesWithDefault(1)).toEqual(simpleByteString);
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(
+ createArrayBuffer(0x0A, 0x01, 0x00, 0x0A, 0x01, 0x01));
+ expect(accessor.getBytesWithDefault(1)).toEqual(simpleByteString);
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getBytesWithDefault(1);
+ }).toThrowError('Expected wire type: 2 but found: 1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const arrayBuffer = createArrayBuffer(1);
+ expect(accessor.getBytesWithDefault(1))
+ .toEqual(ByteString.fromArrayBuffer(arrayBuffer));
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(
+ () => Kernel.createEmpty().getBytesWithDefault(-1, simpleByteString))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getBytesWithDefault(-1, simpleByteString))
+ .toEqual(simpleByteString);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x0A, 0x01, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setBytes(1, simpleByteString);
+ expect(accessor.getBytesWithDefault(1)).toEqual(simpleByteString);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x0A, 0x01, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x0A, 0x01, 0x01);
+ accessor.setBytes(1, simpleByteString);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x0A, 0x01, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getBytesWithDefault(1)).toEqual(simpleByteString);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getBytesWithDefault(1)).toEqual(simpleByteString);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setBytes(-1, simpleByteString))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setBytes(-1, simpleByteString);
+ expect(accessor.getBytesWithDefault(-1)).toEqual(simpleByteString);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setBytes(
+ 1, /** @type {!ByteString} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setBytes(
+ 1, /** @type {!ByteString} */ (/** @type {*} */ (null)));
+ expect(accessor.getBytesWithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Fixed32 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getFixed32WithDefault(1)).toEqual(0);
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getFixed32WithDefault(1, 2)).toEqual(2);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00));
+ expect(accessor.getFixed32WithDefault(1)).toEqual(1);
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x0D, 0x01, 0x00, 0x80, 0x00, 0x0D, 0x02, 0x00, 0x00, 0x00));
+ expect(accessor.getFixed32WithDefault(1)).toEqual(2);
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getFixed32WithDefault(1);
+ }).toThrowError('Expected wire type: 5 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getFixed32WithDefault(1)).toEqual(8421504);
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getFixed32WithDefault(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getFixed32WithDefault(-1, 1)).toEqual(1);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setFixed32(1, 2);
+ expect(accessor.getFixed32WithDefault(1)).toEqual(2);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00);
+ accessor.setFixed32(1, 0);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getFixed32WithDefault(1)).toBe(1);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getFixed32WithDefault(1)).toBe(1);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setFixed32(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFixed32(-1, 1);
+ expect(accessor.getFixed32WithDefault(-1)).toEqual(1);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setFixed32(
+ 1, /** @type {number} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFixed32(1, /** @type {number} */ (/** @type {*} */ (null)));
+ expect(accessor.getFixed32WithDefault(1)).toEqual(null);
+ }
+ });
+
+ it('throws in setter for negative value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => Kernel.createEmpty().setFixed32(1, -1)).toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFixed32(1, -1);
+ expect(accessor.getFixed32WithDefault(1)).toEqual(-1);
+ }
+ });
+});
+
+describe('Fixed64 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getFixed64WithDefault(1)).toEqual(Int64.fromInt(0));
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getFixed64WithDefault(1, Int64.fromInt(2)))
+ .toEqual(Int64.fromInt(2));
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ expect(accessor.getFixed64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x02, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ expect(accessor.getFixed64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ if (CHECK_CRITICAL_STATE) {
+ it('fails when getting value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(
+ createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ expect(() => {
+ accessor.getFixed64WithDefault(1);
+ }).toThrow();
+ });
+ }
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(
+ () =>
+ Kernel.createEmpty().getFixed64WithDefault(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getFixed64WithDefault(-1, Int64.fromInt(1)))
+ .toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setFixed64(1, Int64.fromInt(2));
+ expect(accessor.getFixed64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ it('encode the value from setter', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes =
+ createArrayBuffer(0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ accessor.setFixed64(1, Int64.fromInt(0));
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getFixed64WithDefault(1)).toEqual(Int64.fromInt(1));
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getFixed64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setFixed64(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFixed64(-1, Int64.fromInt(1));
+ expect(accessor.getFixed64WithDefault(-1)).toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setSfixed64(
+ 1, /** @type {!Int64} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFixed64(1, /** @type {!Int64} */ (/** @type {*} */ (null)));
+ expect(accessor.getFixed64WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Float access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getFloatWithDefault(1)).toEqual(0);
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getFloatWithDefault(1, 2)).toEqual(2);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x80, 0x3F));
+ expect(accessor.getFloatWithDefault(1)).toEqual(1);
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x0D, 0x00, 0x00, 0x80, 0x3F, 0x0D, 0x00, 0x00, 0x80, 0xBF));
+ expect(accessor.getFloatWithDefault(1)).toEqual(-1);
+ });
+
+ if (CHECK_CRITICAL_STATE) {
+ it('fails when getting float value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F));
+ expect(() => {
+ accessor.getFloatWithDefault(1);
+ }).toThrow();
+ });
+ }
+
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getFloatWithDefault(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getFloatWithDefault(-1, 1)).toEqual(1);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x0D, 0x00, 0x00, 0x80, 0x3F);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setFloat(1, 1.6);
+ expect(accessor.getFloatWithDefault(1)).toEqual(Math.fround(1.6));
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x0D, 0x00, 0x00, 0x80, 0x3F);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00);
+ accessor.setFloat(1, 0);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns float value from cache', () => {
+ const bytes = createArrayBuffer(0x0D, 0x00, 0x00, 0x80, 0x3F);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getFloatWithDefault(1)).toBe(1);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getFloatWithDefault(1)).toBe(1);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setFloat(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFloat(-1, 1);
+ expect(accessor.getFloatWithDefault(-1)).toEqual(1);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setFloat(
+ 1, /** @type {number} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFloat(1, /** @type {number} */ (/** @type {*} */ (null)));
+ expect(accessor.getFloatWithDefault(1)).toEqual(0);
+ }
+ });
+
+ it('throws in setter for value outside of float32 precision', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => Kernel.createEmpty().setFloat(1, Number.MAX_VALUE))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setFloat(1, Number.MAX_VALUE);
+ expect(accessor.getFloatWithDefault(1)).toEqual(Infinity);
+ }
+ });
+});
+
+describe('Int32 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getInt32WithDefault(1)).toEqual(0);
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getInt32WithDefault(1, 2)).toEqual(2);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ expect(accessor.getInt32WithDefault(1)).toEqual(1);
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01, 0x08, 0x02));
+ expect(accessor.getInt32WithDefault(1)).toEqual(2);
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getInt32WithDefault(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getInt32WithDefault(1)).toEqual(0);
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getInt32WithDefault(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getInt32WithDefault(-1, 1)).toEqual(1);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setInt32(1, 2);
+ expect(accessor.getInt32WithDefault(1)).toEqual(2);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x08, 0x00);
+ accessor.setInt32(1, 0);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getInt32WithDefault(1)).toBe(1);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getInt32WithDefault(1)).toBe(1);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setInt32(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setInt32(-1, 1);
+ expect(accessor.getInt32WithDefault(-1)).toEqual(1);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setInt32(
+ 1, /** @type {number} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setInt32(1, /** @type {number} */ (/** @type {*} */ (null)));
+ expect(accessor.getInt32WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Int64 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getInt64WithDefault(1)).toEqual(Int64.fromInt(0));
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getInt64WithDefault(1, Int64.fromInt(2)))
+ .toEqual(Int64.fromInt(2));
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ expect(accessor.getInt64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01, 0x08, 0x02));
+ expect(accessor.getInt64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getInt64WithDefault(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getInt64WithDefault(1)).toEqual(Int64.fromInt(0));
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(
+ () => Kernel.createEmpty().getInt64WithDefault(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getInt64WithDefault(-1, Int64.fromInt(1)))
+ .toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setInt64(1, Int64.fromInt(2));
+ expect(accessor.getInt64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x08, 0x00);
+ accessor.setInt64(1, Int64.fromInt(0));
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getInt64WithDefault(1)).toEqual(Int64.fromInt(1));
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getInt64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setInt64(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setInt64(-1, Int64.fromInt(1));
+ expect(accessor.getInt64WithDefault(-1)).toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setInt64(
+ 1, /** @type {!Int64} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setInt64(1, /** @type {!Int64} */ (/** @type {*} */ (null)));
+ expect(accessor.getInt64WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Sfixed32 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSfixed32WithDefault(1)).toEqual(0);
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSfixed32WithDefault(1, 2)).toEqual(2);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00));
+ expect(accessor.getSfixed32WithDefault(1)).toEqual(1);
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x0D, 0x01, 0x00, 0x80, 0x00, 0x0D, 0x02, 0x00, 0x00, 0x00));
+ expect(accessor.getSfixed32WithDefault(1)).toEqual(2);
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x80, 0x80, 0x80, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getSfixed32WithDefault(1);
+ }).toThrowError('Expected wire type: 5 but found: 0');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getSfixed32WithDefault(1)).toEqual(8421504);
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getSfixed32WithDefault(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getSfixed32WithDefault(-1, 1)).toEqual(1);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setSfixed32(1, 2);
+ expect(accessor.getSfixed32WithDefault(1)).toEqual(2);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00);
+ accessor.setSfixed32(1, 0);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x0D, 0x01, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getSfixed32WithDefault(1)).toBe(1);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getSfixed32WithDefault(1)).toBe(1);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setSfixed32(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setSfixed32(-1, 1);
+ expect(accessor.getSfixed32WithDefault(-1)).toEqual(1);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setSfixed32(
+ 1, /** @type {number} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setSfixed32(1, /** @type {number} */ (/** @type {*} */ (null)));
+ expect(accessor.getSfixed32WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Sfixed64 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSfixed64WithDefault(1)).toEqual(Int64.fromInt(0));
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSfixed64WithDefault(1, Int64.fromInt(2)))
+ .toEqual(Int64.fromInt(2));
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ expect(accessor.getSfixed64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x02, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ expect(accessor.getSfixed64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ if (CHECK_CRITICAL_STATE) {
+ it('fails when getting value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(
+ createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ expect(() => {
+ accessor.getSfixed64WithDefault(1);
+ }).toThrow();
+ });
+ }
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(
+ () =>
+ Kernel.createEmpty().getSfixed64WithDefault(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getSfixed64WithDefault(-1, Int64.fromInt(1)))
+ .toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setSfixed64(1, Int64.fromInt(2));
+ expect(accessor.getSfixed64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ it('encode the value from setter', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes =
+ createArrayBuffer(0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ accessor.setSfixed64(1, Int64.fromInt(0));
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getSfixed64WithDefault(1)).toEqual(Int64.fromInt(1));
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getSfixed64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setSfixed64(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setSfixed64(-1, Int64.fromInt(1));
+ expect(accessor.getSfixed64WithDefault(-1)).toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setSfixed64(
+ 1, /** @type {!Int64} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setSfixed64(1, /** @type {!Int64} */ (/** @type {*} */ (null)));
+ expect(accessor.getSfixed64WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Sint32 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSint32WithDefault(1)).toEqual(0);
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSint32WithDefault(1, 2)).toEqual(2);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x02));
+ expect(accessor.getSint32WithDefault(1)).toEqual(1);
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x03, 0x08, 0x02));
+ expect(accessor.getSint32WithDefault(1)).toEqual(1);
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getSint32WithDefault(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getSint32WithDefault(1)).toEqual(0);
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getSint32WithDefault(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getSint32WithDefault(-1, 1)).toEqual(1);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setSint32(1, 2);
+ expect(accessor.getSint32WithDefault(1)).toEqual(2);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x08, 0x00);
+ accessor.setSint32(1, 0);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x08, 0x02);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getSint32WithDefault(1)).toBe(1);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getSint32WithDefault(1)).toBe(1);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setSint32(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setSint32(-1, 1);
+ expect(accessor.getSint32WithDefault(-1)).toEqual(1);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setSint32(
+ 1, /** @type {number} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setSint32(1, /** @type {number} */ (/** @type {*} */ (null)));
+ expect(accessor.getSint32WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('SInt64 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSint64WithDefault(1)).toEqual(Int64.fromInt(0));
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getSint64WithDefault(1, Int64.fromInt(2)))
+ .toEqual(Int64.fromInt(2));
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x02));
+ expect(accessor.getSint64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01, 0x08, 0x02));
+ expect(accessor.getSint64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getSint64WithDefault(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getSint64WithDefault(1)).toEqual(Int64.fromInt(0));
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(
+ () => Kernel.createEmpty().getSint64WithDefault(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getSint64WithDefault(-1, Int64.fromInt(1)))
+ .toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setSint64(1, Int64.fromInt(2));
+ expect(accessor.getSint64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x08, 0x00);
+ accessor.setSint64(1, Int64.fromInt(0));
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x08, 0x02);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getSint64WithDefault(1)).toEqual(Int64.fromInt(1));
+ // Make sure the value is cached.
+ bytes[1] = 0x00;
+ expect(accessor.getSint64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setSint64(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setInt64(-1, Int64.fromInt(1));
+ expect(accessor.getSint64WithDefault(-1)).toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setSint64(
+ 1, /** @type {!Int64} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setSint64(1, /** @type {!Int64} */ (/** @type {*} */ (null)));
+ expect(accessor.getSint64WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('String access', () => {
+ it('returns empty string for the empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getStringWithDefault(1)).toEqual('');
+ });
+
+ it('returns the default for the empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getStringWithDefault(1, 'bar')).toEqual('bar');
+ });
+
+ it('decodes value from wire', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x01, 0x61));
+ expect(accessor.getStringWithDefault(1)).toEqual('a');
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(
+ createArrayBuffer(0x0A, 0x01, 0x60, 0x0A, 0x01, 0x61));
+ expect(accessor.getStringWithDefault(1)).toEqual('a');
+ });
+
+ if (CHECK_CRITICAL_STATE) {
+ it('fails when getting string value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x02, 0x08, 0x08));
+ expect(() => {
+ accessor.getStringWithDefault(1);
+ }).toThrow();
+ });
+ }
+
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getStringWithDefault(-1, 'a'))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getStringWithDefault(-1, 'a')).toEqual('a');
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x0A, 0x01, 0x61);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setString(1, 'b');
+ expect(accessor.getStringWithDefault(1)).toEqual('b');
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x0A, 0x01, 0x61);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x0A, 0x01, 0x62);
+ accessor.setString(1, 'b');
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns string value from cache', () => {
+ const bytes = createArrayBuffer(0x0A, 0x01, 0x61);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getStringWithDefault(1)).toBe('a');
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getStringWithDefault(1)).toBe('a');
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_TYPE) {
+ expect(() => Kernel.createEmpty().setString(-1, 'a'))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setString(-1, 'a');
+ expect(accessor.getStringWithDefault(-1)).toEqual('a');
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setString(
+ 1, /** @type {string} */ (/** @type {*} */ (null))))
+ .toThrowError('Must be string, but got: null');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setString(1, /** @type {string} */ (/** @type {*} */ (null)));
+ expect(accessor.getStringWithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Uint32 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getUint32WithDefault(1)).toEqual(0);
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getUint32WithDefault(1, 2)).toEqual(2);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ expect(accessor.getUint32WithDefault(1)).toEqual(1);
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01, 0x08, 0x02));
+ expect(accessor.getUint32WithDefault(1)).toEqual(2);
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getUint32WithDefault(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getUint32WithDefault(1)).toEqual(0);
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getUint32WithDefault(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getUint32WithDefault(-1, 1)).toEqual(1);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setUint32(1, 2);
+ expect(accessor.getUint32WithDefault(1)).toEqual(2);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x08, 0x00);
+ accessor.setUint32(1, 0);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getUint32WithDefault(1)).toBe(1);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getUint32WithDefault(1)).toBe(1);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setInt32(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setUint32(-1, 1);
+ expect(accessor.getUint32WithDefault(-1)).toEqual(1);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setUint32(
+ 1, /** @type {number} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setUint32(1, /** @type {number} */ (/** @type {*} */ (null)));
+ expect(accessor.getUint32WithDefault(1)).toEqual(null);
+ }
+ });
+
+ it('throws in setter for negative value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => Kernel.createEmpty().setUint32(1, -1)).toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setUint32(1, -1);
+ expect(accessor.getUint32WithDefault(1)).toEqual(-1);
+ }
+ });
+});
+
+describe('Uint64 access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getUint64WithDefault(1)).toEqual(Int64.fromInt(0));
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getUint64WithDefault(1, Int64.fromInt(2)))
+ .toEqual(Int64.fromInt(2));
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ expect(accessor.getUint64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01, 0x08, 0x02));
+ expect(accessor.getUint64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ it('fails when getting value with other wire types', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0D, 0x00, 0x00, 0x00, 0x00));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => {
+ accessor.getUint64WithDefault(1);
+ }).toThrowError('Expected wire type: 0 but found: 5');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ expect(accessor.getUint64WithDefault(1)).toEqual(Int64.fromInt(0));
+ }
+ });
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(
+ () => Kernel.createEmpty().getUint64WithDefault(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getUint64WithDefault(-1, Int64.fromInt(1)))
+ .toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setUint64(1, Int64.fromInt(2));
+ expect(accessor.getUint64WithDefault(1)).toEqual(Int64.fromInt(2));
+ });
+
+ it('encode the value from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes = createArrayBuffer(0x08, 0x00);
+ accessor.setUint64(1, Int64.fromInt(0));
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns value from cache', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getUint64WithDefault(1)).toEqual(Int64.fromInt(1));
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getUint64WithDefault(1)).toEqual(Int64.fromInt(1));
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setUint64(-1, Int64.fromInt(1)))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setUint64(-1, Int64.fromInt(1));
+ expect(accessor.getUint64WithDefault(-1)).toEqual(Int64.fromInt(1));
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setUint64(
+ 1, /** @type {!Int64} */ (/** @type {*} */ (null))))
+ .toThrow();
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setUint64(1, /** @type {!Int64} */ (/** @type {*} */ (null)));
+ expect(accessor.getUint64WithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Double access', () => {
+ it('returns default value for empty input', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getDoubleWithDefault(1)).toEqual(0);
+ });
+
+ it('returns the default from parameter', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer());
+ expect(accessor.getDoubleWithDefault(1, 2)).toEqual(2);
+ });
+
+ it('decodes value from wire', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F));
+ expect(accessor.getDoubleWithDefault(1)).toEqual(1);
+ });
+
+
+ it('decodes value from wire with multple values being present', () => {
+ const accessor = Kernel.fromArrayBuffer(createArrayBuffer(
+ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F, 0x09, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0xF0, 0xBF));
+ expect(accessor.getDoubleWithDefault(1)).toEqual(-1);
+ });
+
+ if (CHECK_CRITICAL_STATE) {
+ it('fails when getting double value with other wire types', () => {
+ const accessor = Kernel.fromArrayBuffer(
+ createArrayBuffer(0x0D, 0x00, 0x00, 0xF0, 0x3F));
+ expect(() => {
+ accessor.getDoubleWithDefault(1);
+ }).toThrow();
+ });
+ }
+
+
+ it('throws in getter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().getDoubleWithDefault(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ expect(Kernel.createEmpty().getDoubleWithDefault(-1, 1)).toEqual(1);
+ }
+ });
+
+ it('returns the value from setter', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.setDouble(1, 2);
+ expect(accessor.getDoubleWithDefault(1)).toEqual(2);
+ });
+
+ it('encode the value from setter', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const newBytes =
+ createArrayBuffer(0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
+ accessor.setDouble(1, 0);
+ expect(accessor.serialize()).toEqual(newBytes);
+ });
+
+ it('returns string value from cache', () => {
+ const bytes =
+ createArrayBuffer(0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getDoubleWithDefault(1)).toBe(1);
+ // Make sure the value is cached.
+ bytes[2] = 0x00;
+ expect(accessor.getDoubleWithDefault(1)).toBe(1);
+ });
+
+ it('throws in setter for invalid fieldNumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => Kernel.createEmpty().setDouble(-1, 1))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setDouble(-1, 1);
+ expect(accessor.getDoubleWithDefault(-1)).toEqual(1);
+ }
+ });
+
+ it('throws in setter for invalid value', () => {
+ if (CHECK_CRITICAL_TYPE) {
+ expect(
+ () => Kernel.createEmpty().setDouble(
+ 1, /** @type {number} */ (/** @type {*} */ (null))))
+ .toThrowError('Must be a number, but got: null');
+ } else {
+ const accessor = Kernel.createEmpty();
+ accessor.setDouble(1, /** @type {number} */ (/** @type {*} */ (null)));
+ expect(accessor.getDoubleWithDefault(1)).toEqual(null);
+ }
+ });
+});
+
+describe('Kernel for singular group does', () => {
+ it('return group from the input', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg = accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ expect(msg.getBoolWithDefault(1, false)).toBe(true);
+ });
+
+ it('return group from the input when pivot is set', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg = accessor.getGroupOrNull(1, TestMessage.instanceCreator, 0);
+ expect(msg.getBoolWithDefault(1, false)).toBe(true);
+ });
+
+ it('encode group from the input', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode group from the input after read', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('return last group from multiple inputs', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x00, 0x0C, 0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg = accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ expect(msg.getBoolWithDefault(1, false)).toBe(true);
+ });
+
+ it('removes duplicated group when serializing', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x00, 0x0C, 0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ expect(accessor.serialize())
+ .toEqual(createArrayBuffer(0x0B, 0x08, 0x01, 0x0C));
+ });
+
+ it('encode group from multiple inputs', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x00, 0x0C, 0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.serialize()).toEqual(bytes);
+ });
+
+ it('encode group after read', () => {
+ const bytes =
+ createArrayBuffer(0x0B, 0x08, 0x00, 0x0C, 0x0B, 0x08, 0x01, 0x0C);
+ const expected = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ expect(accessor.serialize()).toEqual(expected);
+ });
+
+ it('return group from setter', () => {
+ const bytes = createArrayBuffer(0x08, 0x01);
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const subaccessor = Kernel.fromArrayBuffer(bytes);
+ const submsg1 = new TestMessage(subaccessor);
+ accessor.setGroup(1, submsg1);
+ const submsg2 = accessor.getGroup(1, TestMessage.instanceCreator);
+ expect(submsg1).toBe(submsg2);
+ });
+
+ it('encode group from setter', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const subaccessor = Kernel.fromArrayBuffer(createArrayBuffer(0x08, 0x01));
+ const submsg = new TestMessage(subaccessor);
+ accessor.setGroup(1, submsg);
+ const expected = createArrayBuffer(0x0B, 0x08, 0x01, 0x0C);
+ expect(accessor.serialize()).toEqual(expected);
+ });
+
+ it('leave hasFieldNumber unchanged after getGroupOrNull', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ expect(accessor.getGroupOrNull(1, TestMessage.instanceCreator)).toBe(null);
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ });
+
+ it('serialize changes to subgroups made with getGroupsOrNull', () => {
+ const intTwoBytes = createArrayBuffer(0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+ const mutableSubMessage =
+ accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ mutableSubMessage.setInt32(1, 10);
+ const intTenBytes = createArrayBuffer(0x0B, 0x08, 0x0A, 0x0C);
+ expect(accessor.serialize()).toEqual(intTenBytes);
+ });
+
+ it('serialize additions to subgroups made with getGroupOrNull', () => {
+ const intTwoBytes = createArrayBuffer(0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+ const mutableSubMessage =
+ accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ mutableSubMessage.setInt32(2, 3);
+ // Sub group contains the original field, plus the new one.
+ expect(accessor.serialize())
+ .toEqual(createArrayBuffer(0x0B, 0x08, 0x02, 0x10, 0x03, 0x0C));
+ });
+
+ it('fail with getGroupOrNull if immutable group exist in cache', () => {
+ const intTwoBytes = createArrayBuffer(0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+
+ const readOnly = accessor.getGroup(1, TestMessage.instanceCreator);
+ if (CHECK_TYPE) {
+ expect(() => accessor.getGroupOrNull(1, TestMessage.instanceCreator))
+ .toThrow();
+ } else {
+ const mutableSubGropu =
+ accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ // The instance returned by getGroupOrNull is the exact same instance.
+ expect(mutableSubGropu).toBe(readOnly);
+
+ // Serializing the subgroup does not write the changes
+ mutableSubGropu.setInt32(1, 0);
+ expect(accessor.serialize()).toEqual(intTwoBytes);
+ }
+ });
+
+ it('change hasFieldNumber after getGroupAttach', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ expect(accessor.getGroupAttach(1, TestMessage.instanceCreator))
+ .not.toBe(null);
+ expect(accessor.hasFieldNumber(1)).toBe(true);
+ });
+
+ it('change hasFieldNumber after getGroupAttach when pivot is set', () => {
+ const accessor = Kernel.createEmpty();
+ expect(accessor.hasFieldNumber(1)).toBe(false);
+ expect(
+ accessor.getGroupAttach(1, TestMessage.instanceCreator, /* pivot= */ 1))
+ .not.toBe(null);
+ expect(accessor.hasFieldNumber(1)).toBe(true);
+ });
+
+ it('serialize subgroups made with getGroupAttach', () => {
+ const accessor = Kernel.createEmpty();
+ const mutableSubGroup =
+ accessor.getGroupAttach(1, TestMessage.instanceCreator);
+ mutableSubGroup.setInt32(1, 10);
+ const intTenBytes = createArrayBuffer(0x0B, 0x08, 0x0A, 0x0C);
+ expect(accessor.serialize()).toEqual(intTenBytes);
+ });
+
+ it('serialize additions to subgroups using getMessageAttach', () => {
+ const intTwoBytes = createArrayBuffer(0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+ const mutableSubGroup =
+ accessor.getGroupAttach(1, TestMessage.instanceCreator);
+ mutableSubGroup.setInt32(2, 3);
+ // Sub message contains the original field, plus the new one.
+ expect(accessor.serialize())
+ .toEqual(createArrayBuffer(0x0B, 0x08, 0x02, 0x10, 0x03, 0x0C));
+ });
+
+ it('fail with getGroupAttach if immutable message exist in cache', () => {
+ const intTwoBytes = createArrayBuffer(0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(intTwoBytes);
+
+ const readOnly = accessor.getGroup(1, TestMessage.instanceCreator);
+ if (CHECK_TYPE) {
+ expect(() => accessor.getGroupAttach(1, TestMessage.instanceCreator))
+ .toThrow();
+ } else {
+ const mutableSubGroup =
+ accessor.getGroupAttach(1, TestMessage.instanceCreator);
+ // The instance returned by getMessageOrNull is the exact same instance.
+ expect(mutableSubGroup).toBe(readOnly);
+
+ // Serializing the submessage does not write the changes
+ mutableSubGroup.setInt32(1, 0);
+ expect(accessor.serialize()).toEqual(intTwoBytes);
+ }
+ });
+
+ it('read default group return empty group with getGroup', () => {
+ const bytes = new ArrayBuffer(0);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getGroup(1, TestMessage.instanceCreator)).toBeTruthy();
+ expect(accessor.getGroup(1, TestMessage.instanceCreator).serialize())
+ .toEqual(bytes);
+ });
+
+ it('read default group return null with getGroupOrNull', () => {
+ const bytes = new ArrayBuffer(0);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ expect(accessor.getGroupOrNull(1, TestMessage.instanceCreator)).toBe(null);
+ });
+
+ it('read group preserve reference equality', () => {
+ const bytes = createArrayBuffer(0x0B, 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg1 = accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ const msg2 = accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ const msg3 = accessor.getGroupAttach(1, TestMessage.instanceCreator);
+ expect(msg1).toBe(msg2);
+ expect(msg1).toBe(msg3);
+ });
+
+ it('fail when getting group with null instance constructor', () => {
+ const accessor =
+ Kernel.fromArrayBuffer(createArrayBuffer(0x0A, 0x02, 0x08, 0x01));
+ const nullMessage = /** @type {function(!Kernel):!TestMessage} */
+ (/** @type {*} */ (null));
+ expect(() => accessor.getGroupOrNull(1, nullMessage)).toThrow();
+ });
+
+ it('fail when setting group value with null value', () => {
+ const accessor = Kernel.fromArrayBuffer(new ArrayBuffer(0));
+ const fakeMessage = /** @type {!TestMessage} */ (/** @type {*} */ (null));
+ if (CHECK_CRITICAL_TYPE) {
+ expect(() => accessor.setGroup(1, fakeMessage))
+ .toThrowError('Given value is not a message instance: null');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ accessor.setMessage(1, fakeMessage);
+ expect(accessor.getGroupOrNull(
+ /* fieldNumber= */ 1, TestMessage.instanceCreator))
+ .toBeNull();
+ }
+ });
+
+ it('reads group in a longer buffer', () => {
+ const bytes = createArrayBuffer(
+ 0x12, 0x20, // 32 length delimited
+ 0x00, // random values for padding start
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, // random values for padding end
+ 0x0B, // Group tag
+ 0x08, 0x02, 0x0C);
+ const accessor = Kernel.fromArrayBuffer(bytes);
+ const msg1 = accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ const msg2 = accessor.getGroupOrNull(1, TestMessage.instanceCreator);
+ expect(msg1).toBe(msg2);
+ });
+});
diff --git a/js/experimental/runtime/kernel/message_set.js b/js/experimental/runtime/kernel/message_set.js
new file mode 100644
index 0000000..d66bace
--- /dev/null
+++ b/js/experimental/runtime/kernel/message_set.js
@@ -0,0 +1,285 @@
+/*
+##########################################################
+# #
+# __ __ _____ _ _ _____ _ _ _____ #
+# \ \ / /\ | __ \| \ | |_ _| \ | |/ ____| #
+# \ \ /\ / / \ | |__) | \| | | | | \| | | __ #
+# \ \/ \/ / /\ \ | _ /| . ` | | | | . ` | | |_ | #
+# \ /\ / ____ \| | \ \| |\ |_| |_| |\ | |__| | #
+# \/ \/_/ \_\_| \_\_| \_|_____|_| \_|\_____| #
+# #
+# #
+##########################################################
+# Do not use this class in your code. This class purely #
+# exists to make proto code generation easier. #
+##########################################################
+*/
+goog.module('protobuf.runtime.MessageSet');
+
+const InternalMessage = goog.require('protobuf.binary.InternalMessage');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+
+// These are the tags for the old MessageSet format, which was defined as:
+// message MessageSet {
+// repeated group Item = 1 {
+// required uint32 type_id = 2;
+// optional bytes message = 3;
+// }
+// }
+/** @const {number} */
+const MSET_GROUP_FIELD_NUMBER = 1;
+/** @const {number} */
+const MSET_TYPE_ID_FIELD_NUMBER = 2;
+/** @const {number} */
+const MSET_MESSAGE_FIELD_NUMBER = 3;
+
+/**
+ * @param {!Kernel} kernel
+ * @return {!Map<number, !Item>}
+ */
+function createItemMap(kernel) {
+ const itemMap = new Map();
+ let totalCount = 0;
+ for (const item of kernel.getRepeatedGroupIterable(
+ MSET_GROUP_FIELD_NUMBER, Item.fromKernel)) {
+ itemMap.set(item.getTypeId(), item);
+ totalCount++;
+ }
+
+ // Normalize the entries.
+ if (totalCount > itemMap.size) {
+ writeItemMap(kernel, itemMap);
+ }
+ return itemMap;
+}
+
+/**
+ * @param {!Kernel} kernel
+ * @param {!Map<number, !Item>} itemMap
+ */
+function writeItemMap(kernel, itemMap) {
+ kernel.setRepeatedGroupIterable(MSET_GROUP_FIELD_NUMBER, itemMap.values());
+}
+
+/**
+ * @implements {InternalMessage}
+ * @final
+ */
+class MessageSet {
+ /**
+ * @param {!Kernel} kernel
+ * @return {!MessageSet}
+ */
+ static fromKernel(kernel) {
+ const itemMap = createItemMap(kernel);
+ return new MessageSet(kernel, itemMap);
+ }
+
+ /**
+ * @return {!MessageSet}
+ */
+ static createEmpty() {
+ return MessageSet.fromKernel(Kernel.createEmpty());
+ }
+
+ /**
+ * @param {!Kernel} kernel
+ * @param {!Map<number, !Item>} itemMap
+ * @private
+ */
+ constructor(kernel, itemMap) {
+ /** @const {!Kernel} @private */
+ this.kernel_ = kernel;
+ /** @const {!Map<number, !Item>} @private */
+ this.itemMap_ = itemMap;
+ }
+
+
+
+ // code helpers for code gen
+
+ /**
+ * @param {number} typeId
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {?T}
+ * @template T
+ */
+ getMessageOrNull(typeId, instanceCreator, pivot) {
+ const item = this.itemMap_.get(typeId);
+ return item ? item.getMessageOrNull(instanceCreator, pivot) : null;
+ }
+
+ /**
+ * @param {number} typeId
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getMessageAttach(typeId, instanceCreator, pivot) {
+ let item = this.itemMap_.get(typeId);
+ if (item) {
+ return item.getMessageAttach(instanceCreator, pivot);
+ }
+ const message = instanceCreator(Kernel.createEmpty());
+ this.setMessage(typeId, message);
+ return message;
+ }
+
+ /**
+ * @param {number} typeId
+ * @param {number=} pivot
+ * @return {?Kernel}
+ */
+ getMessageAccessorOrNull(typeId, pivot) {
+ const item = this.itemMap_.get(typeId);
+ return item ? item.getMessageAccessorOrNull(pivot) : null;
+ }
+
+
+ /**
+ * @param {number} typeId
+ */
+ clearMessage(typeId) {
+ if (this.itemMap_.delete(typeId)) {
+ writeItemMap(this.kernel_, this.itemMap_);
+ }
+ }
+
+ /**
+ * @param {number} typeId
+ * @return {boolean}
+ */
+ hasMessage(typeId) {
+ return this.itemMap_.has(typeId);
+ }
+
+ /**
+ * @param {number} typeId
+ * @param {!InternalMessage} value
+ */
+ setMessage(typeId, value) {
+ const item = this.itemMap_.get(typeId);
+ if (item) {
+ item.setMessage(value);
+ } else {
+ this.itemMap_.set(typeId, Item.create(typeId, value));
+ writeItemMap(this.kernel_, this.itemMap_);
+ }
+ }
+
+ /**
+ * @return {!Kernel}
+ * @override
+ */
+ internalGetKernel() {
+ return this.kernel_;
+ }
+}
+
+/**
+ * @implements {InternalMessage}
+ * @final
+ */
+class Item {
+ /**
+ * @param {number} typeId
+ * @param {!InternalMessage} message
+ * @return {!Item}
+ */
+ static create(typeId, message) {
+ const messageSet = Item.fromKernel(Kernel.createEmpty());
+ messageSet.setTypeId_(typeId);
+ messageSet.setMessage(message);
+ return messageSet;
+ }
+
+
+ /**
+ * @param {!Kernel} kernel
+ * @return {!Item}
+ */
+ static fromKernel(kernel) {
+ return new Item(kernel);
+ }
+
+ /**
+ * @param {!Kernel} kernel
+ * @private
+ */
+ constructor(kernel) {
+ /** @const {!Kernel} @private */
+ this.kernel_ = kernel;
+ }
+
+ /**
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getMessage(instanceCreator, pivot) {
+ return this.kernel_.getMessage(
+ MSET_MESSAGE_FIELD_NUMBER, instanceCreator, pivot);
+ }
+
+ /**
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {?T}
+ * @template T
+ */
+ getMessageOrNull(instanceCreator, pivot) {
+ return this.kernel_.getMessageOrNull(
+ MSET_MESSAGE_FIELD_NUMBER, instanceCreator, pivot);
+ }
+
+ /**
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number=} pivot
+ * @return {T}
+ * @template T
+ */
+ getMessageAttach(instanceCreator, pivot) {
+ return this.kernel_.getMessageAttach(
+ MSET_MESSAGE_FIELD_NUMBER, instanceCreator, pivot);
+ }
+
+ /**
+ * @param {number=} pivot
+ * @return {?Kernel}
+ */
+ getMessageAccessorOrNull(pivot) {
+ return this.kernel_.getMessageAccessorOrNull(
+ MSET_MESSAGE_FIELD_NUMBER, pivot);
+ }
+
+ /** @param {!InternalMessage} value */
+ setMessage(value) {
+ this.kernel_.setMessage(MSET_MESSAGE_FIELD_NUMBER, value);
+ }
+
+ /** @return {number} */
+ getTypeId() {
+ return this.kernel_.getUint32WithDefault(MSET_TYPE_ID_FIELD_NUMBER);
+ }
+
+ /**
+ * @param {number} value
+ * @private
+ */
+ setTypeId_(value) {
+ this.kernel_.setUint32(MSET_TYPE_ID_FIELD_NUMBER, value);
+ }
+
+ /**
+ * @return {!Kernel}
+ * @override
+ */
+ internalGetKernel() {
+ return this.kernel_;
+ }
+}
+
+exports = MessageSet;
diff --git a/js/experimental/runtime/kernel/message_set_test.js b/js/experimental/runtime/kernel/message_set_test.js
new file mode 100644
index 0000000..35e5935
--- /dev/null
+++ b/js/experimental/runtime/kernel/message_set_test.js
@@ -0,0 +1,262 @@
+/**
+ * @fileoverview Tests for message_set.js.
+ */
+goog.module('protobuf.runtime.MessageSetTest');
+
+goog.setTestOnly();
+
+const Kernel = goog.require('protobuf.runtime.Kernel');
+const MessageSet = goog.require('protobuf.runtime.MessageSet');
+const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
+
+/**
+ * @param {...number} bytes
+ * @return {!ArrayBuffer}
+ */
+function createArrayBuffer(...bytes) {
+ return new Uint8Array(bytes).buffer;
+}
+
+describe('MessageSet does', () => {
+ it('returns no messages for empty set', () => {
+ const messageSet = MessageSet.createEmpty();
+ expect(messageSet.getMessageOrNull(12345, TestMessage.instanceCreator))
+ .toBeNull();
+ });
+
+ it('returns no kernel for empty set', () => {
+ const messageSet = MessageSet.createEmpty();
+ expect(messageSet.getMessageAccessorOrNull(12345)).toBeNull();
+ });
+
+ it('returns message that has been set', () => {
+ const messageSet = MessageSet.createEmpty();
+ const message = TestMessage.createEmpty();
+ messageSet.setMessage(12345, message);
+ expect(messageSet.getMessageOrNull(12345, TestMessage.instanceCreator))
+ .toBe(message);
+ });
+
+ it('returns null for cleared message', () => {
+ const messageSet = MessageSet.createEmpty();
+ const message = TestMessage.createEmpty();
+ messageSet.setMessage(12345, message);
+ messageSet.clearMessage(12345);
+ expect(messageSet.getMessageAccessorOrNull(12345)).toBeNull();
+ });
+
+ it('returns false for not present message', () => {
+ const messageSet = MessageSet.createEmpty();
+ expect(messageSet.hasMessage(12345)).toBe(false);
+ });
+
+ it('returns true for present message', () => {
+ const messageSet = MessageSet.createEmpty();
+ const message = TestMessage.createEmpty();
+ messageSet.setMessage(12345, message);
+ expect(messageSet.hasMessage(12345)).toBe(true);
+ });
+
+ it('returns false for cleared message', () => {
+ const messageSet = MessageSet.createEmpty();
+ const message = TestMessage.createEmpty();
+ messageSet.setMessage(12345, message);
+ messageSet.clearMessage(12345);
+ expect(messageSet.hasMessage(12345)).toBe(false);
+ });
+
+ it('returns false for cleared message without it being present', () => {
+ const messageSet = MessageSet.createEmpty();
+ messageSet.clearMessage(12345);
+ expect(messageSet.hasMessage(12345)).toBe(false);
+ });
+
+ const createMessageSet = () => {
+ const messageSet = MessageSet.createEmpty();
+ const message = TestMessage.createEmpty();
+ message.setInt32(1, 2);
+ messageSet.setMessage(12345, message);
+
+
+ const parsedKernel =
+ Kernel.fromArrayBuffer(messageSet.internalGetKernel().serialize());
+ return MessageSet.fromKernel(parsedKernel);
+ };
+
+ it('pass through pivot for getMessageOrNull', () => {
+ const messageSet = createMessageSet();
+ const message =
+ messageSet.getMessageOrNull(12345, TestMessage.instanceCreator, 2);
+ expect(message.internalGetKernel().getPivot()).toBe(2);
+ });
+
+ it('pass through pivot for getMessageAttach', () => {
+ const messageSet = createMessageSet();
+ const message =
+ messageSet.getMessageAttach(12345, TestMessage.instanceCreator, 2);
+ expect(message.internalGetKernel().getPivot()).toBe(2);
+ });
+
+ it('pass through pivot for getMessageAccessorOrNull', () => {
+ const messageSet = createMessageSet();
+ const kernel = messageSet.getMessageAccessorOrNull(12345, 2);
+ expect(kernel.getPivot()).toBe(2);
+ });
+
+ it('pick the last value in the stream', () => {
+ const arrayBuffer = createArrayBuffer(
+ 0x52, // Tag (field:10, length delimited)
+ 0x14, // Length of 20 bytes
+ 0x0B, // Start group fieldnumber 1
+ 0x10, // Tag (field 2, varint)
+ 0xB9, // 12345
+ 0x60, // 12345
+ 0x1A, // Tag (field 3, length delimited)
+ 0x03, // length 3
+ 0xA0, // Tag (fieldnumber 20, varint)
+ 0x01, // Tag (fieldnumber 20, varint)
+ 0x1E, // 30
+ 0x0C, // Stop Group field number 1
+ // second group
+ 0x0B, // Start group fieldnumber 1
+ 0x10, // Tag (field 2, varint)
+ 0xB9, // 12345
+ 0x60, // 12345
+ 0x1A, // Tag (field 3, length delimited)
+ 0x03, // length 3
+ 0xA0, // Tag (fieldnumber 20, varint)
+ 0x01, // Tag (fieldnumber 20, varint)
+ 0x01, // 1
+ 0x0C // Stop Group field number 1
+ );
+
+ const outerMessage = Kernel.fromArrayBuffer(arrayBuffer);
+
+ const messageSet = outerMessage.getMessage(10, MessageSet.fromKernel);
+
+ const message =
+ messageSet.getMessageOrNull(12345, TestMessage.instanceCreator);
+ expect(message.getInt32WithDefault(20)).toBe(1);
+ });
+
+ it('removes duplicates when read', () => {
+ const arrayBuffer = createArrayBuffer(
+ 0x52, // Tag (field:10, length delimited)
+ 0x14, // Length of 20 bytes
+ 0x0B, // Start group fieldnumber 1
+ 0x10, // Tag (field 2, varint)
+ 0xB9, // 12345
+ 0x60, // 12345
+ 0x1A, // Tag (field 3, length delimited)
+ 0x03, // length 3
+ 0xA0, // Tag (fieldnumber 20, varint)
+ 0x01, // Tag (fieldnumber 20, varint)
+ 0x1E, // 30
+ 0x0C, // Stop Group field number 1
+ // second group
+ 0x0B, // Start group fieldnumber 1
+ 0x10, // Tag (field 2, varint)
+ 0xB9, // 12345
+ 0x60, // 12345
+ 0x1A, // Tag (field 3, length delimited)
+ 0x03, // length 3
+ 0xA0, // Tag (fieldnumber 20, varint)
+ 0x01, // Tag (fieldnumber 20, varint)
+ 0x01, // 1
+ 0x0C // Stop Group field number 1
+ );
+
+
+ const outerMessage = Kernel.fromArrayBuffer(arrayBuffer);
+ outerMessage.getMessageAttach(10, MessageSet.fromKernel);
+
+ expect(outerMessage.serialize())
+ .toEqual(createArrayBuffer(
+ 0x52, // Tag (field:10, length delimited)
+ 0x0A, // Length of 10 bytes
+ 0x0B, // Start group fieldnumber 1
+ 0x10, // Tag (field 2, varint)
+ 0xB9, // 12345
+ 0x60, // 12345
+ 0x1A, // Tag (field 3, length delimited)
+ 0x03, // length 3
+ 0xA0, // Tag (fieldnumber 20, varint)
+ 0x01, // Tag (fieldnumber 20, varint)
+ 0x01, // 1
+ 0x0C // Stop Group field number 1
+ ));
+ });
+
+ it('allow for large typeIds', () => {
+ const messageSet = MessageSet.createEmpty();
+ const message = TestMessage.createEmpty();
+ messageSet.setMessage(0xFFFFFFFE >>> 0, message);
+ expect(messageSet.hasMessage(0xFFFFFFFE >>> 0)).toBe(true);
+ });
+});
+
+describe('Optional MessageSet does', () => {
+ // message Bar {
+ // optional MessageSet mset = 10;
+ //}
+ //
+ // message Foo {
+ // extend proto2.bridge.MessageSet {
+ // optional Foo message_set_extension = 12345;
+ // }
+ // optional int32 f20 = 20;
+ //}
+
+ it('encode as a field', () => {
+ const fooMessage = Kernel.createEmpty();
+ fooMessage.setInt32(20, 30);
+
+ const messageSet = MessageSet.createEmpty();
+ messageSet.setMessage(12345, TestMessage.instanceCreator(fooMessage));
+
+ const barMessage = Kernel.createEmpty();
+ barMessage.setMessage(10, messageSet);
+
+ expect(barMessage.serialize())
+ .toEqual(createArrayBuffer(
+ 0x52, // Tag (field:10, length delimited)
+ 0x0A, // Length of 10 bytes
+ 0x0B, // Start group fieldnumber 1
+ 0x10, // Tag (field 2, varint)
+ 0xB9, // 12345
+ 0x60, // 12345
+ 0x1A, // Tag (field 3, length delimited)
+ 0x03, // length 3
+ 0xA0, // Tag (fieldnumber 20, varint)
+ 0x01, // Tag (fieldnumber 20, varint)
+ 0x1E, // 30
+ 0x0C // Stop Group field number 1
+ ));
+ });
+
+ it('deserializes', () => {
+ const fooMessage = Kernel.createEmpty();
+ fooMessage.setInt32(20, 30);
+
+ const messageSet = MessageSet.createEmpty();
+ messageSet.setMessage(12345, TestMessage.instanceCreator(fooMessage));
+
+
+ const barMessage = Kernel.createEmpty();
+ barMessage.setMessage(10, messageSet);
+
+ const arrayBuffer = barMessage.serialize();
+
+ const barMessageParsed = Kernel.fromArrayBuffer(arrayBuffer);
+ expect(barMessageParsed.hasFieldNumber(10)).toBe(true);
+
+ const messageSetParsed =
+ barMessageParsed.getMessage(10, MessageSet.fromKernel);
+
+ const fooMessageParsed =
+ messageSetParsed.getMessageOrNull(12345, TestMessage.instanceCreator)
+ .internalGetKernel();
+
+ expect(fooMessageParsed.getInt32WithDefault(20)).toBe(30);
+ });
+});
diff --git a/js/experimental/runtime/kernel/packed_bool_test_pairs.js b/js/experimental/runtime/kernel/packed_bool_test_pairs.js
new file mode 100644
index 0000000..e8dd2f4
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_bool_test_pairs.js
@@ -0,0 +1,59 @@
+goog.module('protobuf.binary.packedBoolTestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed bool values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, boolValues: !Array<boolean>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedBoolPairs() {
+ return [
+ {
+ name: 'empty value',
+ boolValues: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ boolValues: [true],
+ bufferDecoder: createBufferDecoder(0x01, 0x01),
+ },
+ {
+ name: 'single multi-bytes value',
+ boolValues: [true],
+ bufferDecoder: createBufferDecoder(0x02, 0x80, 0x01),
+ skip_writer: true,
+ },
+ {
+ name: 'multiple values',
+ boolValues: [true, false],
+ bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00),
+ },
+ {
+ name: 'multiple multi-bytes values',
+ boolValues: [true, false],
+ bufferDecoder: createBufferDecoder(
+ 0x0C, // length
+ 0x80,
+ 0x80,
+ 0x80,
+ 0x80,
+ 0x80,
+ 0x01, // true
+ 0x80,
+ 0x80,
+ 0x80,
+ 0x80,
+ 0x80,
+ 0x00, // false
+ ),
+ skip_writer: true,
+ },
+ ];
+}
+
+exports = {getPackedBoolPairs};
diff --git a/js/experimental/runtime/kernel/packed_double_test_pairs.js b/js/experimental/runtime/kernel/packed_double_test_pairs.js
new file mode 100644
index 0000000..de2cb55
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_double_test_pairs.js
@@ -0,0 +1,52 @@
+goog.module('protobuf.binary.packedDoubleTestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed double values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, doubleValues: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedDoublePairs() {
+ return [
+ {
+ name: 'empty value',
+ doubleValues: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ doubleValues: [1],
+ bufferDecoder: createBufferDecoder(
+ 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F),
+ },
+ {
+ name: 'multiple values',
+ doubleValues: [1, 0],
+ bufferDecoder: createBufferDecoder(
+ 0x10, // length
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xF0,
+ 0x3F, // 1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // 0
+ ),
+ },
+ ];
+}
+
+exports = {getPackedDoublePairs};
diff --git a/js/experimental/runtime/kernel/packed_fixed32_test_pairs.js b/js/experimental/runtime/kernel/packed_fixed32_test_pairs.js
new file mode 100644
index 0000000..5c8a54d
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_fixed32_test_pairs.js
@@ -0,0 +1,34 @@
+goog.module('protobuf.binary.packedFixed32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed fixed32 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, fixed32Values: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedFixed32Pairs() {
+ return [
+ {
+ name: 'empty value',
+ fixed32Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ fixed32Values: [1],
+ bufferDecoder: createBufferDecoder(0x04, 0x01, 0x00, 0x00, 0x00),
+ },
+ {
+ name: 'multiple values',
+ fixed32Values: [1, 0],
+ bufferDecoder: createBufferDecoder(
+ 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedFixed32Pairs};
diff --git a/js/experimental/runtime/kernel/packed_float_test_pairs.js b/js/experimental/runtime/kernel/packed_float_test_pairs.js
new file mode 100644
index 0000000..6d12046
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_float_test_pairs.js
@@ -0,0 +1,34 @@
+goog.module('protobuf.binary.packedFloatTestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, floatValues: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedFloatPairs() {
+ return [
+ {
+ name: 'empty value',
+ floatValues: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ floatValues: [1],
+ bufferDecoder: createBufferDecoder(0x04, 0x00, 0x00, 0x80, 0x3F),
+ },
+ {
+ name: 'multiple values',
+ floatValues: [1, 0],
+ bufferDecoder: createBufferDecoder(
+ 0x08, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedFloatPairs};
diff --git a/js/experimental/runtime/kernel/packed_int32_test_pairs.js b/js/experimental/runtime/kernel/packed_int32_test_pairs.js
new file mode 100644
index 0000000..fbe5f40
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_int32_test_pairs.js
@@ -0,0 +1,33 @@
+goog.module('protobuf.binary.packedInt32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed int32 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, int32Values: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedInt32Pairs() {
+ return [
+ {
+ name: 'empty value',
+ int32Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ int32Values: [1],
+ bufferDecoder: createBufferDecoder(0x01, 0x01),
+ },
+ {
+ name: 'multiple values',
+ int32Values: [1, 0],
+ bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedInt32Pairs};
diff --git a/js/experimental/runtime/kernel/packed_int64_test_pairs.js b/js/experimental/runtime/kernel/packed_int64_test_pairs.js
new file mode 100644
index 0000000..a6cf54e
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_int64_test_pairs.js
@@ -0,0 +1,34 @@
+goog.module('protobuf.binary.packedInt64TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const Int64 = goog.require('protobuf.Int64');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed int64 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, int64Values: !Array<!Int64>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedInt64Pairs() {
+ return [
+ {
+ name: 'empty value',
+ int64Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ int64Values: [Int64.fromInt(1)],
+ bufferDecoder: createBufferDecoder(0x01, 0x01),
+ },
+ {
+ name: 'multiple values',
+ int64Values: [Int64.fromInt(1), Int64.fromInt(0)],
+ bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedInt64Pairs};
diff --git a/js/experimental/runtime/kernel/packed_sfixed32_test_pairs.js b/js/experimental/runtime/kernel/packed_sfixed32_test_pairs.js
new file mode 100644
index 0000000..d6daa79
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_sfixed32_test_pairs.js
@@ -0,0 +1,34 @@
+goog.module('protobuf.binary.packedSfixed32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed sfixed32 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, sfixed32Values: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedSfixed32Pairs() {
+ return [
+ {
+ name: 'empty value',
+ sfixed32Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ sfixed32Values: [1],
+ bufferDecoder: createBufferDecoder(0x04, 0x01, 0x00, 0x00, 0x00),
+ },
+ {
+ name: 'multiple values',
+ sfixed32Values: [1, 0],
+ bufferDecoder: createBufferDecoder(
+ 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedSfixed32Pairs};
diff --git a/js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js b/js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js
new file mode 100644
index 0000000..5b86703
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js
@@ -0,0 +1,53 @@
+goog.module('protobuf.binary.packedSfixed64TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const Int64 = goog.require('protobuf.Int64');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed sfixed64 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, sfixed64Values: !Array<!Int64>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedSfixed64Pairs() {
+ return [
+ {
+ name: 'empty value',
+ sfixed64Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ sfixed64Values: [Int64.fromInt(1)],
+ bufferDecoder: createBufferDecoder(
+ 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
+ },
+ {
+ name: 'multiple values',
+ sfixed64Values: [Int64.fromInt(1), Int64.fromInt(0)],
+ bufferDecoder: createBufferDecoder(
+ 0x10, // length
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // 1
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00, // 2
+ ),
+ },
+ ];
+}
+
+exports = {getPackedSfixed64Pairs};
diff --git a/js/experimental/runtime/kernel/packed_sint32_test_pairs.js b/js/experimental/runtime/kernel/packed_sint32_test_pairs.js
new file mode 100644
index 0000000..314ac11
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_sint32_test_pairs.js
@@ -0,0 +1,33 @@
+goog.module('protobuf.binary.packedSint32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed sint32 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, sint32Values: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedSint32Pairs() {
+ return [
+ {
+ name: 'empty value',
+ sint32Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ sint32Values: [-1],
+ bufferDecoder: createBufferDecoder(0x01, 0x01),
+ },
+ {
+ name: 'multiple values',
+ sint32Values: [-1, 0],
+ bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedSint32Pairs};
diff --git a/js/experimental/runtime/kernel/packed_sint64_test_pairs.js b/js/experimental/runtime/kernel/packed_sint64_test_pairs.js
new file mode 100644
index 0000000..c873022
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_sint64_test_pairs.js
@@ -0,0 +1,34 @@
+goog.module('protobuf.binary.packedSint64TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const Int64 = goog.require('protobuf.Int64');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed sint64 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, sint64Values: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedSint64Pairs() {
+ return [
+ {
+ name: 'empty value',
+ sint64Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ sint64Values: [Int64.fromInt(-1)],
+ bufferDecoder: createBufferDecoder(0x01, 0x01),
+ },
+ {
+ name: 'multiple values',
+ sint64Values: [Int64.fromInt(-1), Int64.fromInt(0)],
+ bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedSint64Pairs};
diff --git a/js/experimental/runtime/kernel/packed_uint32_test_pairs.js b/js/experimental/runtime/kernel/packed_uint32_test_pairs.js
new file mode 100644
index 0000000..34fbbdf
--- /dev/null
+++ b/js/experimental/runtime/kernel/packed_uint32_test_pairs.js
@@ -0,0 +1,33 @@
+goog.module('protobuf.binary.packedUint32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of packed uint32 values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, uint32Values: !Array<number>,
+ * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>}
+ */
+function getPackedUint32Pairs() {
+ return [
+ {
+ name: 'empty value',
+ uint32Values: [],
+ bufferDecoder: createBufferDecoder(0x00),
+ skip_writer: true,
+ },
+ {
+ name: 'single value',
+ uint32Values: [1],
+ bufferDecoder: createBufferDecoder(0x01, 0x01),
+ },
+ {
+ name: 'multiple values',
+ uint32Values: [1, 0],
+ bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00),
+ },
+ ];
+}
+
+exports = {getPackedUint32Pairs};
diff --git a/js/experimental/runtime/kernel/reader.js b/js/experimental/runtime/kernel/reader.js
new file mode 100644
index 0000000..2b80e15
--- /dev/null
+++ b/js/experimental/runtime/kernel/reader.js
@@ -0,0 +1,366 @@
+/**
+ * @fileoverview Helper methods for reading data from the binary wire format.
+ */
+goog.module('protobuf.binary.reader');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const {checkState} = goog.require('protobuf.internal.checks');
+
+
+/******************************************************************************
+ * OPTIONAL FUNCTIONS
+ ******************************************************************************/
+
+/**
+ * Reads a boolean value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {boolean}
+ * @package
+ */
+function readBool(bufferDecoder, start) {
+ const {lowBits, highBits} = bufferDecoder.getVarint(start);
+ return lowBits !== 0 || highBits !== 0;
+}
+
+/**
+ * Reads a ByteString value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!ByteString}
+ * @package
+ */
+function readBytes(bufferDecoder, start) {
+ return readDelimited(bufferDecoder, start).asByteString();
+}
+
+/**
+ * Reads a int32 value from the binary bytes encoded as varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {number}
+ * @package
+ */
+function readInt32(bufferDecoder, start) {
+ // Negative 32 bit integers are encoded with 64 bit values.
+ // Clients are expected to truncate back to 32 bits.
+ // This is why we are dropping the upper bytes here.
+ return bufferDecoder.getUnsignedVarint32At(start) | 0;
+}
+
+/**
+ * Reads a int32 value from the binary bytes encoded as varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Int64}
+ * @package
+ */
+function readInt64(bufferDecoder, start) {
+ const {lowBits, highBits} = bufferDecoder.getVarint(start);
+ return Int64.fromBits(lowBits, highBits);
+}
+
+/**
+ * Reads a fixed int32 value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {number}
+ * @package
+ */
+function readFixed32(bufferDecoder, start) {
+ return bufferDecoder.getUint32(start);
+}
+
+/**
+ * Reads a float value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {number}
+ * @package
+ */
+function readFloat(bufferDecoder, start) {
+ return bufferDecoder.getFloat32(start);
+}
+
+/**
+ * Reads a fixed int64 value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Int64}
+ * @package
+ */
+function readSfixed64(bufferDecoder, start) {
+ const lowBits = bufferDecoder.getInt32(start);
+ const highBits = bufferDecoder.getInt32(start + 4);
+ return Int64.fromBits(lowBits, highBits);
+}
+
+/**
+ * Reads a sint32 value from the binary bytes encoded as varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {number}
+ * @package
+ */
+function readSint32(bufferDecoder, start) {
+ const bits = bufferDecoder.getUnsignedVarint32At(start);
+ // Truncate upper bits and convert from zig zag to signd int
+ return (bits >>> 1) ^ -(bits & 0x01);
+}
+
+/**
+ * Reads a sint64 value from the binary bytes encoded as varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Int64}
+ * @package
+ */
+function readSint64(bufferDecoder, start) {
+ const {lowBits, highBits} = bufferDecoder.getVarint(start);
+ const sign = -(lowBits & 0x01);
+ const decodedLowerBits = ((lowBits >>> 1) | (highBits & 0x01) << 31) ^ sign;
+ const decodedUpperBits = (highBits >>> 1) ^ sign;
+ return Int64.fromBits(decodedLowerBits, decodedUpperBits);
+}
+
+/**
+ * Read a subarray of bytes representing a length delimited field.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!BufferDecoder}
+ * @package
+ */
+function readDelimited(bufferDecoder, start) {
+ const unsignedLength = bufferDecoder.getUnsignedVarint32At(start);
+ return bufferDecoder.subBufferDecoder(bufferDecoder.cursor(), unsignedLength);
+}
+
+/**
+ * Reads a string value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {string}
+ * @package
+ */
+function readString(bufferDecoder, start) {
+ return readDelimited(bufferDecoder, start).asString();
+}
+
+/**
+ * Reads a uint32 value from the binary bytes encoded as varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {number}
+ * @package
+ */
+function readUint32(bufferDecoder, start) {
+ return bufferDecoder.getUnsignedVarint32At(start);
+}
+
+/**
+ * Reads a double value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {number}
+ * @package
+ */
+function readDouble(bufferDecoder, start) {
+ return bufferDecoder.getFloat64(start);
+}
+
+/**
+ * Reads a fixed int32 value from the binary bytes.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {number}
+ * @package
+ */
+function readSfixed32(bufferDecoder, start) {
+ return bufferDecoder.getInt32(start);
+}
+
+/******************************************************************************
+ * REPEATED FUNCTIONS
+ ******************************************************************************/
+
+/**
+ * Reads a packed bool field, which consists of a length header and a list of
+ * unsigned varints.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<boolean>}
+ * @package
+ */
+function readPackedBool(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readBool);
+}
+
+/**
+ * Reads a packed double field, which consists of a length header and a list of
+ * fixed64.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<number>}
+ * @package
+ */
+function readPackedDouble(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readDouble);
+}
+
+/**
+ * Reads a packed fixed32 field, which consists of a length header and a list of
+ * fixed32.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<number>}
+ * @package
+ */
+function readPackedFixed32(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readFixed32);
+}
+
+/**
+ * Reads a packed float field, which consists of a length header and a list of
+ * fixed64.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<number>}
+ * @package
+ */
+function readPackedFloat(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readFloat);
+}
+
+/**
+ * Reads a packed int32 field, which consists of a length header and a list of
+ * varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<number>}
+ * @package
+ */
+function readPackedInt32(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readInt32);
+}
+
+/**
+ * Reads a packed int64 field, which consists of a length header and a list
+ * of int64.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<!Int64>}
+ * @package
+ */
+function readPackedInt64(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readInt64);
+}
+
+/**
+ * Reads a packed sfixed32 field, which consists of a length header and a list
+ * of sfixed32.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<number>}
+ * @package
+ */
+function readPackedSfixed32(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readSfixed32);
+}
+
+/**
+ * Reads a packed sfixed64 field, which consists of a length header and a list
+ * of sfixed64.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<!Int64>}
+ * @package
+ */
+function readPackedSfixed64(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readSfixed64);
+}
+
+/**
+ * Reads a packed sint32 field, which consists of a length header and a list of
+ * varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<number>}
+ * @package
+ */
+function readPackedSint32(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readSint32);
+}
+
+/**
+ * Reads a packed sint64 field, which consists of a length header and a list
+ * of sint64.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<!Int64>}
+ * @package
+ */
+function readPackedSint64(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readSint64);
+}
+
+/**
+ * Reads a packed uint32 field, which consists of a length header and a list of
+ * varint.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @return {!Array<number>}
+ * @package
+ */
+function readPackedUint32(bufferDecoder, start) {
+ return readPacked(bufferDecoder, start, readUint32);
+}
+
+/**
+ * Read packed values.
+ * @param {!BufferDecoder} bufferDecoder Binary format encoded bytes.
+ * @param {number} start Start of the data.
+ * @param {function(!BufferDecoder, number):T} valueFunction
+ * @return {!Array<T>}
+ * @package
+ * @template T
+ */
+function readPacked(bufferDecoder, start, valueFunction) {
+ const /** !Array<T> */ result = [];
+ const unsignedLength = bufferDecoder.getUnsignedVarint32At(start);
+ const dataStart = bufferDecoder.cursor();
+ while (bufferDecoder.cursor() < dataStart + unsignedLength) {
+ checkState(bufferDecoder.cursor() > 0);
+ result.push(valueFunction(bufferDecoder, bufferDecoder.cursor()));
+ }
+ return result;
+}
+
+exports = {
+ readBool,
+ readBytes,
+ readDelimited,
+ readDouble,
+ readFixed32,
+ readFloat,
+ readInt32,
+ readInt64,
+ readSint32,
+ readSint64,
+ readSfixed32,
+ readSfixed64,
+ readString,
+ readUint32,
+ readPackedBool,
+ readPackedDouble,
+ readPackedFixed32,
+ readPackedFloat,
+ readPackedInt32,
+ readPackedInt64,
+ readPackedSfixed32,
+ readPackedSfixed64,
+ readPackedSint32,
+ readPackedSint64,
+ readPackedUint32,
+};
diff --git a/js/experimental/runtime/kernel/reader_test.js b/js/experimental/runtime/kernel/reader_test.js
new file mode 100644
index 0000000..100c793
--- /dev/null
+++ b/js/experimental/runtime/kernel/reader_test.js
@@ -0,0 +1,425 @@
+/**
+ * @fileoverview Tests for reader.js.
+ */
+goog.module('protobuf.binary.ReaderTest');
+
+goog.setTestOnly();
+
+// Note to the reader:
+// Since the reader behavior changes with the checking level some of the
+// tests in this file have to know which checking level is enable to make
+// correct assertions.
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const ByteString = goog.require('protobuf.ByteString');
+const reader = goog.require('protobuf.binary.reader');
+const {CHECK_CRITICAL_STATE} = goog.require('protobuf.internal.checks');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+const {encode} = goog.require('protobuf.binary.textencoding');
+const {getBoolPairs} = goog.require('protobuf.binary.boolTestPairs');
+const {getDoublePairs} = goog.require('protobuf.binary.doubleTestPairs');
+const {getFixed32Pairs} = goog.require('protobuf.binary.fixed32TestPairs');
+const {getFloatPairs} = goog.require('protobuf.binary.floatTestPairs');
+const {getInt32Pairs} = goog.require('protobuf.binary.int32TestPairs');
+const {getInt64Pairs} = goog.require('protobuf.binary.int64TestPairs');
+const {getPackedBoolPairs} = goog.require('protobuf.binary.packedBoolTestPairs');
+const {getPackedDoublePairs} = goog.require('protobuf.binary.packedDoubleTestPairs');
+const {getPackedFixed32Pairs} = goog.require('protobuf.binary.packedFixed32TestPairs');
+const {getPackedFloatPairs} = goog.require('protobuf.binary.packedFloatTestPairs');
+const {getPackedInt32Pairs} = goog.require('protobuf.binary.packedInt32TestPairs');
+const {getPackedInt64Pairs} = goog.require('protobuf.binary.packedInt64TestPairs');
+const {getPackedSfixed32Pairs} = goog.require('protobuf.binary.packedSfixed32TestPairs');
+const {getPackedSfixed64Pairs} = goog.require('protobuf.binary.packedSfixed64TestPairs');
+const {getPackedSint32Pairs} = goog.require('protobuf.binary.packedSint32TestPairs');
+const {getPackedSint64Pairs} = goog.require('protobuf.binary.packedSint64TestPairs');
+const {getPackedUint32Pairs} = goog.require('protobuf.binary.packedUint32TestPairs');
+const {getSfixed32Pairs} = goog.require('protobuf.binary.sfixed32TestPairs');
+const {getSfixed64Pairs} = goog.require('protobuf.binary.sfixed64TestPairs');
+const {getSint32Pairs} = goog.require('protobuf.binary.sint32TestPairs');
+const {getSint64Pairs} = goog.require('protobuf.binary.sint64TestPairs');
+const {getUint32Pairs} = goog.require('protobuf.binary.uint32TestPairs');
+
+/******************************************************************************
+ * Optional FUNCTIONS
+ ******************************************************************************/
+
+describe('Read bool does', () => {
+ for (const pair of getBoolPairs()) {
+ it(`decode ${pair.name}`, () => {
+ if (pair.error && CHECK_CRITICAL_STATE) {
+ expect(() => reader.readBool(pair.bufferDecoder, 0)).toThrow();
+ } else {
+ const d = reader.readBool(
+ pair.bufferDecoder, pair.bufferDecoder.startIndex());
+ expect(d).toEqual(pair.boolValue);
+ }
+ });
+ }
+});
+
+describe('readBytes does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder();
+ expect(() => reader.readBytes(bufferDecoder, 0)).toThrow();
+ });
+
+ it('read bytes by index', () => {
+ const bufferDecoder = createBufferDecoder(3, 1, 2, 3);
+ const byteString = reader.readBytes(bufferDecoder, 0);
+ expect(ByteString.fromArrayBuffer(new Uint8Array([1, 2, 3]).buffer))
+ .toEqual(byteString);
+ });
+});
+
+describe('readDouble does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder();
+ expect(() => reader.readDouble(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getDoublePairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readDouble(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.doubleValue);
+ });
+ }
+});
+
+describe('readFixed32 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder();
+ expect(() => reader.readFixed32(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getFixed32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readFixed32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.intValue);
+ });
+ }
+});
+
+describe('readFloat does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder();
+ expect(() => reader.readFloat(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getFloatPairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readFloat(pair.bufferDecoder, 0);
+ expect(d).toEqual(Math.fround(pair.floatValue));
+ });
+ }
+});
+
+describe('readInt32 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder(0x80);
+ expect(() => reader.readInt32(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getInt32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ if (pair.error && CHECK_CRITICAL_STATE) {
+ expect(() => reader.readInt32(pair.bufferDecoder, 0)).toThrow();
+ } else {
+ const d = reader.readInt32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.intValue);
+ }
+ });
+ }
+});
+
+describe('readSfixed32 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder(0x80);
+ expect(() => reader.readSfixed32(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getSfixed32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readSfixed32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.intValue);
+ });
+ }
+});
+
+describe('readSfixed64 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder(0x80);
+ expect(() => reader.readSfixed64(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getSfixed64Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readSfixed64(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.longValue);
+ });
+ }
+});
+
+describe('readSint32 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder(0x80);
+ expect(() => reader.readSint32(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getSint32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ if (pair.error && CHECK_CRITICAL_STATE) {
+ expect(() => reader.readSint32(pair.bufferDecoder, 0)).toThrow();
+ } else {
+ const d = reader.readSint32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.intValue);
+ }
+ });
+ }
+});
+
+describe('readInt64 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder(0x80);
+ expect(() => reader.readInt64(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getInt64Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ if (pair.error && CHECK_CRITICAL_STATE) {
+ expect(() => reader.readInt64(pair.bufferDecoder, 0)).toThrow();
+ } else {
+ const d = reader.readInt64(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.longValue);
+ }
+ });
+ }
+});
+
+describe('readSint64 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder(0x80);
+ expect(() => reader.readSint64(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getSint64Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ if (pair.error && CHECK_CRITICAL_STATE) {
+ expect(() => reader.readSint64(pair.bufferDecoder, 0)).toThrow();
+ } else {
+ const d = reader.readSint64(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.longValue);
+ }
+ });
+ }
+});
+
+describe('readUint32 does', () => {
+ it('throw exception if data is too short', () => {
+ const bufferDecoder = createBufferDecoder(0x80);
+ expect(() => reader.readUint32(bufferDecoder, 0)).toThrow();
+ });
+
+ for (const pair of getUint32Pairs()) {
+ if (!pair.skip_reader) {
+ it(`decode ${pair.name}`, () => {
+ if (pair.error && CHECK_CRITICAL_STATE) {
+ expect(() => reader.readUint32(pair.bufferDecoder, 0)).toThrow();
+ } else {
+ const d = reader.readUint32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.intValue);
+ }
+ });
+ }
+ }
+});
+
+/**
+ *
+ * @param {string} s
+ * @return {!Uint8Array}
+ */
+function encodeString(s) {
+ if (typeof TextEncoder !== 'undefined') {
+ const textEncoder = new TextEncoder('utf-8');
+ return textEncoder.encode(s);
+ } else {
+ return encode(s);
+ }
+}
+
+/** @param {string} s */
+function expectEncodedStringToMatch(s) {
+ const array = encodeString(s);
+ const length = array.length;
+ if (length > 127) {
+ throw new Error('Test only works for strings shorter than 128');
+ }
+ const encodedArray = new Uint8Array(length + 1);
+ encodedArray[0] = length;
+ encodedArray.set(array, 1);
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(encodedArray.buffer);
+ expect(reader.readString(bufferDecoder, 0)).toEqual(s);
+}
+
+describe('readString does', () => {
+ it('return empty string for zero length string', () => {
+ const s = reader.readString(createBufferDecoder(0x00), 0);
+ expect(s).toEqual('');
+ });
+
+ it('decode random strings', () => {
+ // 1 byte strings
+ expectEncodedStringToMatch('hello');
+ expectEncodedStringToMatch('HELLO1!');
+
+ // 2 byte String
+ expectEncodedStringToMatch('©');
+
+ // 3 byte string
+ expectEncodedStringToMatch('❄');
+
+ // 4 byte string
+ expectEncodedStringToMatch('😁');
+ });
+
+ it('decode 1 byte strings', () => {
+ for (let i = 0; i < 0x80; i++) {
+ const s = String.fromCharCode(i);
+ expectEncodedStringToMatch(s);
+ }
+ });
+
+ it('decode 2 byte strings', () => {
+ for (let i = 0xC0; i < 0x7FF; i++) {
+ const s = String.fromCharCode(i);
+ expectEncodedStringToMatch(s);
+ }
+ });
+
+ it('decode 3 byte strings', () => {
+ for (let i = 0x7FF; i < 0x8FFF; i++) {
+ const s = String.fromCharCode(i);
+ expectEncodedStringToMatch(s);
+ }
+ });
+
+ it('throw exception on invalid bytes', () => {
+ // This test will only succeed with the native TextDecoder since
+ // our polyfill does not do any validation. IE10 and IE11 don't support
+ // TextDecoder.
+ // TODO: Remove this check once we no longer need to support IE
+ if (typeof TextDecoder !== 'undefined') {
+ expect(
+ () => reader.readString(
+ createBufferDecoder(0x01, /* invalid utf data point*/ 0xFF), 0))
+ .toThrow();
+ }
+ });
+
+ it('throw exception if data is too short', () => {
+ const array = createBufferDecoder(0x02, '?'.charCodeAt(0));
+ expect(() => reader.readString(array, 0)).toThrow();
+ });
+});
+
+/******************************************************************************
+ * REPEATED FUNCTIONS
+ ******************************************************************************/
+
+describe('readPackedBool does', () => {
+ for (const pair of getPackedBoolPairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedBool(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.boolValues);
+ });
+ }
+});
+
+describe('readPackedDouble does', () => {
+ for (const pair of getPackedDoublePairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedDouble(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.doubleValues);
+ });
+ }
+});
+
+describe('readPackedFixed32 does', () => {
+ for (const pair of getPackedFixed32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedFixed32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.fixed32Values);
+ });
+ }
+});
+
+describe('readPackedFloat does', () => {
+ for (const pair of getPackedFloatPairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedFloat(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.floatValues);
+ });
+ }
+});
+
+describe('readPackedInt32 does', () => {
+ for (const pair of getPackedInt32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedInt32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.int32Values);
+ });
+ }
+});
+
+describe('readPackedInt64 does', () => {
+ for (const pair of getPackedInt64Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedInt64(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.int64Values);
+ });
+ }
+});
+
+describe('readPackedSfixed32 does', () => {
+ for (const pair of getPackedSfixed32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedSfixed32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.sfixed32Values);
+ });
+ }
+});
+
+describe('readPackedSfixed64 does', () => {
+ for (const pair of getPackedSfixed64Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedSfixed64(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.sfixed64Values);
+ });
+ }
+});
+
+describe('readPackedSint32 does', () => {
+ for (const pair of getPackedSint32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedSint32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.sint32Values);
+ });
+ }
+});
+
+describe('readPackedSint64 does', () => {
+ for (const pair of getPackedSint64Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedSint64(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.sint64Values);
+ });
+ }
+});
+
+describe('readPackedUint32 does', () => {
+ for (const pair of getPackedUint32Pairs()) {
+ it(`decode ${pair.name}`, () => {
+ const d = reader.readPackedUint32(pair.bufferDecoder, 0);
+ expect(d).toEqual(pair.uint32Values);
+ });
+ }
+});
diff --git a/js/experimental/runtime/kernel/sfixed32_test_pairs.js b/js/experimental/runtime/kernel/sfixed32_test_pairs.js
new file mode 100644
index 0000000..5a082ce
--- /dev/null
+++ b/js/experimental/runtime/kernel/sfixed32_test_pairs.js
@@ -0,0 +1,46 @@
+/**
+ * @fileoverview Test data for sfixed32 encoding and decoding.
+ */
+goog.module('protobuf.binary.sfixed32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of int values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, intValue: number, bufferDecoder:
+ * !BufferDecoder}>}
+ */
+function getSfixed32Pairs() {
+ const sfixed32Pairs = [
+ {
+ name: 'zero',
+ intValue: 0,
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x00, 0x00),
+ },
+ {
+ name: 'one',
+ intValue: 1,
+ bufferDecoder: createBufferDecoder(0x01, 0x00, 0x00, 0x00)
+ },
+ {
+ name: 'minus one',
+ intValue: -1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF),
+ },
+ {
+ name: 'max int 2^31 -1',
+ intValue: Math.pow(2, 31) - 1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0x7F)
+ },
+ {
+ name: 'min int -2^31',
+ intValue: -Math.pow(2, 31),
+ bufferDecoder: createBufferDecoder(0x00, 0x00, 0x00, 0x80)
+ },
+ ];
+ return [...sfixed32Pairs];
+}
+
+exports = {getSfixed32Pairs};
diff --git a/js/experimental/runtime/kernel/sfixed64_test_pairs.js b/js/experimental/runtime/kernel/sfixed64_test_pairs.js
new file mode 100644
index 0000000..c7c8d00
--- /dev/null
+++ b/js/experimental/runtime/kernel/sfixed64_test_pairs.js
@@ -0,0 +1,52 @@
+/**
+ * @fileoverview Test data for sfixed32 encoding and decoding.
+ */
+goog.module('protobuf.binary.sfixed64TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const Int64 = goog.require('protobuf.Int64');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of int values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, longValue: !Int64, bufferDecoder:
+ * !BufferDecoder}>}
+ */
+function getSfixed64Pairs() {
+ const sfixed64Pairs = [
+ {
+ name: 'zero',
+ longValue: Int64.fromInt(0),
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
+ },
+ {
+ name: 'one',
+ longValue: Int64.fromInt(1),
+ bufferDecoder:
+ createBufferDecoder(0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
+ },
+ {
+ name: 'minus one',
+ longValue: Int64.fromInt(-1),
+ bufferDecoder:
+ createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF),
+ },
+ {
+ name: 'max int 2^63 -1',
+ longValue: Int64.getMaxValue(),
+ bufferDecoder:
+ createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F)
+ },
+ {
+ name: 'min int -2^63',
+ longValue: Int64.getMinValue(),
+ bufferDecoder:
+ createBufferDecoder(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80)
+ },
+ ];
+ return [...sfixed64Pairs];
+}
+
+exports = {getSfixed64Pairs};
diff --git a/js/experimental/runtime/kernel/sint32_test_pairs.js b/js/experimental/runtime/kernel/sint32_test_pairs.js
new file mode 100644
index 0000000..954df90
--- /dev/null
+++ b/js/experimental/runtime/kernel/sint32_test_pairs.js
@@ -0,0 +1,57 @@
+/**
+ * @fileoverview Test data for int32 encoding and decoding.
+ */
+goog.module('protobuf.binary.sint32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, intValue:number, bufferDecoder:
+ * !BufferDecoder, error: ?boolean, skip_writer: ?boolean}>}
+ */
+function getSint32Pairs() {
+ const sint32Pairs = [
+ {
+ name: 'zero',
+ intValue: 0,
+ bufferDecoder: createBufferDecoder(0x00),
+ },
+ {
+ name: 'one ',
+ intValue: 1,
+ bufferDecoder: createBufferDecoder(0x02),
+ },
+ {
+ name: 'minus one',
+ intValue: -1,
+ bufferDecoder: createBufferDecoder(0x01),
+ },
+ {
+ name: 'two',
+ intValue: 2,
+ bufferDecoder: createBufferDecoder(0x04),
+ },
+ {
+ name: 'minus two',
+ intValue: -2,
+ bufferDecoder: createBufferDecoder(0x03),
+ },
+ {
+ name: 'int 2^31 - 1',
+ intValue: Math.pow(2, 31) - 1,
+ bufferDecoder: createBufferDecoder(0xFE, 0xFF, 0xFF, 0xFF, 0x0F),
+
+ },
+ {
+ name: '-2^31',
+ intValue: -Math.pow(2, 31),
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0x0F),
+ },
+ ];
+ return [...sint32Pairs];
+}
+
+exports = {getSint32Pairs};
diff --git a/js/experimental/runtime/kernel/sint64_test_pairs.js b/js/experimental/runtime/kernel/sint64_test_pairs.js
new file mode 100644
index 0000000..f1b4610
--- /dev/null
+++ b/js/experimental/runtime/kernel/sint64_test_pairs.js
@@ -0,0 +1,60 @@
+/**
+ * @fileoverview Test data for sint64 encoding and decoding.
+ */
+goog.module('protobuf.binary.sint64TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const Int64 = goog.require('protobuf.Int64');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, longValue: !Int64, bufferDecoder:
+ * !BufferDecoder, error: ?boolean, skip_writer: ?boolean}>}
+ */
+function getSint64Pairs() {
+ const sint64Pairs = [
+ {
+ name: 'zero',
+ longValue: Int64.fromInt(0),
+ bufferDecoder: createBufferDecoder(0x00),
+ },
+ {
+ name: 'one ',
+ longValue: Int64.fromInt(1),
+ bufferDecoder: createBufferDecoder(0x02),
+ },
+ {
+ name: 'minus one',
+ longValue: Int64.fromInt(-1),
+ bufferDecoder: createBufferDecoder(0x01),
+ },
+ {
+ name: 'two',
+ longValue: Int64.fromInt(2),
+ bufferDecoder: createBufferDecoder(0x04),
+ },
+ {
+ name: 'minus two',
+ longValue: Int64.fromInt(-2),
+ bufferDecoder: createBufferDecoder(0x03),
+ },
+ {
+ name: 'min value',
+ longValue: Int64.getMinValue(),
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ },
+
+ {
+ name: 'max value',
+ longValue: Int64.getMaxValue(),
+ bufferDecoder: createBufferDecoder(
+ 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ },
+ ];
+ return [...sint64Pairs];
+}
+
+exports = {getSint64Pairs};
diff --git a/js/experimental/runtime/kernel/storage.js b/js/experimental/runtime/kernel/storage.js
new file mode 100644
index 0000000..a3e1e4f
--- /dev/null
+++ b/js/experimental/runtime/kernel/storage.js
@@ -0,0 +1,67 @@
+goog.module('protobuf.runtime.Storage');
+
+/**
+ * Interface for getting and storing fields of a protobuf message.
+ *
+ * @interface
+ * @package
+ * @template FieldType
+ */
+class Storage {
+ /**
+ * Returns the pivot value.
+ *
+ * @return {number}
+ */
+ getPivot() {}
+
+ /**
+ * Sets a field in the specified field number.
+ *
+ * @param {number} fieldNumber
+ * @param {!FieldType} field
+ */
+ set(fieldNumber, field) {}
+
+ /**
+ * Returns a field at the specified field number.
+ *
+ * @param {number} fieldNumber
+ * @return {!FieldType|undefined}
+ */
+ get(fieldNumber) {}
+
+ /**
+ * Deletes a field from the specified field number.
+ *
+ * @param {number} fieldNumber
+ */
+ delete(fieldNumber) {}
+
+ /**
+ * Executes the provided function once for each field.
+ *
+ * @param {function(!FieldType, number): void} callback
+ */
+ forEach(callback) {}
+
+ /**
+ * Creates a shallow copy of the storage.
+ *
+ * @return {!Storage}
+ */
+ shallowCopy() {}
+}
+
+/**
+ * 85% of the proto fields have a field number <= 24:
+ * https://plx.corp.google.com/scripts2/script_5d._f02af6_0000_23b1_a15f_001a1139dd02
+ *
+ * @type {number}
+ */
+// LINT.IfChange
+Storage.DEFAULT_PIVOT = 24;
+// LINT.ThenChange(//depot/google3/third_party/protobuf/javascript/runtime/kernel/binary_storage_test.js,
+// //depot/google3/net/proto2/contrib/js_proto/internal/kernel_message_generator.cc)
+
+exports = Storage;
diff --git a/js/experimental/runtime/kernel/tag.js b/js/experimental/runtime/kernel/tag.js
new file mode 100644
index 0000000..b288df3
--- /dev/null
+++ b/js/experimental/runtime/kernel/tag.js
@@ -0,0 +1,144 @@
+goog.module('protobuf.binary.tag');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const WireType = goog.require('protobuf.binary.WireType');
+const {checkCriticalElementIndex, checkCriticalState} = goog.require('protobuf.internal.checks');
+
+/**
+ * Returns wire type stored in a tag.
+ * Protos store the wire type as the first 3 bit of a tag.
+ * @param {number} tag
+ * @return {!WireType}
+ */
+function tagToWireType(tag) {
+ return /** @type {!WireType} */ (tag & 0x07);
+}
+
+/**
+ * Returns the field number stored in a tag.
+ * Protos store the field number in the upper 29 bits of a 32 bit number.
+ * @param {number} tag
+ * @return {number}
+ */
+function tagToFieldNumber(tag) {
+ return tag >>> 3;
+}
+
+/**
+ * Combines wireType and fieldNumber into a tag.
+ * @param {!WireType} wireType
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+function createTag(wireType, fieldNumber) {
+ return (fieldNumber << 3 | wireType) >>> 0;
+}
+
+/**
+ * Returns the length, in bytes, of the field in the tag stream, less the tag
+ * itself.
+ * Note: This moves the cursor in the bufferDecoder.
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {number} start
+ * @param {!WireType} wireType
+ * @param {number} fieldNumber
+ * @return {number}
+ * @private
+ */
+function getTagLength(bufferDecoder, start, wireType, fieldNumber) {
+ bufferDecoder.setCursor(start);
+ skipField(bufferDecoder, wireType, fieldNumber);
+ return bufferDecoder.cursor() - start;
+}
+
+/**
+ * @param {number} value
+ * @return {number}
+ */
+function get32BitVarintLength(value) {
+ if (value < 0) {
+ return 5;
+ }
+ let size = 1;
+ while (value >= 128) {
+ size++;
+ value >>>= 7;
+ }
+ return size;
+}
+
+/**
+ * Skips over a field.
+ * Note: If the field is a start group the entire group will be skipped, placing
+ * the cursor onto the next field.
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {!WireType} wireType
+ * @param {number} fieldNumber
+ */
+function skipField(bufferDecoder, wireType, fieldNumber) {
+ switch (wireType) {
+ case WireType.VARINT:
+ checkCriticalElementIndex(
+ bufferDecoder.cursor(), bufferDecoder.endIndex());
+ bufferDecoder.skipVarint();
+ return;
+ case WireType.FIXED64:
+ bufferDecoder.skip(8);
+ return;
+ case WireType.DELIMITED:
+ checkCriticalElementIndex(
+ bufferDecoder.cursor(), bufferDecoder.endIndex());
+ const length = bufferDecoder.getUnsignedVarint32();
+ bufferDecoder.skip(length);
+ return;
+ case WireType.START_GROUP:
+ const foundGroup = skipGroup_(bufferDecoder, fieldNumber);
+ checkCriticalState(foundGroup, 'No end group found.');
+ return;
+ case WireType.FIXED32:
+ bufferDecoder.skip(4);
+ return;
+ default:
+ throw new Error(`Unexpected wire type: ${wireType}`);
+ }
+}
+
+/**
+ * Skips over fields until it finds the end of a given group consuming the stop
+ * group tag.
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {number} groupFieldNumber
+ * @return {boolean} Whether the end group tag was found.
+ * @private
+ */
+function skipGroup_(bufferDecoder, groupFieldNumber) {
+ // On a start group we need to keep skipping fields until we find a
+ // corresponding stop group
+ // Note: Since we are calling skipField from here nested groups will be
+ // handled by recursion of this method and thus we will not see a nested
+ // STOP GROUP here unless there is something wrong with the input data.
+ while (bufferDecoder.hasNext()) {
+ const tag = bufferDecoder.getUnsignedVarint32();
+ const wireType = tagToWireType(tag);
+ const fieldNumber = tagToFieldNumber(tag);
+
+ if (wireType === WireType.END_GROUP) {
+ checkCriticalState(
+ groupFieldNumber === fieldNumber,
+ `Expected stop group for fieldnumber ${groupFieldNumber} not found.`);
+ return true;
+ } else {
+ skipField(bufferDecoder, wireType, fieldNumber);
+ }
+ }
+ return false;
+}
+
+exports = {
+ createTag,
+ get32BitVarintLength,
+ getTagLength,
+ skipField,
+ tagToWireType,
+ tagToFieldNumber,
+};
diff --git a/js/experimental/runtime/kernel/tag_test.js b/js/experimental/runtime/kernel/tag_test.js
new file mode 100644
index 0000000..04a6cb6
--- /dev/null
+++ b/js/experimental/runtime/kernel/tag_test.js
@@ -0,0 +1,221 @@
+/**
+ * @fileoverview Tests for tag.js.
+ */
+goog.module('protobuf.binary.TagTests');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const WireType = goog.require('protobuf.binary.WireType');
+const {CHECK_CRITICAL_STATE} = goog.require('protobuf.internal.checks');
+const {createTag, get32BitVarintLength, skipField, tagToFieldNumber, tagToWireType} = goog.require('protobuf.binary.tag');
+
+
+goog.setTestOnly();
+
+/**
+ * @param {...number} bytes
+ * @return {!ArrayBuffer}
+ */
+function createArrayBuffer(...bytes) {
+ return new Uint8Array(bytes).buffer;
+}
+
+describe('skipField', () => {
+ it('skips varints', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x80, 0x00));
+ skipField(bufferDecoder, WireType.VARINT, 1);
+ expect(bufferDecoder.cursor()).toBe(2);
+ });
+
+ it('throws for out of bounds varints', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x80, 0x00));
+ bufferDecoder.setCursor(2);
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => skipField(bufferDecoder, WireType.VARINT, 1)).toThrowError();
+ }
+ });
+
+ it('skips fixed64', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
+ skipField(bufferDecoder, WireType.FIXED64, 1);
+ expect(bufferDecoder.cursor()).toBe(8);
+ });
+
+ it('throws for fixed64 if length is too short', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => skipField(bufferDecoder, WireType.FIXED64, 1))
+ .toThrowError();
+ }
+ });
+
+ it('skips fixed32', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0x80, 0x00, 0x00, 0x00));
+ skipField(bufferDecoder, WireType.FIXED32, 1);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+
+ it('throws for fixed32 if length is too short', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x80, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => skipField(bufferDecoder, WireType.FIXED32, 1))
+ .toThrowError();
+ }
+ });
+
+
+ it('skips length delimited', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0x03, 0x00, 0x00, 0x00));
+ skipField(bufferDecoder, WireType.DELIMITED, 1);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+
+ it('throws for length delimited if length is too short', () => {
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x03, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => skipField(bufferDecoder, WireType.DELIMITED, 1))
+ .toThrowError();
+ }
+ });
+
+ it('skips groups', () => {
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(
+ createArrayBuffer(0x0B, 0x08, 0x01, 0x0C));
+ bufferDecoder.setCursor(1);
+ skipField(bufferDecoder, WireType.START_GROUP, 1);
+ expect(bufferDecoder.cursor()).toBe(4);
+ });
+
+ it('skips group in group', () => {
+ const buffer = createArrayBuffer(
+ 0x0B, // start outter
+ 0x10, 0x01, // field: 2, value: 1
+ 0x0B, // start inner group
+ 0x10, 0x01, // payload inner group
+ 0x0C, // stop inner group
+ 0x0C // end outter
+ );
+ const bufferDecoder = BufferDecoder.fromArrayBuffer(buffer);
+ bufferDecoder.setCursor(1);
+ skipField(bufferDecoder, WireType.START_GROUP, 1);
+ expect(bufferDecoder.cursor()).toBe(8);
+ });
+
+ it('throws for group if length is too short', () => {
+ // no closing group
+ const bufferDecoder =
+ BufferDecoder.fromArrayBuffer(createArrayBuffer(0x0B, 0x00, 0x00));
+ if (CHECK_CRITICAL_STATE) {
+ expect(() => skipField(bufferDecoder, WireType.START_GROUP, 1))
+ .toThrowError();
+ }
+ });
+});
+
+
+describe('tagToWireType', () => {
+ it('decodes numbers ', () => {
+ // simple numbers
+ expect(tagToWireType(0x00)).toBe(WireType.VARINT);
+ expect(tagToWireType(0x01)).toBe(WireType.FIXED64);
+ expect(tagToWireType(0x02)).toBe(WireType.DELIMITED);
+ expect(tagToWireType(0x03)).toBe(WireType.START_GROUP);
+ expect(tagToWireType(0x04)).toBe(WireType.END_GROUP);
+ expect(tagToWireType(0x05)).toBe(WireType.FIXED32);
+
+ // upper bits should not matter
+ expect(tagToWireType(0x08)).toBe(WireType.VARINT);
+ expect(tagToWireType(0x09)).toBe(WireType.FIXED64);
+ expect(tagToWireType(0x0A)).toBe(WireType.DELIMITED);
+ expect(tagToWireType(0x0B)).toBe(WireType.START_GROUP);
+ expect(tagToWireType(0x0C)).toBe(WireType.END_GROUP);
+ expect(tagToWireType(0x0D)).toBe(WireType.FIXED32);
+
+ // upper bits should not matter
+ expect(tagToWireType(0xF8)).toBe(WireType.VARINT);
+ expect(tagToWireType(0xF9)).toBe(WireType.FIXED64);
+ expect(tagToWireType(0xFA)).toBe(WireType.DELIMITED);
+ expect(tagToWireType(0xFB)).toBe(WireType.START_GROUP);
+ expect(tagToWireType(0xFC)).toBe(WireType.END_GROUP);
+ expect(tagToWireType(0xFD)).toBe(WireType.FIXED32);
+
+ // negative numbers work
+ expect(tagToWireType(-8)).toBe(WireType.VARINT);
+ expect(tagToWireType(-7)).toBe(WireType.FIXED64);
+ expect(tagToWireType(-6)).toBe(WireType.DELIMITED);
+ expect(tagToWireType(-5)).toBe(WireType.START_GROUP);
+ expect(tagToWireType(-4)).toBe(WireType.END_GROUP);
+ expect(tagToWireType(-3)).toBe(WireType.FIXED32);
+ });
+});
+
+describe('tagToFieldNumber', () => {
+ it('returns fieldNumber', () => {
+ expect(tagToFieldNumber(0x08)).toBe(1);
+ expect(tagToFieldNumber(0x09)).toBe(1);
+ expect(tagToFieldNumber(0x10)).toBe(2);
+ expect(tagToFieldNumber(0x12)).toBe(2);
+ });
+});
+
+describe('createTag', () => {
+ it('combines fieldNumber and wireType', () => {
+ expect(createTag(WireType.VARINT, 1)).toBe(0x08);
+ expect(createTag(WireType.FIXED64, 1)).toBe(0x09);
+ expect(createTag(WireType.DELIMITED, 1)).toBe(0x0A);
+ expect(createTag(WireType.START_GROUP, 1)).toBe(0x0B);
+ expect(createTag(WireType.END_GROUP, 1)).toBe(0x0C);
+ expect(createTag(WireType.FIXED32, 1)).toBe(0x0D);
+
+ expect(createTag(WireType.VARINT, 2)).toBe(0x10);
+ expect(createTag(WireType.FIXED64, 2)).toBe(0x11);
+ expect(createTag(WireType.DELIMITED, 2)).toBe(0x12);
+ expect(createTag(WireType.START_GROUP, 2)).toBe(0x13);
+ expect(createTag(WireType.END_GROUP, 2)).toBe(0x14);
+ expect(createTag(WireType.FIXED32, 2)).toBe(0x15);
+
+ expect(createTag(WireType.VARINT, 0x1FFFFFFF)).toBe(0xFFFFFFF8 >>> 0);
+ expect(createTag(WireType.FIXED64, 0x1FFFFFFF)).toBe(0xFFFFFFF9 >>> 0);
+ expect(createTag(WireType.DELIMITED, 0x1FFFFFFF)).toBe(0xFFFFFFFA >>> 0);
+ expect(createTag(WireType.START_GROUP, 0x1FFFFFFF)).toBe(0xFFFFFFFB >>> 0);
+ expect(createTag(WireType.END_GROUP, 0x1FFFFFFF)).toBe(0xFFFFFFFC >>> 0);
+ expect(createTag(WireType.FIXED32, 0x1FFFFFFF)).toBe(0xFFFFFFFD >>> 0);
+ });
+});
+
+describe('get32BitVarintLength', () => {
+ it('length of tag', () => {
+ expect(get32BitVarintLength(0)).toBe(1);
+ expect(get32BitVarintLength(1)).toBe(1);
+ expect(get32BitVarintLength(1)).toBe(1);
+
+ expect(get32BitVarintLength(Math.pow(2, 7) - 1)).toBe(1);
+ expect(get32BitVarintLength(Math.pow(2, 7))).toBe(2);
+
+ expect(get32BitVarintLength(Math.pow(2, 14) - 1)).toBe(2);
+ expect(get32BitVarintLength(Math.pow(2, 14))).toBe(3);
+
+ expect(get32BitVarintLength(Math.pow(2, 21) - 1)).toBe(3);
+ expect(get32BitVarintLength(Math.pow(2, 21))).toBe(4);
+
+ expect(get32BitVarintLength(Math.pow(2, 28) - 1)).toBe(4);
+ expect(get32BitVarintLength(Math.pow(2, 28))).toBe(5);
+
+ expect(get32BitVarintLength(Math.pow(2, 31) - 1)).toBe(5);
+
+ expect(get32BitVarintLength(-1)).toBe(5);
+ expect(get32BitVarintLength(-Math.pow(2, 31))).toBe(5);
+
+ expect(get32BitVarintLength(createTag(WireType.VARINT, 0x1fffffff)))
+ .toBe(5);
+ expect(get32BitVarintLength(createTag(WireType.FIXED32, 0x1fffffff)))
+ .toBe(5);
+ });
+});
diff --git a/js/experimental/runtime/kernel/textencoding.js b/js/experimental/runtime/kernel/textencoding.js
new file mode 100644
index 0000000..fe8fd25
--- /dev/null
+++ b/js/experimental/runtime/kernel/textencoding.js
@@ -0,0 +1,116 @@
+/**
+ * @fileoverview A UTF8 decoder.
+ */
+goog.module('protobuf.binary.textencoding');
+
+const {checkElementIndex} = goog.require('protobuf.internal.checks');
+
+/**
+ * Combines an array of codePoints into a string.
+ * @param {!Array<number>} codePoints
+ * @return {string}
+ */
+function codePointsToString(codePoints) {
+ // Performance: http://jsperf.com/string-fromcharcode-test/13
+ let s = '', i = 0;
+ const length = codePoints.length;
+ const BATCH_SIZE = 10000;
+ while (i < length) {
+ const end = Math.min(i + BATCH_SIZE, length);
+ s += String.fromCharCode.apply(null, codePoints.slice(i, end));
+ i = end;
+ }
+ return s;
+}
+
+/**
+ * Decodes raw bytes into a string.
+ * Supports codepoints from U+0000 up to U+10FFFF.
+ * (http://en.wikipedia.org/wiki/UTF-8).
+ * @param {!DataView} bytes
+ * @return {string}
+ */
+function decode(bytes) {
+ let cursor = 0;
+ const codePoints = [];
+
+ while (cursor < bytes.byteLength) {
+ const c = bytes.getUint8(cursor++);
+ if (c < 0x80) { // Regular 7-bit ASCII.
+ codePoints.push(c);
+ } else if (c < 0xC0) {
+ // UTF-8 continuation mark. We are out of sync. This
+ // might happen if we attempted to read a character
+ // with more than four bytes.
+ continue;
+ } else if (c < 0xE0) { // UTF-8 with two bytes.
+ checkElementIndex(cursor, bytes.byteLength);
+ const c2 = bytes.getUint8(cursor++);
+ codePoints.push(((c & 0x1F) << 6) | (c2 & 0x3F));
+ } else if (c < 0xF0) { // UTF-8 with three bytes.
+ checkElementIndex(cursor + 1, bytes.byteLength);
+ const c2 = bytes.getUint8(cursor++);
+ const c3 = bytes.getUint8(cursor++);
+ codePoints.push(((c & 0xF) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F));
+ } else if (c < 0xF8) { // UTF-8 with 4 bytes.
+ checkElementIndex(cursor + 2, bytes.byteLength);
+ const c2 = bytes.getUint8(cursor++);
+ const c3 = bytes.getUint8(cursor++);
+ const c4 = bytes.getUint8(cursor++);
+ // Characters written on 4 bytes have 21 bits for a codepoint.
+ // We can't fit that on 16bit characters, so we use surrogates.
+ let codepoint = ((c & 0x07) << 18) | ((c2 & 0x3F) << 12) |
+ ((c3 & 0x3F) << 6) | (c4 & 0x3F);
+ // Surrogates formula from wikipedia.
+ // 1. Subtract 0x10000 from codepoint
+ codepoint -= 0x10000;
+ // 2. Split this into the high 10-bit value and the low 10-bit value
+ // 3. Add 0xD800 to the high value to form the high surrogate
+ // 4. Add 0xDC00 to the low value to form the low surrogate:
+ const low = (codepoint & 0x3FF) + 0xDC00;
+ const high = ((codepoint >> 10) & 0x3FF) + 0xD800;
+ codePoints.push(high, low);
+ }
+ }
+ return codePointsToString(codePoints);
+}
+
+/**
+ * Writes a UTF16 JavaScript string to the buffer encoded as UTF8.
+ * @param {string} value The string to write.
+ * @return {!Uint8Array} An array containing the encoded bytes.
+ */
+function encode(value) {
+ const buffer = [];
+
+ for (let i = 0; i < value.length; i++) {
+ const c1 = value.charCodeAt(i);
+
+ if (c1 < 0x80) {
+ buffer.push(c1);
+ } else if (c1 < 0x800) {
+ buffer.push((c1 >> 6) | 0xC0);
+ buffer.push((c1 & 0x3F) | 0x80);
+ } else if (c1 < 0xD800 || c1 >= 0xE000) {
+ buffer.push((c1 >> 12) | 0xE0);
+ buffer.push(((c1 >> 6) & 0x3F) | 0x80);
+ buffer.push((c1 & 0x3F) | 0x80);
+ } else {
+ // surrogate pair
+ i++;
+ checkElementIndex(i, value.length);
+ const c2 = value.charCodeAt(i);
+ const paired = 0x10000 + (((c1 & 0x3FF) << 10) | (c2 & 0x3FF));
+ buffer.push((paired >> 18) | 0xF0);
+ buffer.push(((paired >> 12) & 0x3F) | 0x80);
+ buffer.push(((paired >> 6) & 0x3F) | 0x80);
+ buffer.push((paired & 0x3F) | 0x80);
+ }
+ }
+ return new Uint8Array(buffer);
+}
+
+exports = {
+ decode,
+ encode,
+};
diff --git a/js/experimental/runtime/kernel/textencoding_test.js b/js/experimental/runtime/kernel/textencoding_test.js
new file mode 100644
index 0000000..c7ecd18
--- /dev/null
+++ b/js/experimental/runtime/kernel/textencoding_test.js
@@ -0,0 +1,113 @@
+/**
+ * @fileoverview Tests for textdecoder.js.
+ */
+goog.module('protobuf.binary.TextDecoderTest');
+
+goog.setTestOnly();
+
+const {decode, encode} = goog.require('protobuf.binary.textencoding');
+
+describe('Decode does', () => {
+ it('return empty string for empty array', () => {
+ expect(decode(new DataView(new ArrayBuffer(0)))).toEqual('');
+ });
+
+ it('throw on null being passed', () => {
+ expect(() => decode(/** @type {!DataView} */ (/** @type {*} */ (null))))
+ .toThrow();
+ });
+});
+
+describe('Encode does', () => {
+ it('return empty array for empty string', () => {
+ expect(encode('')).toEqual(new Uint8Array(0));
+ });
+
+ it('throw on null being passed', () => {
+ expect(() => encode(/** @type {string} */ (/** @type {*} */ (null))))
+ .toThrow();
+ });
+});
+
+/** @const {!TextEncoder} */
+const textEncoder = new TextEncoder('utf-8');
+
+/**
+ * A Pair of string and Uint8Array representing the same data.
+ * Each pair has the string value and its utf-8 bytes.
+ */
+class Pair {
+ /**
+ * Constructs a pair from a given string.
+ * @param {string} s
+ * @return {!Pair}
+ */
+ static fromString(s) {
+ return new Pair(s, textEncoder.encode(s).buffer);
+ }
+ /**
+ * Constructs a pair from a given charCode.
+ * @param {number} charCode
+ * @return {!Pair}
+ */
+ static fromCharCode(charCode) {
+ return Pair.fromString(String.fromCharCode(charCode));
+ }
+
+ /**
+ * @param {string} stringValue
+ * @param {!ArrayBuffer} bytes
+ * @private
+ */
+ constructor(stringValue, bytes) {
+ /** @const @private {string} */
+ this.stringValue_ = stringValue;
+ /** @const @private {!ArrayBuffer} */
+ this.bytes_ = bytes;
+ }
+
+ /** Ensures that a given pair encodes and decodes round trip*/
+ expectPairToMatch() {
+ expect(decode(new DataView(this.bytes_))).toEqual(this.stringValue_);
+ expect(encode(this.stringValue_)).toEqual(new Uint8Array(this.bytes_));
+ }
+}
+
+describe('textencoding does', () => {
+ it('works for empty string', () => {
+ Pair.fromString('').expectPairToMatch();
+ });
+
+ it('decode and encode random strings', () => {
+ // 1 byte strings
+ Pair.fromString('hello').expectPairToMatch();
+ Pair.fromString('HELLO1!');
+
+ // 2 byte String
+ Pair.fromString('©').expectPairToMatch();
+
+ // 3 byte string
+ Pair.fromString('❄').expectPairToMatch();
+
+ // 4 byte string
+ Pair.fromString('😁').expectPairToMatch();
+ });
+
+ it('decode and encode 1 byte strings', () => {
+ for (let i = 0; i < 0x80; i++) {
+ Pair.fromCharCode(i).expectPairToMatch();
+ }
+ });
+
+ it('decode and encode 2 byte strings', () => {
+ for (let i = 0xC0; i < 0x7FF; i++) {
+ Pair.fromCharCode(i).expectPairToMatch();
+ }
+ });
+
+ it('decode and encode 3 byte strings', () => {
+ for (let i = 0x7FF; i < 0x8FFF; i++) {
+ Pair.fromCharCode(i).expectPairToMatch();
+ }
+ });
+});
diff --git a/js/experimental/runtime/kernel/typed_arrays.js b/js/experimental/runtime/kernel/typed_arrays.js
new file mode 100644
index 0000000..0280965
--- /dev/null
+++ b/js/experimental/runtime/kernel/typed_arrays.js
@@ -0,0 +1,116 @@
+/**
+ * @fileoverview Helper methods for typed arrays.
+ */
+goog.module('protobuf.binary.typedArrays');
+
+const {assert} = goog.require('goog.asserts');
+
+/**
+ * @param {!ArrayBuffer} buffer1
+ * @param {!ArrayBuffer} buffer2
+ * @return {boolean}
+ */
+function arrayBufferEqual(buffer1, buffer2) {
+ if (!buffer1 || !buffer2) {
+ throw new Error('Buffer shouldn\'t be empty');
+ }
+
+ const array1 = new Uint8Array(buffer1);
+ const array2 = new Uint8Array(buffer2);
+
+ return uint8ArrayEqual(array1, array2);
+}
+
+/**
+ * @param {!Uint8Array} array1
+ * @param {!Uint8Array} array2
+ * @return {boolean}
+ */
+function uint8ArrayEqual(array1, array2) {
+ if (array1 === array2) {
+ return true;
+ }
+
+ if (array1.byteLength !== array2.byteLength) {
+ return false;
+ }
+
+ for (let i = 0; i < array1.byteLength; i++) {
+ if (array1[i] !== array2[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/**
+ * ArrayBuffer.prototype.slice, but fallback to manual copy if missing.
+ * @param {!ArrayBuffer} buffer
+ * @param {number} start
+ * @param {number=} end
+ * @return {!ArrayBuffer} New array buffer with given the contents of `buffer`.
+ */
+function arrayBufferSlice(buffer, start, end = undefined) {
+ // The fallback isn't fully compatible with ArrayBuffer.slice, enforce
+ // strict requirements on start/end.
+ // Spec:
+ // https://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer.prototype.slice
+ assert(start >= 0);
+ assert(end === undefined || (end >= 0 && end <= buffer.byteLength));
+ assert((end === undefined ? buffer.byteLength : end) >= start);
+ if (buffer.slice) {
+ const slicedBuffer = buffer.slice(start, end);
+ // The ArrayBuffer.prototype.slice function was flawed before iOS 12.2. This
+ // causes 0-length results when passing undefined or a number greater
+ // than 32 bits for the optional end value. In these cases, we fall back to
+ // using our own slice implementation.
+ // More details: https://bugs.webkit.org/show_bug.cgi?id=185127
+ if (slicedBuffer.byteLength !== 0 || (start === end)) {
+ return slicedBuffer;
+ }
+ }
+ const realEnd = end == null ? buffer.byteLength : end;
+ const length = realEnd - start;
+ assert(length >= 0);
+ const view = new Uint8Array(buffer, start, length);
+ // A TypedArray constructed from another Typed array copies the data.
+ const clone = new Uint8Array(view);
+
+ return clone.buffer;
+}
+
+/**
+ * Returns a new Uint8Array with the size and contents of the given
+ * ArrayBufferView. ArrayBufferView is an interface implemented by DataView,
+ * Uint8Array and all typed arrays.
+ * @param {!ArrayBufferView} view
+ * @return {!Uint8Array}
+ */
+function cloneArrayBufferView(view) {
+ return new Uint8Array(arrayBufferSlice(
+ view.buffer, view.byteOffset, view.byteOffset + view.byteLength));
+}
+
+/**
+ * Returns a 32 bit number for the corresponding Uint8Array.
+ * @param {!Uint8Array} array
+ * @return {number}
+ */
+function hashUint8Array(array) {
+ const prime = 31;
+ let result = 17;
+
+ for (let i = 0; i < array.length; i++) {
+ // '| 0' ensures signed 32 bits
+ result = (result * prime + array[i]) | 0;
+ }
+ return result;
+}
+
+exports = {
+ arrayBufferEqual,
+ uint8ArrayEqual,
+ arrayBufferSlice,
+ cloneArrayBufferView,
+ hashUint8Array,
+};
diff --git a/js/experimental/runtime/kernel/typed_arrays_test.js b/js/experimental/runtime/kernel/typed_arrays_test.js
new file mode 100644
index 0000000..be9ba65
--- /dev/null
+++ b/js/experimental/runtime/kernel/typed_arrays_test.js
@@ -0,0 +1,191 @@
+/**
+ * @fileoverview Tests for typed_arrays.js.
+ */
+goog.module('protobuf.binary.typedArraysTest');
+
+const {arrayBufferEqual, arrayBufferSlice, cloneArrayBufferView, hashUint8Array, uint8ArrayEqual} = goog.require('protobuf.binary.typedArrays');
+
+describe('arrayBufferEqual', () => {
+ it('returns true for empty buffers', () => {
+ const buffer1 = new ArrayBuffer(0);
+ const buffer2 = new ArrayBuffer(0);
+ expect(arrayBufferEqual(buffer1, buffer2)).toBe(true);
+ });
+
+ it('throws for first null buffers', () => {
+ const buffer = new ArrayBuffer(0);
+ expect(
+ () => arrayBufferEqual(
+ /** @type {!ArrayBuffer} */ (/** @type {*} */ (null)), buffer))
+ .toThrow();
+ });
+
+ it('throws for second null buffers', () => {
+ const buffer = new ArrayBuffer(0);
+ expect(
+ () => arrayBufferEqual(
+ buffer, /** @type {!ArrayBuffer} */ (/** @type {*} */ (null))))
+ .toThrow();
+ });
+
+ it('returns true for arrays with same values', () => {
+ const array1 = new Uint8Array(4);
+ array1[0] = 1;
+ const array2 = new Uint8Array(4);
+ array2[0] = 1;
+ expect(arrayBufferEqual(array1.buffer, array2.buffer)).toBe(true);
+ });
+
+ it('returns false for arrays with different values', () => {
+ const array1 = new Uint8Array(4);
+ array1[0] = 1;
+ const array2 = new Uint8Array(4);
+ array2[0] = 2;
+ expect(arrayBufferEqual(array1.buffer, array2.buffer)).toBe(false);
+ });
+
+ it('returns true same instance', () => {
+ const array1 = new Uint8Array(4);
+ array1[0] = 1;
+ expect(arrayBufferEqual(array1.buffer, array1.buffer)).toBe(true);
+ });
+});
+
+describe('uint8ArrayEqual', () => {
+ it('returns true for empty arrays', () => {
+ const array1 = new Uint8Array(0);
+ const array2 = new Uint8Array(0);
+ expect(uint8ArrayEqual(array1, array2)).toBe(true);
+ });
+
+ it('throws for first Uint8Array array', () => {
+ const array = new Uint8Array(0);
+ expect(
+ () => uint8ArrayEqual(
+ /** @type {!Uint8Array} */ (/** @type {*} */ (null)), array))
+ .toThrow();
+ });
+
+ it('throws for second null array', () => {
+ const array = new Uint8Array(0);
+ expect(
+ () => uint8ArrayEqual(
+ array, /** @type {!Uint8Array} */ (/** @type {*} */ (null))))
+ .toThrow();
+ });
+
+ it('returns true for arrays with same values', () => {
+ const buffer1 = new Uint8Array([0, 1, 2, 3]).buffer;
+ const buffer2 = new Uint8Array([1, 2, 3, 4]).buffer;
+ const array1 = new Uint8Array(buffer1, 1, 3);
+ const array2 = new Uint8Array(buffer2, 0, 3);
+ expect(uint8ArrayEqual(array1, array2)).toBe(true);
+ });
+
+ it('returns false for arrays with different values', () => {
+ const array1 = new Uint8Array(4);
+ array1[0] = 1;
+ const array2 = new Uint8Array(4);
+ array2[0] = 2;
+ expect(uint8ArrayEqual(array1, array2)).toBe(false);
+ });
+
+ it('returns true same instance', () => {
+ const array1 = new Uint8Array(4);
+ array1[0] = 1;
+ expect(uint8ArrayEqual(array1, array1)).toBe(true);
+ });
+});
+
+describe('arrayBufferSlice', () => {
+ it('Returns a new instance.', () => {
+ const buffer1 = new ArrayBuffer(0);
+ const buffer2 = arrayBufferSlice(buffer1, 0);
+ expect(buffer2).not.toBe(buffer1);
+ expect(arrayBufferEqual(buffer1, buffer2)).toBe(true);
+ });
+
+ it('Copies data with positive start/end.', () => {
+ const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer;
+ expect(buffer1.byteLength).toEqual(10);
+
+ const buffer2 = arrayBufferSlice(buffer1, 2, 6);
+ expect(buffer2.byteLength).toEqual(4);
+ expect(buffer2).not.toBe(buffer1);
+ const expected = new Uint8Array([2, 3, 4, 5]).buffer;
+ expect(arrayBufferEqual(expected, buffer2)).toBe(true);
+ });
+
+ it('Copies all data without end.', () => {
+ const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer;
+ expect(buffer1.byteLength).toEqual(10);
+
+ const buffer2 = arrayBufferSlice(buffer1, 0);
+ expect(buffer2.byteLength).toEqual(10);
+ expect(arrayBufferEqual(buffer1, buffer2)).toBe(true);
+ });
+
+ if (goog.DEBUG) {
+ it('Fails with negative end.', () => {
+ const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer;
+ expect(() => void arrayBufferSlice(buffer1, 2, -1)).toThrow();
+ });
+
+ it('Fails with negative start.', () => {
+ const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer;
+ expect(() => void arrayBufferSlice(buffer1, 2, -1)).toThrow();
+ });
+
+ it('Fails when start > end.', () => {
+ const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer;
+ expect(() => void arrayBufferSlice(buffer1, 2, 1)).toThrow();
+ });
+ }
+});
+
+describe('cloneArrayBufferView', () => {
+ it('Returns a new instance.', () => {
+ const array1 = new Uint8Array(0);
+ const array2 = cloneArrayBufferView(new Uint8Array(array1));
+ expect(array2).not.toBe(array1);
+ expect(uint8ArrayEqual(array1, array2)).toBe(true);
+ });
+
+ it('Returns an array of the exact size.', () => {
+ const array1 =
+ new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).subarray(2, 5);
+ expect(array1.length).toEqual(3);
+ expect(array1.buffer.byteLength).toEqual(10);
+ const array2 = cloneArrayBufferView(array1);
+ expect(array2.byteLength).toEqual(3);
+ expect(array2).toEqual(new Uint8Array([2, 3, 4]));
+ });
+});
+
+describe('hashUint8Array', () => {
+ it('returns same hashcode for empty Uint8Arrays', () => {
+ const array1 = new Uint8Array(0);
+ const array2 = new Uint8Array(0);
+ expect(hashUint8Array(array1)).toBe(hashUint8Array(array2));
+ });
+
+ it('returns same hashcode for Uint8Arrays with same values', () => {
+ const array1 = new Uint8Array(4);
+ array1[0] = 1;
+ const array2 = new Uint8Array(4);
+ array2[0] = 1;
+ expect(hashUint8Array(array1)).toBe(hashUint8Array(array2));
+ });
+
+ it('returns different hashcode for Uint8Arrays with different values', () => {
+ // This test might fail in the future if the hashing algorithm is updated
+ // and we end up with a collision here.
+ // We still need this test to make sure that we are not just returning
+ // the same number for all buffers.
+ const array1 = new Uint8Array(4);
+ array1[0] = 1;
+ const array2 = new Uint8Array(4);
+ array2[0] = 2;
+ expect(hashUint8Array(array1)).not.toBe(hashUint8Array(array2));
+ });
+});
diff --git a/js/experimental/runtime/kernel/uint32_test_pairs.js b/js/experimental/runtime/kernel/uint32_test_pairs.js
new file mode 100644
index 0000000..851996d
--- /dev/null
+++ b/js/experimental/runtime/kernel/uint32_test_pairs.js
@@ -0,0 +1,68 @@
+/**
+ * @fileoverview Test data for int32 encoding and decoding.
+ */
+goog.module('protobuf.binary.uint32TestPairs');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper');
+
+/**
+ * An array of Pairs of float values and their bit representation.
+ * This is used to test encoding and decoding from/to the protobuf wire format.
+ * @return {!Array<{name: string, intValue:number, bufferDecoder:
+ * !BufferDecoder, error: (boolean|undefined),
+ * skip_reader: (boolean|undefined), skip_writer: (boolean|undefined)}>}
+ */
+function getUint32Pairs() {
+ const uint32Pairs = [
+ {
+ name: 'zero',
+ intValue: 0,
+ bufferDecoder: createBufferDecoder(0x00),
+ },
+ {
+ name: 'one ',
+ intValue: 1,
+ bufferDecoder: createBufferDecoder(0x01),
+ },
+ {
+ name: 'max signed int 2^31 - 1',
+ intValue: Math.pow(2, 31) - 1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0x07),
+ },
+ {
+ name: 'max unsigned int 2^32 - 1',
+ intValue: Math.pow(2, 32) - 1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0x0F),
+ },
+ {
+ name: 'negative one',
+ intValue: -1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0x0F),
+ skip_reader: true,
+ },
+ {
+ name: 'truncates more than 32 bits',
+ intValue: Math.pow(2, 32) - 1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01),
+ skip_writer: true,
+ },
+ {
+ name: 'truncates more than 32 bits (bit 33 set)',
+ intValue: Math.pow(2, 28) - 1,
+ bufferDecoder: createBufferDecoder(0xFF, 0xFF, 0xFF, 0xFF, 0x10),
+ skip_writer: true,
+ },
+ {
+ name: 'errors out for 11 bytes',
+ intValue: Math.pow(2, 32) - 1,
+ bufferDecoder: createBufferDecoder(
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF),
+ error: true,
+ skip_writer: true,
+ },
+ ];
+ return [...uint32Pairs];
+}
+
+exports = {getUint32Pairs};
diff --git a/js/experimental/runtime/kernel/uint8arrays.js b/js/experimental/runtime/kernel/uint8arrays.js
new file mode 100644
index 0000000..c6bed16
--- /dev/null
+++ b/js/experimental/runtime/kernel/uint8arrays.js
@@ -0,0 +1,28 @@
+/**
+ * @fileoverview Helper methods for Uint8Arrays.
+ */
+goog.module('protobuf.binary.uint8arrays');
+
+/**
+ * Combines multiple bytes arrays (either Uint8Array or number array whose
+ * values are bytes) into a single Uint8Array.
+ * @param {!Array<!Uint8Array>|!Array<!Array<number>>} arrays
+ * @return {!Uint8Array}
+ */
+function concatenateByteArrays(arrays) {
+ let totalLength = 0;
+ for (const array of arrays) {
+ totalLength += array.length;
+ }
+ const result = new Uint8Array(totalLength);
+ let offset = 0;
+ for (const array of arrays) {
+ result.set(array, offset);
+ offset += array.length;
+ }
+ return result;
+}
+
+exports = {
+ concatenateByteArrays,
+};
diff --git a/js/experimental/runtime/kernel/uint8arrays_test.js b/js/experimental/runtime/kernel/uint8arrays_test.js
new file mode 100644
index 0000000..6bb5a75
--- /dev/null
+++ b/js/experimental/runtime/kernel/uint8arrays_test.js
@@ -0,0 +1,47 @@
+/**
+ * @fileoverview Tests for uint8arrays.js.
+ */
+goog.module('protobuf.binary.Uint8ArraysTest');
+
+goog.setTestOnly();
+
+const {concatenateByteArrays} = goog.require('protobuf.binary.uint8arrays');
+
+describe('concatenateByteArrays does', () => {
+ it('concatenate empty array', () => {
+ const byteArrays = [];
+ expect(concatenateByteArrays(byteArrays)).toEqual(new Uint8Array(0));
+ });
+
+ it('concatenate Uint8Arrays', () => {
+ const byteArrays = [new Uint8Array([0x01]), new Uint8Array([0x02])];
+ expect(concatenateByteArrays(byteArrays)).toEqual(new Uint8Array([
+ 0x01, 0x02
+ ]));
+ });
+
+ it('concatenate array of bytes', () => {
+ const byteArrays = [[0x01], [0x02]];
+ expect(concatenateByteArrays(byteArrays)).toEqual(new Uint8Array([
+ 0x01, 0x02
+ ]));
+ });
+
+ it('concatenate array of non-bytes', () => {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ const byteArrays = [[40.0], [256]];
+ expect(concatenateByteArrays(byteArrays)).toEqual(new Uint8Array([
+ 0x28, 0x00
+ ]));
+ });
+
+ it('throw for null array', () => {
+ expect(
+ () => concatenateByteArrays(
+ /** @type {!Array<!Uint8Array>} */ (/** @type {*} */ (null))))
+ .toThrow();
+ });
+});
diff --git a/js/experimental/runtime/kernel/wire_type.js b/js/experimental/runtime/kernel/wire_type.js
new file mode 100644
index 0000000..dee6fe4
--- /dev/null
+++ b/js/experimental/runtime/kernel/wire_type.js
@@ -0,0 +1,17 @@
+goog.module('protobuf.binary.WireType');
+
+/**
+ * Wire-format type codes, taken from proto2/public/wire_format_lite.h.
+ * @enum {number}
+ */
+const WireType = {
+ VARINT: 0,
+ FIXED64: 1,
+ DELIMITED: 2,
+ START_GROUP: 3,
+ END_GROUP: 4,
+ FIXED32: 5,
+ INVALID: 6
+};
+
+exports = WireType;
diff --git a/js/experimental/runtime/kernel/writer.js b/js/experimental/runtime/kernel/writer.js
new file mode 100644
index 0000000..5b8b79b
--- /dev/null
+++ b/js/experimental/runtime/kernel/writer.js
@@ -0,0 +1,743 @@
+/**
+ * @fileoverview Implements Writer for writing data as the binary wire format
+ * bytes array.
+ */
+goog.module('protobuf.binary.Writer');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const WireType = goog.require('protobuf.binary.WireType');
+const {POLYFILL_TEXT_ENCODING, checkFieldNumber, checkTypeUnsignedInt32, checkWireType} = goog.require('protobuf.internal.checks');
+const {concatenateByteArrays} = goog.require('protobuf.binary.uint8arrays');
+const {createTag, getTagLength} = goog.require('protobuf.binary.tag');
+const {encode} = goog.require('protobuf.binary.textencoding');
+
+/**
+ * Returns a valid utf-8 encoder function based on TextEncoder if available or
+ * a polyfill.
+ * Some of the environments we run in do not have TextEncoder defined.
+ * TextEncoder is faster than our polyfill so we prefer it over the polyfill.
+ * @return {function(string):!Uint8Array}
+ */
+function getEncoderFunction() {
+ if (goog.global['TextEncoder']) {
+ const textEncoder = new goog.global['TextEncoder']('utf-8');
+ return s => s.length === 0 ? new Uint8Array(0) : textEncoder.encode(s);
+ }
+ if (POLYFILL_TEXT_ENCODING) {
+ return encode;
+ } else {
+ throw new Error(
+ 'TextEncoder is missing. ' +
+ 'Enable protobuf.defines.POLYFILL_TEXT_ENCODING');
+ }
+}
+
+/** @const {function(string): !Uint8Array} */
+const encoderFunction = getEncoderFunction();
+
+/**
+ * Writer provides methods for encoding all protobuf supported type into a
+ * binary format bytes array.
+ * Check https://developers.google.com/protocol-buffers/docs/encoding for binary
+ * format definition.
+ * @final
+ * @package
+ */
+class Writer {
+ constructor() {
+ /**
+ * Blocks of data that needs to be serialized. After writing all the data,
+ * the blocks are concatenated into a single Uint8Array.
+ * @private {!Array<!Uint8Array>}
+ */
+ this.blocks_ = [];
+
+ /**
+ * A buffer for writing varint data (tag number + field number for each
+ * field, int32, uint32 etc.). Before writing a non-varint data block
+ * (string, fixed32 etc.), the buffer is appended to the block array as a
+ * new block, and a new buffer is started.
+ *
+ * We could've written each varint as a new block instead of writing
+ * multiple varints in this buffer. But this will increase the number of
+ * blocks, and concatenating many small blocks is slower than concatenating
+ * few large blocks.
+ *
+ * TODO: Experiment with writing data in a fixed-length
+ * Uint8Array instead of using a growing buffer.
+ *
+ * @private {!Array<number>}
+ */
+ this.currentBuffer_ = [];
+ }
+
+ /**
+ * Converts the encoded data into a Uint8Array.
+ * The writer is also reset.
+ * @return {!ArrayBuffer}
+ */
+ getAndResetResultBuffer() {
+ this.closeAndStartNewBuffer_();
+ const result = concatenateByteArrays(this.blocks_);
+ this.blocks_ = [];
+ return result.buffer;
+ }
+
+ /**
+ * Encodes a (field number, wire type) tuple into a wire-format field header.
+ * @param {number} fieldNumber
+ * @param {!WireType} wireType
+ */
+ writeTag(fieldNumber, wireType) {
+ checkFieldNumber(fieldNumber);
+ checkWireType(wireType);
+ const tag = createTag(wireType, fieldNumber);
+ this.writeUnsignedVarint32_(tag);
+ }
+
+ /**
+ * Appends the current buffer into the blocks array and starts a new buffer.
+ * @private
+ */
+ closeAndStartNewBuffer_() {
+ this.blocks_.push(new Uint8Array(this.currentBuffer_));
+ this.currentBuffer_ = [];
+ }
+
+ /**
+ * Encodes a 32-bit integer into its wire-format varint representation and
+ * stores it in the buffer.
+ * @param {number} value
+ * @private
+ */
+ writeUnsignedVarint32_(value) {
+ checkTypeUnsignedInt32(value);
+ while (value > 0x7f) {
+ this.currentBuffer_.push((value & 0x7f) | 0x80);
+ value = value >>> 7;
+ }
+ this.currentBuffer_.push(value);
+ }
+
+ /****************************************************************************
+ * OPTIONAL METHODS
+ ****************************************************************************/
+
+ /**
+ * Writes a boolean value field to the buffer as a varint.
+ * @param {boolean} value
+ * @private
+ */
+ writeBoolValue_(value) {
+ this.currentBuffer_.push(value ? 1 : 0);
+ }
+
+ /**
+ * Writes a boolean value field to the buffer as a varint.
+ * @param {number} fieldNumber
+ * @param {boolean} value
+ */
+ writeBool(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.VARINT);
+ this.writeBoolValue_(value);
+ }
+
+ /**
+ * Writes a bytes value field to the buffer as a length delimited field.
+ * @param {number} fieldNumber
+ * @param {!ByteString} value
+ */
+ writeBytes(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.DELIMITED);
+ const buffer = value.toArrayBuffer();
+ this.writeUnsignedVarint32_(buffer.byteLength);
+ this.writeRaw_(buffer);
+ }
+
+ /**
+ * Writes a double value field to the buffer without tag.
+ * @param {number} value
+ * @private
+ */
+ writeDoubleValue_(value) {
+ const buffer = new ArrayBuffer(8);
+ const view = new DataView(buffer);
+ view.setFloat64(0, value, true);
+ this.writeRaw_(buffer);
+ }
+
+ /**
+ * Writes a double value field to the buffer.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ writeDouble(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.FIXED64);
+ this.writeDoubleValue_(value);
+ }
+
+ /**
+ * Writes a fixed32 value field to the buffer without tag.
+ * @param {number} value
+ * @private
+ */
+ writeFixed32Value_(value) {
+ const buffer = new ArrayBuffer(4);
+ const view = new DataView(buffer);
+ view.setUint32(0, value, true);
+ this.writeRaw_(buffer);
+ }
+
+ /**
+ * Writes a fixed32 value field to the buffer.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ writeFixed32(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.FIXED32);
+ this.writeFixed32Value_(value);
+ }
+
+ /**
+ * Writes a float value field to the buffer without tag.
+ * @param {number} value
+ * @private
+ */
+ writeFloatValue_(value) {
+ const buffer = new ArrayBuffer(4);
+ const view = new DataView(buffer);
+ view.setFloat32(0, value, true);
+ this.writeRaw_(buffer);
+ }
+
+ /**
+ * Writes a float value field to the buffer.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ writeFloat(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.FIXED32);
+ this.writeFloatValue_(value);
+ }
+
+ /**
+ * Writes a int32 value field to the buffer as a varint without tag.
+ * @param {number} value
+ * @private
+ */
+ writeInt32Value_(value) {
+ if (value >= 0) {
+ this.writeVarint64_(0, value);
+ } else {
+ this.writeVarint64_(0xFFFFFFFF, value);
+ }
+ }
+
+ /**
+ * Writes a int32 value field to the buffer as a varint.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ writeInt32(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.VARINT);
+ this.writeInt32Value_(value);
+ }
+
+ /**
+ * Writes a int64 value field to the buffer as a varint.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ writeInt64(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.VARINT);
+ this.writeVarint64_(value.getHighBits(), value.getLowBits());
+ }
+
+ /**
+ * Writes a sfixed32 value field to the buffer.
+ * @param {number} value
+ * @private
+ */
+ writeSfixed32Value_(value) {
+ const buffer = new ArrayBuffer(4);
+ const view = new DataView(buffer);
+ view.setInt32(0, value, true);
+ this.writeRaw_(buffer);
+ }
+
+ /**
+ * Writes a sfixed32 value field to the buffer.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ writeSfixed32(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.FIXED32);
+ this.writeSfixed32Value_(value);
+ }
+
+ /**
+ * Writes a sfixed64 value field to the buffer without tag.
+ * @param {!Int64} value
+ * @private
+ */
+ writeSfixed64Value_(value) {
+ const buffer = new ArrayBuffer(8);
+ const view = new DataView(buffer);
+ view.setInt32(0, value.getLowBits(), true);
+ view.setInt32(4, value.getHighBits(), true);
+ this.writeRaw_(buffer);
+ }
+
+ /**
+ * Writes a sfixed64 value field to the buffer.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ writeSfixed64(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.FIXED64);
+ this.writeSfixed64Value_(value);
+ }
+
+ /**
+ * Writes a sfixed64 value field to the buffer.
+ * @param {number} fieldNumber
+ */
+ writeStartGroup(fieldNumber) {
+ this.writeTag(fieldNumber, WireType.START_GROUP);
+ }
+
+ /**
+ * Writes a sfixed64 value field to the buffer.
+ * @param {number} fieldNumber
+ */
+ writeEndGroup(fieldNumber) {
+ this.writeTag(fieldNumber, WireType.END_GROUP);
+ }
+
+ /**
+ * Writes a uint32 value field to the buffer as a varint without tag.
+ * @param {number} value
+ * @private
+ */
+ writeUint32Value_(value) {
+ this.writeVarint64_(0, value);
+ }
+
+ /**
+ * Writes a uint32 value field to the buffer as a varint.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ writeUint32(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.VARINT);
+ this.writeUint32Value_(value);
+ }
+
+ /**
+ * Writes the bits of a 64 bit number to the buffer as a varint.
+ * @param {number} highBits
+ * @param {number} lowBits
+ * @private
+ */
+ writeVarint64_(highBits, lowBits) {
+ for (let i = 0; i < 28; i = i + 7) {
+ const shift = lowBits >>> i;
+ const hasNext = !((shift >>> 7) === 0 && highBits === 0);
+ const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
+ this.currentBuffer_.push(byte);
+ if (!hasNext) {
+ return;
+ }
+ }
+
+ const splitBits = ((lowBits >>> 28) & 0x0F) | ((highBits & 0x07) << 4);
+ const hasMoreBits = !((highBits >> 3) === 0);
+ this.currentBuffer_.push(
+ (hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF);
+
+ if (!hasMoreBits) {
+ return;
+ }
+
+ for (let i = 3; i < 31; i = i + 7) {
+ const shift = highBits >>> i;
+ const hasNext = !((shift >>> 7) === 0);
+ const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
+ this.currentBuffer_.push(byte);
+ if (!hasNext) {
+ return;
+ }
+ }
+
+ this.currentBuffer_.push((highBits >>> 31) & 0x01);
+ }
+
+ /**
+ * Writes a sint32 value field to the buffer as a varint without tag.
+ * @param {number} value
+ * @private
+ */
+ writeSint32Value_(value) {
+ value = (value << 1) ^ (value >> 31);
+ this.writeVarint64_(0, value);
+ }
+
+ /**
+ * Writes a sint32 value field to the buffer as a varint.
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ writeSint32(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.VARINT);
+ this.writeSint32Value_(value);
+ }
+
+ /**
+ * Writes a sint64 value field to the buffer as a varint without tag.
+ * @param {!Int64} value
+ * @private
+ */
+ writeSint64Value_(value) {
+ const highBits = value.getHighBits();
+ const lowBits = value.getLowBits();
+
+ const sign = highBits >> 31;
+ const encodedLowBits = (lowBits << 1) ^ sign;
+ const encodedHighBits = ((highBits << 1) | (lowBits >>> 31)) ^ sign;
+ this.writeVarint64_(encodedHighBits, encodedLowBits);
+ }
+
+ /**
+ * Writes a sint64 value field to the buffer as a varint.
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ writeSint64(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.VARINT);
+ this.writeSint64Value_(value);
+ }
+
+ /**
+ * Writes a string value field to the buffer as a varint.
+ * @param {number} fieldNumber
+ * @param {string} value
+ */
+ writeString(fieldNumber, value) {
+ this.writeTag(fieldNumber, WireType.DELIMITED);
+ const array = encoderFunction(value);
+ this.writeUnsignedVarint32_(array.length);
+ this.closeAndStartNewBuffer_();
+ this.blocks_.push(array);
+ }
+
+ /**
+ * Writes raw bytes to the buffer.
+ * @param {!ArrayBuffer} arrayBuffer
+ * @private
+ */
+ writeRaw_(arrayBuffer) {
+ this.closeAndStartNewBuffer_();
+ this.blocks_.push(new Uint8Array(arrayBuffer));
+ }
+
+ /**
+ * Writes raw bytes to the buffer.
+ * @param {!BufferDecoder} bufferDecoder
+ * @param {number} start
+ * @param {!WireType} wireType
+ * @param {number} fieldNumber
+ * @package
+ */
+ writeBufferDecoder(bufferDecoder, start, wireType, fieldNumber) {
+ this.closeAndStartNewBuffer_();
+ const dataLength =
+ getTagLength(bufferDecoder, start, wireType, fieldNumber);
+ this.blocks_.push(
+ bufferDecoder.subBufferDecoder(start, dataLength).asUint8Array());
+ }
+
+ /**
+ * Write the whole bytes as a length delimited field.
+ * @param {number} fieldNumber
+ * @param {!ArrayBuffer} arrayBuffer
+ */
+ writeDelimited(fieldNumber, arrayBuffer) {
+ this.writeTag(fieldNumber, WireType.DELIMITED);
+ this.writeUnsignedVarint32_(arrayBuffer.byteLength);
+ this.writeRaw_(arrayBuffer);
+ }
+
+ /****************************************************************************
+ * REPEATED METHODS
+ ****************************************************************************/
+
+ /**
+ * Writes repeated boolean values to the buffer as unpacked varints.
+ * @param {number} fieldNumber
+ * @param {!Array<boolean>} values
+ */
+ writeRepeatedBool(fieldNumber, values) {
+ values.forEach(val => this.writeBool(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated boolean values to the buffer as packed varints.
+ * @param {number} fieldNumber
+ * @param {!Array<boolean>} values
+ */
+ writePackedBool(fieldNumber, values) {
+ this.writeFixedPacked_(
+ fieldNumber, values, val => this.writeBoolValue_(val), 1);
+ }
+
+ /**
+ * Writes repeated double values to the buffer as unpacked fixed64.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writeRepeatedDouble(fieldNumber, values) {
+ values.forEach(val => this.writeDouble(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated double values to the buffer as packed fixed64.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writePackedDouble(fieldNumber, values) {
+ this.writeFixedPacked_(
+ fieldNumber, values, val => this.writeDoubleValue_(val), 8);
+ }
+
+ /**
+ * Writes repeated fixed32 values to the buffer as unpacked fixed32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writeRepeatedFixed32(fieldNumber, values) {
+ values.forEach(val => this.writeFixed32(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated fixed32 values to the buffer as packed fixed32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writePackedFixed32(fieldNumber, values) {
+ this.writeFixedPacked_(
+ fieldNumber, values, val => this.writeFixed32Value_(val), 4);
+ }
+
+ /**
+ * Writes repeated float values to the buffer as unpacked fixed64.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writeRepeatedFloat(fieldNumber, values) {
+ values.forEach(val => this.writeFloat(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated float values to the buffer as packed fixed64.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writePackedFloat(fieldNumber, values) {
+ this.writeFixedPacked_(
+ fieldNumber, values, val => this.writeFloatValue_(val), 4);
+ }
+
+ /**
+ * Writes repeated int32 values to the buffer as unpacked int32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writeRepeatedInt32(fieldNumber, values) {
+ values.forEach(val => this.writeInt32(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated int32 values to the buffer as packed int32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writePackedInt32(fieldNumber, values) {
+ this.writeVariablePacked_(
+ fieldNumber, values, (writer, val) => writer.writeInt32Value_(val));
+ }
+
+ /**
+ * Writes repeated int64 values to the buffer as unpacked varint.
+ * @param {number} fieldNumber
+ * @param {!Array<!Int64>} values
+ */
+ writeRepeatedInt64(fieldNumber, values) {
+ values.forEach(val => this.writeInt64(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated int64 values to the buffer as packed varint.
+ * @param {number} fieldNumber
+ * @param {!Array<!Int64>} values
+ */
+ writePackedInt64(fieldNumber, values) {
+ this.writeVariablePacked_(
+ fieldNumber, values,
+ (writer, val) =>
+ writer.writeVarint64_(val.getHighBits(), val.getLowBits()));
+ }
+
+ /**
+ * Writes repeated sfixed32 values to the buffer as unpacked fixed32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writeRepeatedSfixed32(fieldNumber, values) {
+ values.forEach(val => this.writeSfixed32(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated sfixed32 values to the buffer as packed fixed32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writePackedSfixed32(fieldNumber, values) {
+ this.writeFixedPacked_(
+ fieldNumber, values, val => this.writeSfixed32Value_(val), 4);
+ }
+
+ /**
+ * Writes repeated sfixed64 values to the buffer as unpacked fixed64.
+ * @param {number} fieldNumber
+ * @param {!Array<!Int64>} values
+ */
+ writeRepeatedSfixed64(fieldNumber, values) {
+ values.forEach(val => this.writeSfixed64(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated sfixed64 values to the buffer as packed fixed64.
+ * @param {number} fieldNumber
+ * @param {!Array<!Int64>} values
+ */
+ writePackedSfixed64(fieldNumber, values) {
+ this.writeFixedPacked_(
+ fieldNumber, values, val => this.writeSfixed64Value_(val), 8);
+ }
+
+ /**
+ * Writes repeated sint32 values to the buffer as unpacked sint32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writeRepeatedSint32(fieldNumber, values) {
+ values.forEach(val => this.writeSint32(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated sint32 values to the buffer as packed sint32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writePackedSint32(fieldNumber, values) {
+ this.writeVariablePacked_(
+ fieldNumber, values, (writer, val) => writer.writeSint32Value_(val));
+ }
+
+ /**
+ * Writes repeated sint64 values to the buffer as unpacked varint.
+ * @param {number} fieldNumber
+ * @param {!Array<!Int64>} values
+ */
+ writeRepeatedSint64(fieldNumber, values) {
+ values.forEach(val => this.writeSint64(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated sint64 values to the buffer as packed varint.
+ * @param {number} fieldNumber
+ * @param {!Array<!Int64>} values
+ */
+ writePackedSint64(fieldNumber, values) {
+ this.writeVariablePacked_(
+ fieldNumber, values, (writer, val) => writer.writeSint64Value_(val));
+ }
+
+ /**
+ * Writes repeated uint32 values to the buffer as unpacked uint32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writeRepeatedUint32(fieldNumber, values) {
+ values.forEach(val => this.writeUint32(fieldNumber, val));
+ }
+
+ /**
+ * Writes repeated uint32 values to the buffer as packed uint32.
+ * @param {number} fieldNumber
+ * @param {!Array<number>} values
+ */
+ writePackedUint32(fieldNumber, values) {
+ this.writeVariablePacked_(
+ fieldNumber, values, (writer, val) => writer.writeUint32Value_(val));
+ }
+
+ /**
+ * Writes repeated bytes values to the buffer.
+ * @param {number} fieldNumber
+ * @param {!Array<!ByteString>} values
+ */
+ writeRepeatedBytes(fieldNumber, values) {
+ values.forEach(val => this.writeBytes(fieldNumber, val));
+ }
+
+ /**
+ * Writes packed fields with fixed length.
+ * @param {number} fieldNumber
+ * @param {!Array<T>} values
+ * @param {function(T)} valueWriter
+ * @param {number} entitySize
+ * @template T
+ * @private
+ */
+ writeFixedPacked_(fieldNumber, values, valueWriter, entitySize) {
+ if (values.length === 0) {
+ return;
+ }
+ this.writeTag(fieldNumber, WireType.DELIMITED);
+ this.writeUnsignedVarint32_(values.length * entitySize);
+ this.closeAndStartNewBuffer_();
+ values.forEach(value => valueWriter(value));
+ }
+
+ /**
+ * Writes packed fields with variable length.
+ * @param {number} fieldNumber
+ * @param {!Array<T>} values
+ * @param {function(!Writer, T)} valueWriter
+ * @template T
+ * @private
+ */
+ writeVariablePacked_(fieldNumber, values, valueWriter) {
+ if (values.length === 0) {
+ return;
+ }
+ const writer = new Writer();
+ values.forEach(val => valueWriter(writer, val));
+ const bytes = writer.getAndResetResultBuffer();
+ this.writeDelimited(fieldNumber, bytes);
+ }
+
+ /**
+ * Writes repeated string values to the buffer.
+ * @param {number} fieldNumber
+ * @param {!Array<string>} values
+ */
+ writeRepeatedString(fieldNumber, values) {
+ values.forEach(val => this.writeString(fieldNumber, val));
+ }
+}
+
+exports = Writer;
diff --git a/js/experimental/runtime/kernel/writer_test.js b/js/experimental/runtime/kernel/writer_test.js
new file mode 100644
index 0000000..019ae1e
--- /dev/null
+++ b/js/experimental/runtime/kernel/writer_test.js
@@ -0,0 +1,927 @@
+/**
+ * @fileoverview Tests for writer.js.
+ */
+goog.module('protobuf.binary.WriterTest');
+
+goog.setTestOnly();
+
+// Note to the reader:
+// Since the writer behavior changes with the checking level some of the tests
+// in this file have to know which checking level is enable to make correct
+// assertions.
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const ByteString = goog.require('protobuf.ByteString');
+const WireType = goog.require('protobuf.binary.WireType');
+const Writer = goog.require('protobuf.binary.Writer');
+const {CHECK_BOUNDS, CHECK_TYPE, MAX_FIELD_NUMBER} = goog.require('protobuf.internal.checks');
+const {arrayBufferSlice} = goog.require('protobuf.binary.typedArrays');
+const {getDoublePairs} = goog.require('protobuf.binary.doubleTestPairs');
+const {getFixed32Pairs} = goog.require('protobuf.binary.fixed32TestPairs');
+const {getFloatPairs} = goog.require('protobuf.binary.floatTestPairs');
+const {getInt32Pairs} = goog.require('protobuf.binary.int32TestPairs');
+const {getInt64Pairs} = goog.require('protobuf.binary.int64TestPairs');
+const {getPackedBoolPairs} = goog.require('protobuf.binary.packedBoolTestPairs');
+const {getPackedDoublePairs} = goog.require('protobuf.binary.packedDoubleTestPairs');
+const {getPackedFixed32Pairs} = goog.require('protobuf.binary.packedFixed32TestPairs');
+const {getPackedFloatPairs} = goog.require('protobuf.binary.packedFloatTestPairs');
+const {getPackedInt32Pairs} = goog.require('protobuf.binary.packedInt32TestPairs');
+const {getPackedInt64Pairs} = goog.require('protobuf.binary.packedInt64TestPairs');
+const {getPackedSfixed32Pairs} = goog.require('protobuf.binary.packedSfixed32TestPairs');
+const {getPackedSfixed64Pairs} = goog.require('protobuf.binary.packedSfixed64TestPairs');
+const {getPackedSint32Pairs} = goog.require('protobuf.binary.packedSint32TestPairs');
+const {getPackedSint64Pairs} = goog.require('protobuf.binary.packedSint64TestPairs');
+const {getPackedUint32Pairs} = goog.require('protobuf.binary.packedUint32TestPairs');
+const {getSfixed32Pairs} = goog.require('protobuf.binary.sfixed32TestPairs');
+const {getSfixed64Pairs} = goog.require('protobuf.binary.sfixed64TestPairs');
+const {getSint32Pairs} = goog.require('protobuf.binary.sint32TestPairs');
+const {getSint64Pairs} = goog.require('protobuf.binary.sint64TestPairs');
+const {getUint32Pairs} = goog.require('protobuf.binary.uint32TestPairs');
+
+
+/**
+ * @param {...number} bytes
+ * @return {!ArrayBuffer}
+ */
+function createArrayBuffer(...bytes) {
+ return new Uint8Array(bytes).buffer;
+}
+
+/******************************************************************************
+ * OPTIONAL FUNCTIONS
+ ******************************************************************************/
+
+describe('Writer does', () => {
+ it('return an empty ArrayBuffer when nothing is encoded', () => {
+ const writer = new Writer();
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ it('encode tag', () => {
+ const writer = new Writer();
+ writer.writeTag(1, WireType.VARINT);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer(0x08));
+
+ writer.writeTag(0x0FFFFFFF, WireType.VARINT);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(0xF8, 0xFF, 0xFF, 0xFF, 0x7));
+
+ writer.writeTag(0x10000000, WireType.VARINT);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(0x80, 0x80, 0x80, 0x80, 0x08));
+
+ writer.writeTag(0x1FFFFFFF, WireType.VARINT);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(0xF8, 0xFF, 0xFF, 0xFF, 0x0F));
+ });
+
+ it('reset after calling getAndResetResultBuffer', () => {
+ const writer = new Writer();
+ writer.writeTag(1, WireType.VARINT);
+ writer.getAndResetResultBuffer();
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ it('fail when field number is too large for writeTag', () => {
+ const writer = new Writer();
+ if (CHECK_TYPE) {
+ expect(() => writer.writeTag(MAX_FIELD_NUMBER + 1, WireType.VARINT))
+ .toThrowError('Field number is out of range: 536870912');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ writer.writeTag(MAX_FIELD_NUMBER + 1, WireType.VARINT);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer(0));
+ }
+ });
+
+ it('fail when field number is negative for writeTag', () => {
+ const writer = new Writer();
+ if (CHECK_TYPE) {
+ expect(() => writer.writeTag(-1, WireType.VARINT))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ writer.writeTag(-1, WireType.VARINT);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(0xF8, 0xFF, 0xFF, 0xFF, 0xF));
+ }
+ });
+
+ it('fail when wire type is invalid for writeTag', () => {
+ const writer = new Writer();
+ if (CHECK_TYPE) {
+ expect(() => writer.writeTag(1, /** @type {!WireType} */ (0x08)))
+ .toThrowError('Invalid wire type: 8');
+ } else {
+ // Note in unchecked mode we produce invalid output for invalid inputs.
+ // This test just documents our behavior in those cases.
+ // These values might change at any point and are not considered
+ // what the implementation should be doing here.
+ writer.writeTag(1, /** @type {!WireType} */ (0x08));
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer(0x08));
+ }
+ });
+
+ it('encode singular boolean value', () => {
+ const writer = new Writer();
+ writer.writeBool(1, true);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(0x08, 0x01));
+ });
+
+ it('encode length delimited', () => {
+ const writer = new Writer();
+ writer.writeDelimited(1, createArrayBuffer(0x01, 0x02));
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(0x0A, 0x02, 0x01, 0x02));
+ });
+});
+
+describe('Writer.writeBufferDecoder does', () => {
+ it('encode BufferDecoder containing a varint value', () => {
+ const writer = new Writer();
+ const expected = createArrayBuffer(
+ 0x08, /* varint start= */ 0xFF, /* varint end= */ 0x01, 0x08, 0x01);
+ writer.writeBufferDecoder(
+ BufferDecoder.fromArrayBuffer(expected), 1, WireType.VARINT, 1);
+ const result = writer.getAndResetResultBuffer();
+ expect(result).toEqual(arrayBufferSlice(expected, 1, 3));
+ });
+
+ it('encode BufferDecoder containing a fixed64 value', () => {
+ const writer = new Writer();
+ const expected = createArrayBuffer(
+ 0x09, /* fixed64 start= */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ /* fixed64 end= */ 0x08, 0x08, 0x01);
+ writer.writeBufferDecoder(
+ BufferDecoder.fromArrayBuffer(expected), 1, WireType.FIXED64, 1);
+ const result = writer.getAndResetResultBuffer();
+ expect(result).toEqual(arrayBufferSlice(expected, 1, 9));
+ });
+
+ it('encode BufferDecoder containing a length delimited value', () => {
+ const writer = new Writer();
+ const expected = createArrayBuffer(
+ 0xA, /* length= */ 0x03, /* data start= */ 0x01, 0x02,
+ /* data end= */ 0x03, 0x08, 0x01);
+ writer.writeBufferDecoder(
+ BufferDecoder.fromArrayBuffer(expected), 1, WireType.DELIMITED, 1);
+ const result = writer.getAndResetResultBuffer();
+ expect(result).toEqual(arrayBufferSlice(expected, 1, 5));
+ });
+
+ it('encode BufferDecoder containing a group', () => {
+ const writer = new Writer();
+ const expected = createArrayBuffer(
+ 0xB, /* group start= */ 0x08, 0x01, /* nested group start= */ 0x0B,
+ /* nested group end= */ 0x0C, /* group end= */ 0x0C, 0x08, 0x01);
+ writer.writeBufferDecoder(
+ BufferDecoder.fromArrayBuffer(expected), 1, WireType.START_GROUP, 1);
+ const result = writer.getAndResetResultBuffer();
+ expect(result).toEqual(arrayBufferSlice(expected, 1, 6));
+ });
+
+ it('encode BufferDecoder containing a fixed32 value', () => {
+ const writer = new Writer();
+ const expected = createArrayBuffer(
+ 0x09, /* fixed64 start= */ 0x01, 0x02, 0x03, /* fixed64 end= */ 0x04,
+ 0x08, 0x01);
+ writer.writeBufferDecoder(
+ BufferDecoder.fromArrayBuffer(expected), 1, WireType.FIXED32, 1);
+ const result = writer.getAndResetResultBuffer();
+ expect(result).toEqual(arrayBufferSlice(expected, 1, 5));
+ });
+
+ it('fail when encoding out of bound data', () => {
+ const writer = new Writer();
+ const buffer = createArrayBuffer(0x4, 0x0, 0x1, 0x2, 0x3);
+ const subBuffer = arrayBufferSlice(buffer, 0, 2);
+ expect(
+ () => writer.writeBufferDecoder(
+ BufferDecoder.fromArrayBuffer(subBuffer), 0, WireType.DELIMITED, 1))
+ .toThrow();
+ });
+});
+
+describe('Writer.writeBytes does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encodes empty ByteString', () => {
+ writer.writeBytes(1, ByteString.EMPTY);
+ const buffer = writer.getAndResetResultBuffer();
+ expect(buffer.byteLength).toBe(2);
+ });
+
+ it('encodes empty array', () => {
+ writer.writeBytes(1, ByteString.fromArrayBuffer(new ArrayBuffer(0)));
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 1 << 3 | 0x02, // tag (fieldnumber << 3 | (length delimited))
+ 0, // length of the bytes
+ ));
+ });
+
+ it('encodes ByteString', () => {
+ const array = createArrayBuffer(1, 2, 3);
+ writer.writeBytes(1, ByteString.fromArrayBuffer(array));
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 1 << 3 | 0x02, // tag (fieldnumber << 3 | (length delimited))
+ 3, // length of the bytes
+ 1,
+ 2,
+ 3,
+ ));
+ });
+});
+
+describe('Writer.writeDouble does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getDoublePairs()) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeDouble(1, pair.doubleValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ expect(buffer.length).toBe(9);
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x09);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, 9))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+
+ /**
+ * NaN may have different value in different browsers. Thus, we need to make
+ * the test lenient.
+ */
+ it('encode NaN', () => {
+ writer.writeDouble(1, NaN);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ expect(buffer.length).toBe(9);
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x09);
+ // Encoded values are stored right after the tag
+ const float64 = new DataView(buffer.buffer);
+ expect(float64.getFloat64(1, true)).toBeNaN();
+ });
+});
+
+describe('Writer.writeFixed32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getFixed32Pairs()) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeFixed32(1, pair.intValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ expect(buffer.length).toBe(5);
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0D);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, 5)).toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+});
+
+describe('Writer.writeFloat does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getFloatPairs()) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeFloat(1, pair.floatValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ expect(buffer.length).toBe(5);
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0D);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, 5)).toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+
+ /**
+ * NaN may have different value in different browsers. Thus, we need to make
+ * the test lenient.
+ */
+ it('encode NaN', () => {
+ writer.writeFloat(1, NaN);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ expect(buffer.length).toBe(5);
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0D);
+ // Encoded values are stored right after the tag
+ const float32 = new DataView(buffer.buffer);
+ expect(float32.getFloat32(1, true)).toBeNaN();
+ });
+});
+
+describe('Writer.writeInt32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getInt32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeInt32(1, pair.intValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x08);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writeSfixed32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedSfixed32(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getSfixed32Pairs()) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeSfixed32(1, pair.intValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ expect(buffer.length).toBe(5);
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0D);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, 5)).toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+});
+
+describe('Writer.writeSfixed64 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getSfixed64Pairs()) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeSfixed64(1, pair.longValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ expect(buffer.length).toBe(9);
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x09);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, 9)).toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+});
+
+describe('Writer.writeSint32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getSint32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeSint32(1, pair.intValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x08);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writeSint64 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getSint64Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeSint64(1, pair.longValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x08);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writeInt64 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getInt64Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeInt64(1, pair.longValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x08);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writeUint32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ for (const pair of getUint32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writeUint32(1, pair.intValue);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x08);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writeString does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty string', () => {
+ writer.writeString(1, '');
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 1 << 3 | 0x02, // tag (fieldnumber << 3 | (length delimited))
+ 0, // length of the string
+ ));
+ });
+
+ it('encode simple string', () => {
+ writer.writeString(1, 'hello');
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 1 << 3 | 0x02, // tag (fieldnumber << 3 | (length delimited))
+ 5, // length of the string
+ 'h'.charCodeAt(0),
+ 'e'.charCodeAt(0),
+ 'l'.charCodeAt(0),
+ 'l'.charCodeAt(0),
+ 'o'.charCodeAt(0),
+ ));
+ });
+
+ it('throw for invalid fieldnumber', () => {
+ if (CHECK_BOUNDS) {
+ expect(() => writer.writeString(-1, 'a'))
+ .toThrowError('Field number is out of range: -1');
+ } else {
+ writer.writeString(-1, 'a');
+ expect(new Uint8Array(writer.getAndResetResultBuffer()))
+ .toEqual(new Uint8Array(createArrayBuffer(
+ -6, // invalid tag
+ 0xff,
+ 0xff,
+ 0xff,
+ 0x0f,
+ 1, // string length
+ 'a'.charCodeAt(0),
+ )));
+ }
+ });
+
+ it('throw for null string value', () => {
+ expect(
+ () => writer.writeString(
+ 1, /** @type {string} */ (/** @type {*} */ (null))))
+ .toThrow();
+ });
+});
+
+
+/******************************************************************************
+ * REPEATED FUNCTIONS
+ ******************************************************************************/
+
+describe('Writer.writePackedBool does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedBool(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedBoolPairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedBool(1, pair.boolValues);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writeRepeatedBool does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writeRepeatedBool(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ it('encode repeated unpacked boolean values', () => {
+ const writer = new Writer();
+ writer.writeRepeatedBool(1, [true, false]);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 1 << 3 | 0x00, // tag (fieldnumber << 3 | (varint))
+ 0x01, // value[0]
+ 1 << 3 | 0x00, // tag (fieldnumber << 3 | (varint))
+ 0x00, // value[1]
+ ));
+ });
+});
+
+describe('Writer.writePackedDouble does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedDouble(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedDoublePairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedDouble(1, pair.doubleValues);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedFixed32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedFixed32(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedFixed32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedFixed32(1, pair.fixed32Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedFloat does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedFloat(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedFloatPairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedFloat(1, pair.floatValues);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedInt32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedInt32(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedInt32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedInt32(1, pair.int32Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedInt64 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedInt64(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedInt64Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedInt64(1, pair.int64Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedSfixed32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedSfixed32(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedSfixed32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedSfixed32(1, pair.sfixed32Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedSfixed64 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedSfixed64(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedSfixed64Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedSfixed64(1, pair.sfixed64Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedSint32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedSint32(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedSint32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedSint32(1, pair.sint32Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedSint64 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedSint64(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedSint64Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedSint64(1, pair.sint64Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writePackedUint32 does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writePackedUint32(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ for (const pair of getPackedUint32Pairs()) {
+ if (!pair.skip_writer) {
+ it(`encode ${pair.name}`, () => {
+ writer.writePackedUint32(1, pair.uint32Values);
+ const buffer = new Uint8Array(writer.getAndResetResultBuffer());
+ // ensure we have a correct tag
+ expect(buffer[0]).toEqual(0x0A);
+ // Encoded values are stored right after the tag
+ expect(buffer.subarray(1, buffer.length))
+ .toEqual(pair.bufferDecoder.asUint8Array());
+ });
+ }
+ }
+});
+
+describe('Writer.writeRepeatedBytes does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writeRepeatedBytes(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ it('encode single value', () => {
+ const value = createArrayBuffer(0x61);
+ writer.writeRepeatedBytes(1, [ByteString.fromArrayBuffer(value)]);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x61, // a
+ ));
+ });
+
+ it('encode multiple values', () => {
+ const value1 = createArrayBuffer(0x61);
+ const value2 = createArrayBuffer(0x62);
+ writer.writeRepeatedBytes(1, [
+ ByteString.fromArrayBuffer(value1),
+ ByteString.fromArrayBuffer(value2),
+ ]);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x61, // a
+ 0x0A,
+ 0x01,
+ 0x62, // b
+ ));
+ });
+});
+
+describe('Writer.writeRepeatedString does', () => {
+ let writer;
+ beforeEach(() => {
+ writer = new Writer();
+ });
+
+ it('encode empty array', () => {
+ writer.writeRepeatedString(1, []);
+ expect(writer.getAndResetResultBuffer()).toEqual(createArrayBuffer());
+ });
+
+ it('encode single value', () => {
+ writer.writeRepeatedString(1, ['a']);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x61, // a
+ ));
+ });
+
+ it('encode multiple values', () => {
+ writer.writeRepeatedString(1, ['a', 'b']);
+ expect(writer.getAndResetResultBuffer())
+ .toEqual(createArrayBuffer(
+ 0x0A,
+ 0x01,
+ 0x61, // a
+ 0x0A,
+ 0x01,
+ 0x62, // b
+ ));
+ });
+});
diff --git a/js/experimental/runtime/testing/binary/test_message.js b/js/experimental/runtime/testing/binary/test_message.js
new file mode 100644
index 0000000..cfd264b
--- /dev/null
+++ b/js/experimental/runtime/testing/binary/test_message.js
@@ -0,0 +1,1769 @@
+/**
+ * @fileoverview Kernel wrapper message.
+ */
+goog.module('protobuf.testing.binary.TestMessage');
+
+const ByteString = goog.require('protobuf.ByteString');
+const Int64 = goog.require('protobuf.Int64');
+const InternalMessage = goog.require('protobuf.binary.InternalMessage');
+const Kernel = goog.require('protobuf.runtime.Kernel');
+
+/**
+ * A protobuf message implemented as a Kernel wrapper.
+ * @implements {InternalMessage}
+ */
+class TestMessage {
+ /**
+ * @return {!TestMessage}
+ */
+ static createEmpty() {
+ return TestMessage.instanceCreator(Kernel.createEmpty());
+ }
+
+ /**
+ * @param {!Kernel} kernel
+ * @return {!TestMessage}
+ */
+ static instanceCreator(kernel) {
+ return new TestMessage(kernel);
+ }
+
+ /**
+ * @param {!Kernel} kernel
+ */
+ constructor(kernel) {
+ /** @private @const {!Kernel} */
+ this.kernel_ = kernel;
+ }
+
+ /**
+ * @override
+ * @return {!Kernel}
+ */
+ internalGetKernel() {
+ return this.kernel_;
+ }
+
+ /**
+ * @return {!ArrayBuffer}
+ */
+ serialize() {
+ return this.kernel_.serialize();
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {boolean=} defaultValue
+ * @return {boolean}
+ */
+ getBoolWithDefault(fieldNumber, defaultValue = false) {
+ return this.kernel_.getBoolWithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!ByteString=} defaultValue
+ * @return {!ByteString}
+ */
+ getBytesWithDefault(fieldNumber, defaultValue = ByteString.EMPTY) {
+ return this.kernel_.getBytesWithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getDoubleWithDefault(fieldNumber, defaultValue = 0) {
+ return this.kernel_.getDoubleWithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getFixed32WithDefault(fieldNumber, defaultValue = 0) {
+ return this.kernel_.getFixed32WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getFixed64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ return this.kernel_.getFixed64WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getFloatWithDefault(fieldNumber, defaultValue = 0) {
+ return this.kernel_.getFloatWithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getInt32WithDefault(fieldNumber, defaultValue = 0) {
+ return this.kernel_.getInt32WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getInt64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ return this.kernel_.getInt64WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getSfixed32WithDefault(fieldNumber, defaultValue = 0) {
+ return this.kernel_.getSfixed32WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getSfixed64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ return this.kernel_.getSfixed64WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getSint32WithDefault(fieldNumber, defaultValue = 0) {
+ return this.kernel_.getSint32WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getSint64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ return this.kernel_.getSint64WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {string=} defaultValue
+ * @return {string}
+ */
+ getStringWithDefault(fieldNumber, defaultValue = '') {
+ return this.kernel_.getStringWithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number=} defaultValue
+ * @return {number}
+ */
+ getUint32WithDefault(fieldNumber, defaultValue = 0) {
+ return this.kernel_.getUint32WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64=} defaultValue
+ * @return {!Int64}
+ */
+ getUint64WithDefault(fieldNumber, defaultValue = Int64.getZero()) {
+ return this.kernel_.getUint64WithDefault(fieldNumber, defaultValue);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @return {?T}
+ * @template T
+ */
+ getMessageOrNull(fieldNumber, instanceCreator) {
+ return this.kernel_.getMessageOrNull(fieldNumber, instanceCreator);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @return {T}
+ * @template T
+ */
+ getMessageAttach(fieldNumber, instanceCreator) {
+ return this.kernel_.getMessageAttach(fieldNumber, instanceCreator);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @return {T}
+ * @template T
+ */
+ getMessage(fieldNumber, instanceCreator) {
+ return this.kernel_.getMessage(fieldNumber, instanceCreator);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {?Kernel}
+ * @template T
+ */
+ getMessageAccessorOrNull(fieldNumber) {
+ return this.kernel_.getMessageAccessorOrNull(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {boolean}
+ */
+ getRepeatedBoolElement(fieldNumber, index) {
+ return this.kernel_.getRepeatedBoolElement(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<boolean>}
+ */
+ getRepeatedBoolIterable(fieldNumber) {
+ return this.kernel_.getRepeatedBoolIterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedBoolSize(fieldNumber) {
+ return this.kernel_.getRepeatedBoolSize(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedDoubleElement(fieldNumber, index) {
+ return this.kernel_.getRepeatedDoubleElement(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedDoubleIterable(fieldNumber) {
+ return this.kernel_.getRepeatedDoubleIterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedDoubleSize(fieldNumber) {
+ return this.kernel_.getRepeatedDoubleSize(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedFixed32Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedFixed32Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedFixed32Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedFixed32Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedFixed32Size(fieldNumber) {
+ return this.kernel_.getRepeatedFixed32Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedFixed64Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedFixed64Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedFixed64Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedFixed64Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedFixed64Size(fieldNumber) {
+ return this.kernel_.getRepeatedFixed64Size(fieldNumber);
+ }
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedFloatElement(fieldNumber, index) {
+ return this.kernel_.getRepeatedFloatElement(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedFloatIterable(fieldNumber) {
+ return this.kernel_.getRepeatedFloatIterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedFloatSize(fieldNumber) {
+ return this.kernel_.getRepeatedFloatSize(fieldNumber);
+ }
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedInt32Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedInt32Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedInt32Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedInt32Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedInt32Size(fieldNumber) {
+ return this.kernel_.getRepeatedInt32Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedInt64Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedInt64Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedInt64Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedInt64Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedInt64Size(fieldNumber) {
+ return this.kernel_.getRepeatedInt64Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedSfixed32Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedSfixed32Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedSfixed32Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedSfixed32Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSfixed32Size(fieldNumber) {
+ return this.kernel_.getRepeatedSfixed32Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedSfixed64Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedSfixed64Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedSfixed64Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedSfixed64Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSfixed64Size(fieldNumber) {
+ return this.kernel_.getRepeatedSfixed64Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedSint32Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedSint32Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedSint32Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedSint32Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSint32Size(fieldNumber) {
+ return this.kernel_.getRepeatedSint32Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedSint64Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedSint64Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedSint64Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedSint64Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedSint64Size(fieldNumber) {
+ return this.kernel_.getRepeatedSint64Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {number}
+ */
+ getRepeatedUint32Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedUint32Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<number>}
+ */
+ getRepeatedUint32Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedUint32Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedUint32Size(fieldNumber) {
+ return this.kernel_.getRepeatedUint32Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!Int64}
+ */
+ getRepeatedUint64Element(fieldNumber, index) {
+ return this.kernel_.getRepeatedUint64Element(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Int64>}
+ */
+ getRepeatedUint64Iterable(fieldNumber) {
+ return this.kernel_.getRepeatedUint64Iterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedUint64Size(fieldNumber) {
+ return this.kernel_.getRepeatedUint64Size(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {!ByteString}
+ */
+ getRepeatedBytesElement(fieldNumber, index) {
+ return this.kernel_.getRepeatedBytesElement(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<!ByteString>}
+ */
+ getRepeatedBytesIterable(fieldNumber) {
+ return this.kernel_.getRepeatedBytesIterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedBytesSize(fieldNumber) {
+ return this.kernel_.getRepeatedBytesSize(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @return {string}
+ */
+ getRepeatedStringElement(fieldNumber, index) {
+ return this.kernel_.getRepeatedStringElement(fieldNumber, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<string>}
+ */
+ getRepeatedStringIterable(fieldNumber) {
+ return this.kernel_.getRepeatedStringIterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {number}
+ */
+ getRepeatedStringSize(fieldNumber) {
+ return this.kernel_.getRepeatedStringSize(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number} index
+ * @return {T}
+ * @template T
+ */
+ getRepeatedMessageElement(fieldNumber, instanceCreator, index) {
+ return this.kernel_.getRepeatedMessageElement(
+ fieldNumber, instanceCreator, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @return {!Iterable<T>}
+ * @template T
+ */
+ getRepeatedMessageIterable(fieldNumber, instanceCreator) {
+ return this.kernel_.getRepeatedMessageIterable(
+ fieldNumber, instanceCreator);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @return {!Iterable<!Kernel>}
+ * @template T
+ */
+ getRepeatedMessageAccessorIterable(fieldNumber) {
+ return this.kernel_.getRepeatedMessageAccessorIterable(fieldNumber);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {function(!Kernel):T} instanceCreator
+ * @return {number}
+ * @template T
+ */
+ getRepeatedMessageSize(fieldNumber, instanceCreator) {
+ return this.kernel_.getRepeatedMessageSize(fieldNumber, instanceCreator);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {boolean} value
+ */
+ setBool(fieldNumber, value) {
+ this.kernel_.setBool(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!ByteString} value
+ */
+ setBytes(fieldNumber, value) {
+ this.kernel_.setBytes(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setDouble(fieldNumber, value) {
+ this.kernel_.setDouble(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setFixed32(fieldNumber, value) {
+ this.kernel_.setFixed32(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setFixed64(fieldNumber, value) {
+ this.kernel_.setFixed64(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setFloat(fieldNumber, value) {
+ this.kernel_.setFloat(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setInt32(fieldNumber, value) {
+ this.kernel_.setInt32(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setInt64(fieldNumber, value) {
+ this.kernel_.setInt64(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setSfixed32(fieldNumber, value) {
+ this.kernel_.setSfixed32(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setSfixed64(fieldNumber, value) {
+ this.kernel_.setSfixed64(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setSint32(fieldNumber, value) {
+ this.kernel_.setSint32(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setSint64(fieldNumber, value) {
+ this.kernel_.setSint64(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {string} value
+ */
+ setString(fieldNumber, value) {
+ this.kernel_.setString(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ setUint32(fieldNumber, value) {
+ this.kernel_.setUint32(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ setUint64(fieldNumber, value) {
+ this.kernel_.setUint64(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {T} value
+ * @template T
+ */
+ setMessage(fieldNumber, value) {
+ this.kernel_.setMessage(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {boolean} value
+ */
+ addPackedBoolElement(fieldNumber, value) {
+ this.kernel_.addPackedBoolElement(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ addPackedBoolIterable(fieldNumber, values) {
+ this.kernel_.addPackedBoolIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {boolean} value
+ */
+ addUnpackedBoolElement(fieldNumber, value) {
+ this.kernel_.addUnpackedBoolElement(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ addUnpackedBoolIterable(fieldNumber, values) {
+ this.kernel_.addUnpackedBoolIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {boolean} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedBoolElement(fieldNumber, index, value) {
+ this.kernel_.setPackedBoolElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ setPackedBoolIterable(fieldNumber, values) {
+ this.kernel_.setPackedBoolIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {boolean} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedBoolElement(fieldNumber, index, value) {
+ this.kernel_.setUnpackedBoolElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<boolean>} values
+ */
+ setUnpackedBoolIterable(fieldNumber, values) {
+ this.kernel_.setUnpackedBoolIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedDoubleElement(fieldNumber, value) {
+ this.kernel_.addPackedDoubleElement(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedDoubleIterable(fieldNumber, values) {
+ this.kernel_.addPackedDoubleIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedDoubleElement(fieldNumber, value) {
+ this.kernel_.addUnpackedDoubleElement(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedDoubleIterable(fieldNumber, values) {
+ this.kernel_.addUnpackedDoubleIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedDoubleElement(fieldNumber, index, value) {
+ this.kernel_.setPackedDoubleElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedDoubleIterable(fieldNumber, values) {
+ this.kernel_.setPackedDoubleIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedDoubleElement(fieldNumber, index, value) {
+ this.kernel_.setUnpackedDoubleElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedDoubleIterable(fieldNumber, values) {
+ this.kernel_.setUnpackedDoubleIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedFixed32Element(fieldNumber, value) {
+ this.kernel_.addPackedFixed32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedFixed32Iterable(fieldNumber, values) {
+ this.kernel_.addPackedFixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedFixed32Element(fieldNumber, value) {
+ this.kernel_.addUnpackedFixed32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedFixed32Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedFixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedFixed32Element(fieldNumber, index, value) {
+ this.kernel_.setPackedFixed32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedFixed32Iterable(fieldNumber, values) {
+ this.kernel_.setPackedFixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedFixed32Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedFixed32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedFixed32Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedFixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedFixed64Element(fieldNumber, value) {
+ this.kernel_.addPackedFixed64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedFixed64Iterable(fieldNumber, values) {
+ this.kernel_.addPackedFixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedFixed64Element(fieldNumber, value) {
+ this.kernel_.addUnpackedFixed64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedFixed64Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedFixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedFixed64Element(fieldNumber, index, value) {
+ this.kernel_.setPackedFixed64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedFixed64Iterable(fieldNumber, values) {
+ this.kernel_.setPackedFixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedFixed64Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedFixed64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedFixed64Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedFixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedFloatElement(fieldNumber, value) {
+ this.kernel_.addPackedFloatElement(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedFloatIterable(fieldNumber, values) {
+ this.kernel_.addPackedFloatIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedFloatElement(fieldNumber, value) {
+ this.kernel_.addUnpackedFloatElement(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedFloatIterable(fieldNumber, values) {
+ this.kernel_.addUnpackedFloatIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedFloatElement(fieldNumber, index, value) {
+ this.kernel_.setPackedFloatElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedFloatIterable(fieldNumber, values) {
+ this.kernel_.setPackedFloatIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedFloatElement(fieldNumber, index, value) {
+ this.kernel_.setUnpackedFloatElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedFloatIterable(fieldNumber, values) {
+ this.kernel_.setUnpackedFloatIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedInt32Element(fieldNumber, value) {
+ this.kernel_.addPackedInt32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedInt32Iterable(fieldNumber, values) {
+ this.kernel_.addPackedInt32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedInt32Element(fieldNumber, value) {
+ this.kernel_.addUnpackedInt32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedInt32Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedInt32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedInt32Element(fieldNumber, index, value) {
+ this.kernel_.setPackedInt32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedInt32Iterable(fieldNumber, values) {
+ this.kernel_.setPackedInt32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedInt32Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedInt32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedInt32Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedInt32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedInt64Element(fieldNumber, value) {
+ this.kernel_.addPackedInt64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedInt64Iterable(fieldNumber, values) {
+ this.kernel_.addPackedInt64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedInt64Element(fieldNumber, value) {
+ this.kernel_.addUnpackedInt64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedInt64Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedInt64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedInt64Element(fieldNumber, index, value) {
+ this.kernel_.setPackedInt64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedInt64Iterable(fieldNumber, values) {
+ this.kernel_.setPackedInt64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedInt64Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedInt64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedInt64Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedInt64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedSfixed32Element(fieldNumber, value) {
+ this.kernel_.addPackedSfixed32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedSfixed32Iterable(fieldNumber, values) {
+ this.kernel_.addPackedSfixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedSfixed32Element(fieldNumber, value) {
+ this.kernel_.addUnpackedSfixed32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedSfixed32Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedSfixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSfixed32Element(fieldNumber, index, value) {
+ this.kernel_.setPackedSfixed32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedSfixed32Iterable(fieldNumber, values) {
+ this.kernel_.setPackedSfixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSfixed32Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedSfixed32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedSfixed32Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedSfixed32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedSfixed64Element(fieldNumber, value) {
+ this.kernel_.addPackedSfixed64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedSfixed64Iterable(fieldNumber, values) {
+ this.kernel_.addPackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedSfixed64Element(fieldNumber, value) {
+ this.kernel_.addUnpackedSfixed64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedSfixed64Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSfixed64Element(fieldNumber, index, value) {
+ this.kernel_.setPackedSfixed64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedSfixed64Iterable(fieldNumber, values) {
+ this.kernel_.setPackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSfixed64Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedSfixed64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedSfixed64Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedSfixed64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedSint32Element(fieldNumber, value) {
+ this.kernel_.addPackedSint32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedSint32Iterable(fieldNumber, values) {
+ this.kernel_.addPackedSint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedSint32Element(fieldNumber, value) {
+ this.kernel_.addUnpackedSint32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedSint32Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedSint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSint32Element(fieldNumber, index, value) {
+ this.kernel_.setPackedSint32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedSint32Iterable(fieldNumber, values) {
+ this.kernel_.setPackedSint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSint32Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedSint32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedSint32Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedSint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedSint64Element(fieldNumber, value) {
+ this.kernel_.addPackedSint64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedSint64Iterable(fieldNumber, values) {
+ this.kernel_.addPackedSint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedSint64Element(fieldNumber, value) {
+ this.kernel_.addUnpackedSint64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedSint64Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedSint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedSint64Element(fieldNumber, index, value) {
+ this.kernel_.setPackedSint64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedSint64Iterable(fieldNumber, values) {
+ this.kernel_.setPackedSint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedSint64Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedSint64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedSint64Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedSint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addPackedUint32Element(fieldNumber, value) {
+ this.kernel_.addPackedUint32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addPackedUint32Iterable(fieldNumber, values) {
+ this.kernel_.addPackedUint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} value
+ */
+ addUnpackedUint32Element(fieldNumber, value) {
+ this.kernel_.addUnpackedUint32Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ addUnpackedUint32Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedUint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedUint32Element(fieldNumber, index, value) {
+ this.kernel_.setPackedUint32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setPackedUint32Iterable(fieldNumber, values) {
+ this.kernel_.setPackedUint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {number} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedUint32Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedUint32Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<number>} values
+ */
+ setUnpackedUint32Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedUint32Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addPackedUint64Element(fieldNumber, value) {
+ this.kernel_.addPackedUint64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addPackedUint64Iterable(fieldNumber, values) {
+ this.kernel_.addPackedUint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Int64} value
+ */
+ addUnpackedUint64Element(fieldNumber, value) {
+ this.kernel_.addUnpackedUint64Element(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ addUnpackedUint64Iterable(fieldNumber, values) {
+ this.kernel_.addUnpackedUint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setPackedUint64Element(fieldNumber, index, value) {
+ this.kernel_.setPackedUint64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setPackedUint64Iterable(fieldNumber, values) {
+ this.kernel_.setPackedUint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!Int64} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setUnpackedUint64Element(fieldNumber, index, value) {
+ this.kernel_.setUnpackedUint64Element(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!Int64>} values
+ */
+ setUnpackedUint64Iterable(fieldNumber, values) {
+ this.kernel_.setUnpackedUint64Iterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!ByteString>} values
+ */
+ setRepeatedBytesIterable(fieldNumber, values) {
+ this.kernel_.setRepeatedBytesIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<!ByteString>} values
+ */
+ addRepeatedBytesIterable(fieldNumber, values) {
+ this.kernel_.addRepeatedBytesIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {!ByteString} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setRepeatedBytesElement(fieldNumber, index, value) {
+ this.kernel_.setRepeatedBytesElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!ByteString} value
+ */
+ addRepeatedBytesElement(fieldNumber, value) {
+ this.kernel_.addRepeatedBytesElement(fieldNumber, value);
+ }
+
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<string>} values
+ */
+ setRepeatedStringIterable(fieldNumber, values) {
+ this.kernel_.setRepeatedStringIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<string>} values
+ */
+ addRepeatedStringIterable(fieldNumber, values) {
+ this.kernel_.addRepeatedStringIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {number} index
+ * @param {string} value
+ * @throws {!Error} if index is out of range when check mode is critical
+ */
+ setRepeatedStringElement(fieldNumber, index, value) {
+ this.kernel_.setRepeatedStringElement(fieldNumber, index, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {string} value
+ */
+ addRepeatedStringElement(fieldNumber, value) {
+ this.kernel_.addRepeatedStringElement(fieldNumber, value);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<T>} values
+ * @template T
+ */
+ setRepeatedMessageIterable(fieldNumber, values) {
+ this.kernel_.setRepeatedMessageIterable(fieldNumber, values);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {!Iterable<T>} values
+ * @param {function(!Kernel):T} instanceCreator
+ * @template T
+ */
+ addRepeatedMessageIterable(fieldNumber, values, instanceCreator) {
+ this.kernel_.addRepeatedMessageIterable(
+ fieldNumber, values, instanceCreator);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {T} value
+ * @param {function(!Kernel):T} instanceCreator
+ * @param {number} index
+ * @throws {!Error} if index is out of range when check mode is critical
+ * @template T
+ */
+ setRepeatedMessageElement(fieldNumber, value, instanceCreator, index) {
+ this.kernel_.setRepeatedMessageElement(
+ fieldNumber, value, instanceCreator, index);
+ }
+
+ /**
+ * @param {number} fieldNumber
+ * @param {T} value
+ * @param {function(!Kernel):T} instanceCreator
+ * @template T
+ */
+ addRepeatedMessageElement(fieldNumber, value, instanceCreator) {
+ this.kernel_.addRepeatedMessageElement(fieldNumber, value, instanceCreator);
+ }
+}
+
+exports = TestMessage;
diff --git a/js/experimental/runtime/testing/ensure_custom_equality_test.js b/js/experimental/runtime/testing/ensure_custom_equality_test.js
new file mode 100644
index 0000000..9323ffd
--- /dev/null
+++ b/js/experimental/runtime/testing/ensure_custom_equality_test.js
@@ -0,0 +1,44 @@
+/**
+ * @fileoverview Tests in this file will fail if our custom equality have not
+ * been installed.
+ * see b/131864652
+ */
+
+goog.module('protobuf.testing.ensureCustomEqualityTest');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const ByteString = goog.require('protobuf.ByteString');
+
+describe('Custom equality', () => {
+ it('ensure that custom equality for ArrayBuffer is installed', () => {
+ const buffer1 = new ArrayBuffer(4);
+ const buffer2 = new ArrayBuffer(4);
+ const array = new Uint8Array(buffer1);
+ array[0] = 1;
+ expect(buffer1).not.toEqual(buffer2);
+ });
+
+ it('ensure that custom equality for ByteString is installed', () => {
+ const HALLO_IN_BASE64 = 'aGFsbG8=';
+ const BYTES_WITH_HALLO = new Uint8Array([
+ 'h'.charCodeAt(0),
+ 'a'.charCodeAt(0),
+ 'l'.charCodeAt(0),
+ 'l'.charCodeAt(0),
+ 'o'.charCodeAt(0),
+ ]);
+
+ const byteString1 = ByteString.fromBase64String(HALLO_IN_BASE64);
+ const byteString2 = ByteString.fromArrayBufferView(BYTES_WITH_HALLO);
+ expect(byteString1).toEqual(byteString2);
+ });
+
+ it('ensure that custom equality for BufferDecoder is installed', () => {
+ const arrayBuffer1 = new Uint8Array([0, 1, 2]).buffer;
+ const arrayBuffer2 = new Uint8Array([0, 1, 2]).buffer;
+
+ const bufferDecoder1 = BufferDecoder.fromArrayBuffer(arrayBuffer1);
+ const bufferDecoder2 = BufferDecoder.fromArrayBuffer(arrayBuffer2);
+ expect(bufferDecoder1).toEqual(bufferDecoder2);
+ });
+});
diff --git a/js/experimental/runtime/testing/jasmine_protobuf.js b/js/experimental/runtime/testing/jasmine_protobuf.js
new file mode 100644
index 0000000..d6bc0ff
--- /dev/null
+++ b/js/experimental/runtime/testing/jasmine_protobuf.js
@@ -0,0 +1,88 @@
+/**
+ * @fileoverview Installs our custom equality matchers in Jasmine.
+ */
+goog.module('protobuf.testing.jasmineProtoBuf');
+
+const BufferDecoder = goog.require('protobuf.binary.BufferDecoder');
+const ByteString = goog.require('protobuf.ByteString');
+const {arrayBufferEqual} = goog.require('protobuf.binary.typedArrays');
+
+/**
+ * A function that ensures custom equality for ByteStrings.
+ * Since Jasmine compare structure by default Bytestrings might be equal that
+ * are not equal since ArrayBuffers still compare content in g3.
+ * (Jasmine fix upstream: https://github.com/jasmine/jasmine/issues/1687)
+ * Also ByteStrings that are equal might compare non equal in jasmine of the
+ * base64 string has been initialized.
+ * @param {*} first
+ * @param {*} second
+ * @return {boolean|undefined}
+ */
+const byteStringEquality = (first, second) => {
+ if (second instanceof ByteString) {
+ return second.equals(first);
+ }
+
+ // Intentionally not returning anything, this signals to jasmine that we
+ // did not perform any equality on the given objects.
+};
+
+/**
+ * A function that ensures custom equality for ArrayBuffers.
+ * By default Jasmine does not compare the content of an ArrayBuffer and thus
+ * will return true for buffers with the same length but different content.
+ * @param {*} first
+ * @param {*} second
+ * @return {boolean|undefined}
+ */
+const arrayBufferCustomEquality = (first, second) => {
+ if (first instanceof ArrayBuffer && second instanceof ArrayBuffer) {
+ return arrayBufferEqual(first, second);
+ }
+ // Intentionally not returning anything, this signals to jasmine that we
+ // did not perform any equality on the given objects.
+};
+
+/**
+ * A function that ensures custom equality for ArrayBuffers.
+ * By default Jasmine does not compare the content of an ArrayBuffer and thus
+ * will return true for buffers with the same length but different content.
+ * @param {*} first
+ * @param {*} second
+ * @return {boolean|undefined}
+ */
+const bufferDecoderCustomEquality = (first, second) => {
+ if (first instanceof BufferDecoder && second instanceof BufferDecoder) {
+ return first.asByteString().equals(second.asByteString());
+ }
+ // Intentionally not returning anything, this signals to jasmine that we
+ // did not perform any equality on the given objects.
+};
+
+/**
+ * Overrides the default ArrayBuffer toString method ([object ArrayBuffer]) with
+ * a more readable representation.
+ */
+function overrideArrayBufferToString() {
+ /**
+ * Returns the hex values of the underlying bytes of the ArrayBuffer.
+ *
+ * @override
+ * @return {string}
+ */
+ ArrayBuffer.prototype.toString = function() {
+ const arr = Array.from(new Uint8Array(this));
+ return 'ArrayBuffer[' +
+ arr.map((b) => '0x' + (b & 0xFF).toString(16).toUpperCase())
+ .join(', ') +
+ ']';
+ };
+}
+
+beforeEach(() => {
+ jasmine.addCustomEqualityTester(arrayBufferCustomEquality);
+ jasmine.addCustomEqualityTester(bufferDecoderCustomEquality);
+ jasmine.addCustomEqualityTester(byteStringEquality);
+
+ overrideArrayBufferToString();
+});
diff --git a/js/gulpfile.js b/js/gulpfile.js
index 1f0946c..a81c011 100644
--- a/js/gulpfile.js
+++ b/js/gulpfile.js
@@ -37,6 +37,7 @@
'testbinary.proto',
'testempty.proto',
'test.proto',
+ 'testlargenumbers.proto',
];
var group2Protos = [
diff --git a/js/maps_test.js b/js/maps_test.js
old mode 100755
new mode 100644
diff --git a/js/message.js b/js/message.js
index 4bf0378..c1736b3 100644
--- a/js/message.js
+++ b/js/message.js
@@ -317,7 +317,7 @@
return fieldNumber + msg.arrayIndexOffset_;
};
-// This is only here to ensure we are not back sliding on ES6 requiements for
+// This is only here to ensure we are not back sliding on ES6 requirements for
// protos in g3.
jspb.Message.hiddenES6Property_ = class {};
@@ -366,7 +366,7 @@
if (!jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS) {
// TODO(jakubvrana): This is same for all instances, move to prototype.
- // TODO(jakubvrana): There are indexOf calls on this in serializtion,
+ // TODO(jakubvrana): There are indexOf calls on this in serialization,
// consider switching to a set.
msg.repeatedFields = repeatedFields;
}
@@ -1112,8 +1112,11 @@
goog.asserts.assertInstanceof(msg, jspb.Message);
if (value !== defaultValue) {
jspb.Message.setField(msg, fieldNumber, value);
- } else {
+ } else if (fieldNumber < msg.pivot_) {
msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = null;
+ } else {
+ jspb.Message.maybeInitEmptyExtensionObject_(msg);
+ delete msg.extensionObject_[fieldNumber];
}
return msg;
};
@@ -1860,7 +1863,7 @@
* @param {Function} constructor The message constructor.
*/
jspb.Message.registerMessageType = function(id, constructor) {
- // This is needed so we can later access messageId directly on the contructor,
+ // This is needed so we can later access messageId directly on the constructor,
// otherwise it is not available due to 'property collapsing' by the compiler.
/**
* @suppress {strictMissingProperties} messageId is not defined on Function
diff --git a/js/message_test.js b/js/message_test.js
index e038f65..3db8716 100644
--- a/js/message_test.js
+++ b/js/message_test.js
@@ -118,6 +118,8 @@
goog.require('proto.jspb.test.TestExtensionsMessage');
goog.require('proto.jspb.test.TestAllowAliasEnum');
+// CommonJS-LoadFromFile: testlargenumbers_pb proto.jspb.test
+goog.require('proto.jspb.test.MessageWithLargeFieldNumbers');
describe('Message test suite', function() {
var stubs = new goog.testing.PropertyReplacer();
@@ -1075,4 +1077,36 @@
assertEquals(12, package2Message.getA());
});
+
+ it('testMessageWithLargeFieldNumbers', function() {
+ var message = new proto.jspb.test.MessageWithLargeFieldNumbers;
+
+ message.setAString('string');
+ assertEquals('string', message.getAString());
+
+ message.setAString('');
+ assertEquals('', message.getAString());
+
+ message.setAString('new string');
+ assertEquals('new string', message.getAString());
+
+ message.setABoolean(true);
+ assertEquals(true, message.getABoolean());
+
+ message.setABoolean(false);
+ assertEquals(false, message.getABoolean());
+
+ message.setABoolean(true);
+ assertEquals(true, message.getABoolean());
+
+ message.setAInt(42);
+ assertEquals(42, message.getAInt());
+
+ message.setAInt(0);
+ assertEquals(0, message.getAInt());
+
+ message.setAInt(42);
+ assertEquals(42, message.getAInt());
+ });
+
});
diff --git a/js/package.json b/js/package.json
index 2cfba39..0b2adb8 100644
--- a/js/package.json
+++ b/js/package.json
@@ -1,6 +1,6 @@
{
"name": "google-protobuf",
- "version": "3.11.0-rc.1",
+ "version": "3.12.0-rc.2",
"description": "Protocol Buffers for JavaScript",
"main": "google-protobuf.js",
"files": [
diff --git a/js/testlargenumbers.proto b/js/testlargenumbers.proto
new file mode 100644
index 0000000..47aef35
--- /dev/null
+++ b/js/testlargenumbers.proto
@@ -0,0 +1,40 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+syntax = "proto3";
+
+package jspb.test;
+
+
+message MessageWithLargeFieldNumbers {
+ string a_string = 1;
+ bool a_boolean = 900;
+ int32 a_int = 5000;
+}
diff --git a/kokoro/docs/common.cfg b/kokoro/docs/common.cfg
new file mode 100644
index 0000000..771ca7f
--- /dev/null
+++ b/kokoro/docs/common.cfg
@@ -0,0 +1,44 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "protobuf/kokoro/docs/trampoline.sh"
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-multi"
+}
+
+env_vars: {
+ key: "STAGING_BUCKET"
+ value: "docs-staging"
+}
+
+# Fetch the token needed for reporting release status to GitHub
+before_action {
+ fetch_keystore {
+ keystore_resource {
+ keystore_config_id: 73713
+ keyname: "yoshi-automation-github-key"
+ }
+ }
+}
+
+before_action {
+ fetch_keystore {
+ keystore_resource {
+ keystore_config_id: 73713
+ keyname: "docuploader_service_account"
+ }
+ }
+}
diff --git a/kokoro/docs/publish-python.sh b/kokoro/docs/publish-python.sh
new file mode 100755
index 0000000..eea1755
--- /dev/null
+++ b/kokoro/docs/publish-python.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+# Adapted from https://github.com/googleapis/google-cloud-python/blob/master/.kokoro/publish-docs.sh
+
+set -eo pipefail
+
+# Disable buffering, so that the logs stream through.
+export PYTHONUNBUFFERED=1
+
+cd github/protobuf/python
+
+# install package
+sudo apt-get update
+sudo apt-get -y install software-properties-common
+sudo add-apt-repository universe
+sudo apt-get update
+sudo apt-get -y install unzip
+wget https://github.com/protocolbuffers/protobuf/releases/download/v3.11.2/protoc-3.11.2-linux-x86_64.zip
+unzip protoc-3.11.2-linux-x86_64.zip bin/protoc
+mv bin/protoc ../src/protoc
+python3.6 -m venv venv
+source venv/bin/activate
+python setup.py install
+
+# install docs dependencies
+python -m pip install -r docs/requirements.txt
+
+# build docs
+cd docs
+make html
+cd ..
+deactivate
+
+python3.6 -m pip install protobuf==3.11.1 gcp-docuploader
+
+# install a json parser
+sudo apt-get -y install jq
+
+# create metadata
+python3.6 -m docuploader create-metadata \
+ --name=$(jq --raw-output '.name // empty' .repo-metadata.json) \
+ --version=$(python3 setup.py --version) \
+ --language=$(jq --raw-output '.language // empty' .repo-metadata.json) \
+ --distribution-name=$(python3 setup.py --name) \
+ --product-page=$(jq --raw-output '.product_documentation // empty' .repo-metadata.json) \
+ --github-repository=$(jq --raw-output '.repo // empty' .repo-metadata.json) \
+ --issue-tracker=$(jq --raw-output '.issue_tracker // empty' .repo-metadata.json)
+
+cat docs.metadata
+
+# upload docs
+python3.6 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket docs-staging
diff --git a/kokoro/docs/python.cfg b/kokoro/docs/python.cfg
new file mode 100644
index 0000000..382f431
--- /dev/null
+++ b/kokoro/docs/python.cfg
@@ -0,0 +1,7 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Tell the trampoline which build file to use.
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/protobuf/kokoro/docs/publish-python.sh"
+}
diff --git a/kokoro/docs/trampoline.sh b/kokoro/docs/trampoline.sh
new file mode 100755
index 0000000..db7e90b
--- /dev/null
+++ b/kokoro/docs/trampoline.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+# Copied from https://github.com/googleapis/google-cloud-python/blob/master/.kokoro/trampoline.sh
+
+set -eo pipefail
+
+python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" || ret_code=$?
+
+chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh
+${KOKORO_GFILE_DIR}/trampoline_cleanup.sh || true
+
+exit ${ret_code}
diff --git a/kokoro/linux/bazel/build.sh b/kokoro/linux/bazel/build.sh
index b99b4d3..9355eba 100755
--- a/kokoro/linux/bazel/build.sh
+++ b/kokoro/linux/bazel/build.sh
@@ -23,8 +23,12 @@
git submodule update --init --recursive
trap print_test_logs EXIT
-bazel test :build_files_updated_unittest :protobuf_test --copt=-Werror --host_copt=-Werror
+bazel test --copt=-Werror --host_copt=-Werror \
+ //:build_files_updated_unittest \
+ //java/... \
+ //:protobuf_test \
+ @com_google_protobuf//:cc_proto_blacklist_test
trap - EXIT
cd examples
-bazel build :all
+bazel build //...
diff --git a/kokoro/linux/benchmark/build.sh b/kokoro/linux/benchmark/build.sh
old mode 100644
new mode 100755
diff --git a/kokoro/linux/benchmark/continuous.cfg b/kokoro/linux/benchmark/continuous.cfg
old mode 100755
new mode 100644
diff --git a/kokoro/linux/build_and_run_docker.sh b/kokoro/linux/build_and_run_docker.sh
index 3dc5dbb..cdbd6e2 100755
--- a/kokoro/linux/build_and_run_docker.sh
+++ b/kokoro/linux/build_and_run_docker.sh
@@ -28,8 +28,9 @@
DOCKER_IMAGE_NAME=${DOCKERHUB_ORGANIZATION}/${DOCKERFILE_PREFIX}_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ )
fi
-# Pull dockerimage from Dockerhub
-docker pull $DOCKER_IMAGE_NAME
+# Pull dockerimage from Dockerhub. This sometimes fails intermittently, so we
+# keep trying until we succeed.
+until docker pull $DOCKER_IMAGE_NAME; do sleep 10; done
# Ensure existence of ccache directory
CCACHE_DIR=/tmp/protobuf-ccache
diff --git a/kokoro/linux/cpp_distcheck/build.sh b/kokoro/linux/cpp_distcheck/build.sh
index 1343a8c..42ac88c 100755
--- a/kokoro/linux/cpp_distcheck/build.sh
+++ b/kokoro/linux/cpp_distcheck/build.sh
@@ -11,7 +11,7 @@
# Run tests under release docker image.
DOCKER_IMAGE_NAME=protobuf/protoc_$(sha1sum protoc-artifacts/Dockerfile | cut -f1 -d " ")
-docker pull $DOCKER_IMAGE_NAME
+until docker pull $DOCKER_IMAGE_NAME; do sleep 10; done
docker run -v $(pwd):/var/local/protobuf --rm $DOCKER_IMAGE_NAME \
bash -l /var/local/protobuf/tests.sh cpp || FAILED="true"
diff --git a/kokoro/linux/dockerfile/push_testing_images.sh b/kokoro/linux/dockerfile/push_testing_images.sh
index 9a2983c..2d82bab 100755
--- a/kokoro/linux/dockerfile/push_testing_images.sh
+++ b/kokoro/linux/dockerfile/push_testing_images.sh
@@ -8,7 +8,7 @@
DOCKERHUB_ORGANIZATION=protobuftesting
-for DOCKERFILE_DIR in test/* release/*
+for DOCKERFILE_DIR in test/*
do
# Generate image name based on Dockerfile checksum. That works well as long
# as can count on dockerfiles being written in a way that changing the logical
diff --git a/kokoro/linux/dockerfile/release/ruby_rake_compiler/Dockerfile b/kokoro/linux/dockerfile/release/ruby_rake_compiler/Dockerfile
deleted file mode 100644
index 866b289..0000000
--- a/kokoro/linux/dockerfile/release/ruby_rake_compiler/Dockerfile
+++ /dev/null
@@ -1,3 +0,0 @@
-FROM grpctesting/rake-compiler-dock_53c22085d091183c528303791e7771359f699bcf
-
-RUN /bin/bash -l -c "gem update --system '2.7.9' && gem install bundler"
diff --git a/kokoro/linux/dockerfile/test/csharp/Dockerfile b/kokoro/linux/dockerfile/test/csharp/Dockerfile
index 2073057..3d54436 100644
--- a/kokoro/linux/dockerfile/test/csharp/Dockerfile
+++ b/kokoro/linux/dockerfile/test/csharp/Dockerfile
@@ -28,7 +28,8 @@
# Install dotnet SDK via install script
RUN wget -q https://dot.net/v1/dotnet-install.sh && \
chmod u+x dotnet-install.sh && \
- ./dotnet-install.sh --version 2.1.504 && \
+ ./dotnet-install.sh --version 2.1.802 && \
+ ./dotnet-install.sh --version 3.0.100 && \
ln -s /root/.dotnet/dotnet /usr/local/bin
RUN wget -q www.nuget.org/NuGet.exe -O /usr/local/bin/nuget.exe
diff --git a/kokoro/linux/dockerfile/test/php/Dockerfile b/kokoro/linux/dockerfile/test/php/Dockerfile
index 276cb73..a540177 100644
--- a/kokoro/linux/dockerfile/test/php/Dockerfile
+++ b/kokoro/linux/dockerfile/test/php/Dockerfile
@@ -20,6 +20,9 @@
parallel \
time \
wget \
+ re2c \
+ sqlite3 \
+ libsqlite3-dev \
&& apt-get clean
# Install php dependencies
@@ -232,6 +235,48 @@
&& cp phpunit /usr/local/php-7.3/bin \
&& mv phpunit /usr/local/php-7.3-zts/bin
+# php 7.4
+RUN wget https://ftp.gnu.org/gnu/bison/bison-3.0.1.tar.gz -O /var/local/bison-3.0.1.tar.gz
+RUN cd /var/local \
+ && tar -zxvf bison-3.0.1.tar.gz \
+ && cd /var/local/bison-3.0.1 \
+ && ./configure \
+ && make \
+ && make install
+
+RUN wget https://github.com/php/php-src/archive/php-7.4.0.tar.gz -O /var/local/php-7.4.0.tar.gz
+
+RUN cd /var/local \
+ && tar -zxvf php-7.4.0.tar.gz
+
+RUN cd /var/local/php-src-php-7.4.0 \
+ && ./buildconf --force \
+ && ./configure \
+ --enable-bcmath \
+ --with-gmp \
+ --with-openssl \
+ --with-zlib \
+ --prefix=/usr/local/php-7.4 \
+ && make \
+ && make install \
+ && make clean
+RUN cd /var/local/php-src-php-7.4.0 \
+ && ./buildconf --force \
+ && ./configure \
+ --enable-maintainer-zts \
+ --with-gmp \
+ --with-openssl \
+ --with-zlib \
+ --prefix=/usr/local/php-7.4-zts \
+ && make \
+ && make install \
+ && make clean
+
+RUN wget -O phpunit https://phar.phpunit.de/phpunit-8.phar \
+ && chmod +x phpunit \
+ && cp phpunit /usr/local/php-7.4/bin \
+ && mv phpunit /usr/local/php-7.4-zts/bin
+
# Install php dependencies
RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
valgrind \
diff --git a/kokoro/linux/dockerfile/test/php_32bit/Dockerfile b/kokoro/linux/dockerfile/test/php_32bit/Dockerfile
index f8027c4..b40cb70 100644
--- a/kokoro/linux/dockerfile/test/php_32bit/Dockerfile
+++ b/kokoro/linux/dockerfile/test/php_32bit/Dockerfile
@@ -1,4 +1,4 @@
-FROM 32bit/debian:jessie
+FROM i386/debian:jessie
# Install dependencies. We start with the basic ones require to build protoc
# and the C++ build
@@ -20,6 +20,9 @@
parallel \
time \
wget \
+ re2c \
+ sqlite3 \
+ libsqlite3-dev \
&& apt-get clean
# Install php dependencies
@@ -218,6 +221,46 @@
&& cp phpunit /usr/local/php-7.3/bin \
&& mv phpunit /usr/local/php-7.3-zts/bin
+# php 7.4
+RUN wget https://ftp.gnu.org/gnu/bison/bison-3.0.1.tar.gz -O /var/local/bison-3.0.1.tar.gz
+RUN cd /var/local \
+ && tar -zxvf bison-3.0.1.tar.gz \
+ && cd /var/local/bison-3.0.1 \
+ && ./configure \
+ && make \
+ && make install
+
+RUN wget https://github.com/php/php-src/archive/php-7.4.0.tar.gz -O /var/local/php-7.4.0.tar.gz
+
+RUN cd /var/local \
+ && tar -zxvf php-7.4.0.tar.gz
+
+RUN cd /var/local/php-src-php-7.4.0 \
+ && ./buildconf --force \
+ && ./configure \
+ --enable-bcmath \
+ --with-openssl \
+ --with-zlib \
+ --prefix=/usr/local/php-7.4 \
+ && make \
+ && make install \
+ && make clean
+RUN cd /var/local/php-src-php-7.4.0 \
+ && ./buildconf --force \
+ && ./configure \
+ --enable-maintainer-zts \
+ --with-openssl \
+ --with-zlib \
+ --prefix=/usr/local/php-7.4-zts \
+ && make \
+ && make install \
+ && make clean
+
+RUN wget -O phpunit https://phar.phpunit.de/phpunit-8.phar \
+ && chmod +x phpunit \
+ && cp phpunit /usr/local/php-7.4/bin \
+ && mv phpunit /usr/local/php-7.4-zts/bin
+
# Install php dependencies
RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
valgrind \
diff --git a/kokoro/linux/dockerfile/test/python27/Dockerfile b/kokoro/linux/dockerfile/test/python27/Dockerfile
new file mode 100644
index 0000000..e41e49a
--- /dev/null
+++ b/kokoro/linux/dockerfile/test/python27/Dockerfile
@@ -0,0 +1,23 @@
+FROM python:2.7-buster
+
+# Install dependencies. We start with the basic ones require to build protoc
+# and the C++ build
+RUN apt-get update && apt-get install -y \
+ autoconf \
+ autotools-dev \
+ build-essential \
+ bzip2 \
+ ccache \
+ curl \
+ gcc \
+ git \
+ libc6 \
+ libc6-dbg \
+ libc6-dev \
+ libgtest-dev \
+ libtool \
+ make \
+ parallel \
+ time \
+ wget \
+ && apt-get clean
diff --git a/kokoro/linux/dockerfile/test/python35/Dockerfile b/kokoro/linux/dockerfile/test/python35/Dockerfile
new file mode 100644
index 0000000..3ea4c9e
--- /dev/null
+++ b/kokoro/linux/dockerfile/test/python35/Dockerfile
@@ -0,0 +1,23 @@
+FROM python:3.5-buster
+
+# Install dependencies. We start with the basic ones require to build protoc
+# and the C++ build
+RUN apt-get update && apt-get install -y \
+ autoconf \
+ autotools-dev \
+ build-essential \
+ bzip2 \
+ ccache \
+ curl \
+ gcc \
+ git \
+ libc6 \
+ libc6-dbg \
+ libc6-dev \
+ libgtest-dev \
+ libtool \
+ make \
+ parallel \
+ time \
+ wget \
+ && apt-get clean
diff --git a/kokoro/linux/dockerfile/test/python36/Dockerfile b/kokoro/linux/dockerfile/test/python36/Dockerfile
new file mode 100644
index 0000000..4368460
--- /dev/null
+++ b/kokoro/linux/dockerfile/test/python36/Dockerfile
@@ -0,0 +1,23 @@
+FROM python:3.6-buster
+
+# Install dependencies. We start with the basic ones require to build protoc
+# and the C++ build
+RUN apt-get update && apt-get install -y \
+ autoconf \
+ autotools-dev \
+ build-essential \
+ bzip2 \
+ ccache \
+ curl \
+ gcc \
+ git \
+ libc6 \
+ libc6-dbg \
+ libc6-dev \
+ libgtest-dev \
+ libtool \
+ make \
+ parallel \
+ time \
+ wget \
+ && apt-get clean
diff --git a/kokoro/linux/dockerfile/test/python37/Dockerfile b/kokoro/linux/dockerfile/test/python37/Dockerfile
new file mode 100644
index 0000000..c711eb8
--- /dev/null
+++ b/kokoro/linux/dockerfile/test/python37/Dockerfile
@@ -0,0 +1,23 @@
+FROM python:3.7-buster
+
+# Install dependencies. We start with the basic ones require to build protoc
+# and the C++ build
+RUN apt-get update && apt-get install -y \
+ autoconf \
+ autotools-dev \
+ build-essential \
+ bzip2 \
+ ccache \
+ curl \
+ gcc \
+ git \
+ libc6 \
+ libc6-dbg \
+ libc6-dev \
+ libgtest-dev \
+ libtool \
+ make \
+ parallel \
+ time \
+ wget \
+ && apt-get clean
diff --git a/kokoro/linux/dockerfile/test/python38/Dockerfile b/kokoro/linux/dockerfile/test/python38/Dockerfile
new file mode 100644
index 0000000..48a7be5
--- /dev/null
+++ b/kokoro/linux/dockerfile/test/python38/Dockerfile
@@ -0,0 +1,23 @@
+FROM python:3.8-buster
+
+# Install dependencies. We start with the basic ones require to build protoc
+# and the C++ build
+RUN apt-get update && apt-get install -y \
+ autoconf \
+ autotools-dev \
+ build-essential \
+ bzip2 \
+ ccache \
+ curl \
+ gcc \
+ git \
+ libc6 \
+ libc6-dbg \
+ libc6-dev \
+ libgtest-dev \
+ libtool \
+ make \
+ parallel \
+ time \
+ wget \
+ && apt-get clean
diff --git a/kokoro/linux/dockerfile/test/python_jessie/Dockerfile b/kokoro/linux/dockerfile/test/python_jessie/Dockerfile
deleted file mode 100644
index b5a53a3..0000000
--- a/kokoro/linux/dockerfile/test/python_jessie/Dockerfile
+++ /dev/null
@@ -1,39 +0,0 @@
-FROM debian:jessie
-
-# Install dependencies. We start with the basic ones require to build protoc
-# and the C++ build
-RUN apt-get update && apt-get install -y \
- autoconf \
- autotools-dev \
- build-essential \
- bzip2 \
- ccache \
- curl \
- gcc \
- git \
- libc6 \
- libc6-dbg \
- libc6-dev \
- libgtest-dev \
- libtool \
- make \
- parallel \
- time \
- wget \
- && apt-get clean
-
-# Install python dependencies
-RUN apt-get update && apt-get install -y \
- python-setuptools \
- python-all-dev \
- python3-all-dev \
- python-pip
-
-# Install Python packages from PyPI
-RUN pip install --upgrade pip==10.0.1
-RUN pip install virtualenv
-RUN pip install six==1.10.0 twisted==17.5.0
-
-# Install pip and virtualenv for Python 3.4
-RUN curl https://bootstrap.pypa.io/get-pip.py | python3.4
-RUN python3.4 -m pip install virtualenv
diff --git a/kokoro/linux/dockerfile/test/python_stretch/Dockerfile b/kokoro/linux/dockerfile/test/python_stretch/Dockerfile
deleted file mode 100644
index 1dba530..0000000
--- a/kokoro/linux/dockerfile/test/python_stretch/Dockerfile
+++ /dev/null
@@ -1,47 +0,0 @@
-FROM debian:stretch
-
-# Install dependencies. We start with the basic ones require to build protoc
-# and the C++ build
-RUN apt-get update && apt-get install -y \
- autoconf \
- autotools-dev \
- build-essential \
- bzip2 \
- ccache \
- curl \
- gcc \
- git \
- libc6 \
- libc6-dbg \
- libc6-dev \
- libgtest-dev \
- libtool \
- make \
- parallel \
- time \
- wget \
- && apt-get clean
-
-# Install Python 2.7
-RUN apt-get update && apt-get install -y python2.7 python-all-dev
-RUN curl https://bootstrap.pypa.io/get-pip.py | python2.7
-
-# Install python dependencies
-RUN apt-get update && apt-get install -y \
- python-setuptools \
- python-pip
-
-# Add Debian 'testing' repository
-RUN echo 'deb http://ftp.de.debian.org/debian testing main' >> /etc/apt/sources.list
-RUN echo 'APT::Default-Release "stable";' | tee -a /etc/apt/apt.conf.d/00local
-
-# Install Python3
-RUN apt-get update && apt-get -t testing install -y \
- python3.5 \
- python3.6 \
- python3.7 \
- python3-all-dev
-
-RUN curl https://bootstrap.pypa.io/get-pip.py | python3.5
-RUN curl https://bootstrap.pypa.io/get-pip.py | python3.6
-RUN curl https://bootstrap.pypa.io/get-pip.py | python3.7
diff --git a/kokoro/linux/dockerfile/test/ruby/Dockerfile b/kokoro/linux/dockerfile/test/ruby/Dockerfile
index 41bfede..9037da7 100644
--- a/kokoro/linux/dockerfile/test/ruby/Dockerfile
+++ b/kokoro/linux/dockerfile/test/ruby/Dockerfile
@@ -32,6 +32,7 @@
RUN /bin/bash -l -c "rvm install 2.4.5"
RUN /bin/bash -l -c "rvm install 2.5.1"
RUN /bin/bash -l -c "rvm install 2.6.0"
+RUN /bin/bash -l -c "rvm install 2.7.0"
RUN /bin/bash -l -c "echo 'gem: --no-ri --no-rdoc' > ~/.gemrc"
RUN /bin/bash -l -c "echo 'export PATH=/usr/local/rvm/bin:$PATH' >> ~/.bashrc"
diff --git a/kokoro/linux/python27/build.sh b/kokoro/linux/python27/build.sh
index 8c40ba3..41531a1 100755
--- a/kokoro/linux/python27/build.sh
+++ b/kokoro/linux/python27/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python27
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python27"
diff --git a/kokoro/linux/python27_cpp/build.sh b/kokoro/linux/python27_cpp/build.sh
index 2ff09a2..1a972ee 100755
--- a/kokoro/linux/python27_cpp/build.sh
+++ b/kokoro/linux/python27_cpp/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python27
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python27_cpp"
diff --git a/kokoro/linux/python33/build.sh b/kokoro/linux/python33/build.sh
deleted file mode 100755
index 84a9acd..0000000
--- a/kokoro/linux/python33/build.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/bin/bash
-#
-# This is the top-level script we give to Kokoro as the entry point for
-# running the "pull request" project:
-#
-# This script selects a specific Dockerfile (for building a Docker image) and
-# a script to run inside that image. Then we delegate to the general
-# build_and_run_docker.sh script.
-
-# Change to repo root
-cd $(dirname $0)/../../..
-
-export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
-export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
-export OUTPUT_DIR=testoutput
-export TEST_SET="python33"
-./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python33_cpp/build.sh b/kokoro/linux/python33_cpp/build.sh
deleted file mode 100755
index ad33e89..0000000
--- a/kokoro/linux/python33_cpp/build.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/bin/bash
-#
-# This is the top-level script we give to Kokoro as the entry point for
-# running the "pull request" project:
-#
-# This script selects a specific Dockerfile (for building a Docker image) and
-# a script to run inside that image. Then we delegate to the general
-# build_and_run_docker.sh script.
-
-# Change to repo root
-cd $(dirname $0)/../../..
-
-export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
-export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
-export OUTPUT_DIR=testoutput
-export TEST_SET="python33_cpp"
-./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python34/presubmit.cfg b/kokoro/linux/python34/presubmit.cfg
deleted file mode 100644
index e2fc413..0000000
--- a/kokoro/linux/python34/presubmit.cfg
+++ /dev/null
@@ -1,11 +0,0 @@
-# Config file for running tests in Kokoro
-
-# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/python/build.sh"
-timeout_mins: 120
-
-action {
- define_artifacts {
- regex: "**/sponge_log.xml"
- }
-}
diff --git a/kokoro/linux/python34_cpp/build.sh b/kokoro/linux/python34_cpp/build.sh
deleted file mode 100755
index e4590ff..0000000
--- a/kokoro/linux/python34_cpp/build.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/bin/bash
-#
-# This is the top-level script we give to Kokoro as the entry point for
-# running the "pull request" project:
-#
-# This script selects a specific Dockerfile (for building a Docker image) and
-# a script to run inside that image. Then we delegate to the general
-# build_and_run_docker.sh script.
-
-# Change to repo root
-cd $(dirname $0)/../../..
-
-export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
-export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
-export OUTPUT_DIR=testoutput
-export TEST_SET="python34_cpp"
-./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python34_cpp/continuous.cfg b/kokoro/linux/python34_cpp/continuous.cfg
deleted file mode 100644
index b1b0e55..0000000
--- a/kokoro/linux/python34_cpp/continuous.cfg
+++ /dev/null
@@ -1,11 +0,0 @@
-# Config file for running tests in Kokoro
-
-# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/python_cpp/build.sh"
-timeout_mins: 120
-
-action {
- define_artifacts {
- regex: "**/sponge_log.xml"
- }
-}
diff --git a/kokoro/linux/python34_cpp/presubmit.cfg b/kokoro/linux/python34_cpp/presubmit.cfg
deleted file mode 100644
index b1b0e55..0000000
--- a/kokoro/linux/python34_cpp/presubmit.cfg
+++ /dev/null
@@ -1,11 +0,0 @@
-# Config file for running tests in Kokoro
-
-# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/python_cpp/build.sh"
-timeout_mins: 120
-
-action {
- define_artifacts {
- regex: "**/sponge_log.xml"
- }
-}
diff --git a/kokoro/linux/python35/build.sh b/kokoro/linux/python35/build.sh
index f978e2a..66ea03f 100755
--- a/kokoro/linux/python35/build.sh
+++ b/kokoro/linux/python35/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_stretch
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python35
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python35"
diff --git a/kokoro/linux/python35_cpp/build.sh b/kokoro/linux/python35_cpp/build.sh
index 2a79246..4d0dbd4 100755
--- a/kokoro/linux/python35_cpp/build.sh
+++ b/kokoro/linux/python35_cpp/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_stretch
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python35
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python35_cpp"
diff --git a/kokoro/linux/python36/build.sh b/kokoro/linux/python36/build.sh
index 633145b..a483efc 100755
--- a/kokoro/linux/python36/build.sh
+++ b/kokoro/linux/python36/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_stretch
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python36
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python36"
diff --git a/kokoro/linux/python36_cpp/build.sh b/kokoro/linux/python36_cpp/build.sh
index 8e120ff..eb71bda 100755
--- a/kokoro/linux/python36_cpp/build.sh
+++ b/kokoro/linux/python36_cpp/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_stretch
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python36
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python36_cpp"
diff --git a/kokoro/linux/python37/build.sh b/kokoro/linux/python37/build.sh
index 554aa09..2117a27 100755
--- a/kokoro/linux/python37/build.sh
+++ b/kokoro/linux/python37/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_stretch
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python37
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python37"
diff --git a/kokoro/linux/python37_cpp/build.sh b/kokoro/linux/python37_cpp/build.sh
index 8fdc8f9..3126b48 100755
--- a/kokoro/linux/python37_cpp/build.sh
+++ b/kokoro/linux/python37_cpp/build.sh
@@ -11,7 +11,7 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_stretch
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python37
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
export TEST_SET="python37_cpp"
diff --git a/kokoro/linux/python34/build.sh b/kokoro/linux/python38/build.sh
similarity index 85%
rename from kokoro/linux/python34/build.sh
rename to kokoro/linux/python38/build.sh
index 25dfd5d..299c7ba 100755
--- a/kokoro/linux/python34/build.sh
+++ b/kokoro/linux/python38/build.sh
@@ -11,8 +11,8 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python38
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
-export TEST_SET="python34"
+export TEST_SET="python38"
./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python33/continuous.cfg b/kokoro/linux/python38/continuous.cfg
similarity index 100%
rename from kokoro/linux/python33/continuous.cfg
rename to kokoro/linux/python38/continuous.cfg
diff --git a/kokoro/linux/python33/presubmit.cfg b/kokoro/linux/python38/presubmit.cfg
similarity index 100%
rename from kokoro/linux/python33/presubmit.cfg
rename to kokoro/linux/python38/presubmit.cfg
diff --git a/kokoro/linux/python34/build.sh b/kokoro/linux/python38_cpp/build.sh
similarity index 85%
copy from kokoro/linux/python34/build.sh
copy to kokoro/linux/python38_cpp/build.sh
index 25dfd5d..b43859b 100755
--- a/kokoro/linux/python34/build.sh
+++ b/kokoro/linux/python38_cpp/build.sh
@@ -11,8 +11,8 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python38
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
-export TEST_SET="python34"
+export TEST_SET="python38_cpp"
./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python33_cpp/continuous.cfg b/kokoro/linux/python38_cpp/continuous.cfg
similarity index 100%
rename from kokoro/linux/python33_cpp/continuous.cfg
rename to kokoro/linux/python38_cpp/continuous.cfg
diff --git a/kokoro/linux/python33_cpp/presubmit.cfg b/kokoro/linux/python38_cpp/presubmit.cfg
similarity index 100%
rename from kokoro/linux/python33_cpp/presubmit.cfg
rename to kokoro/linux/python38_cpp/presubmit.cfg
diff --git a/kokoro/linux/python34/build.sh b/kokoro/linux/ruby27/build.sh
similarity index 85%
copy from kokoro/linux/python34/build.sh
copy to kokoro/linux/ruby27/build.sh
index 25dfd5d..c38ee36 100755
--- a/kokoro/linux/python34/build.sh
+++ b/kokoro/linux/ruby27/build.sh
@@ -11,8 +11,8 @@
cd $(dirname $0)/../../..
export DOCKERHUB_ORGANIZATION=protobuftesting
-export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python_jessie
+export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/ruby
export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
-export TEST_SET="python34"
+export TEST_SET="ruby27"
./kokoro/linux/build_and_run_docker.sh
diff --git a/kokoro/linux/python34/continuous.cfg b/kokoro/linux/ruby27/continuous.cfg
similarity index 76%
rename from kokoro/linux/python34/continuous.cfg
rename to kokoro/linux/ruby27/continuous.cfg
index e2fc413..9cce8c9 100644
--- a/kokoro/linux/python34/continuous.cfg
+++ b/kokoro/linux/ruby27/continuous.cfg
@@ -1,7 +1,7 @@
# Config file for running tests in Kokoro
# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/python/build.sh"
+build_file: "protobuf/kokoro/linux/ruby27/build.sh"
timeout_mins: 120
action {
diff --git a/kokoro/linux/python34/continuous.cfg b/kokoro/linux/ruby27/presubmit.cfg
similarity index 76%
copy from kokoro/linux/python34/continuous.cfg
copy to kokoro/linux/ruby27/presubmit.cfg
index e2fc413..9cce8c9 100644
--- a/kokoro/linux/python34/continuous.cfg
+++ b/kokoro/linux/ruby27/presubmit.cfg
@@ -1,7 +1,7 @@
# Config file for running tests in Kokoro
# Location of the build script in repository
-build_file: "protobuf/kokoro/linux/python/build.sh"
+build_file: "protobuf/kokoro/linux/ruby27/build.sh"
timeout_mins: 120
action {
diff --git a/kokoro/macos/php7.4_mac/build.sh b/kokoro/macos/php7.4_mac/build.sh
new file mode 100755
index 0000000..98c82d4
--- /dev/null
+++ b/kokoro/macos/php7.4_mac/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh php7.4_mac
diff --git a/kokoro/macos/php7.4_mac/continuous.cfg b/kokoro/macos/php7.4_mac/continuous.cfg
new file mode 100644
index 0000000..5b2d6fd
--- /dev/null
+++ b/kokoro/macos/php7.4_mac/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/php7.4_mac/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/php7.4_mac/presubmit.cfg b/kokoro/macos/php7.4_mac/presubmit.cfg
new file mode 100644
index 0000000..5b2d6fd
--- /dev/null
+++ b/kokoro/macos/php7.4_mac/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/php7.4_mac/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/prepare_build_macos_rc b/kokoro/macos/prepare_build_macos_rc
index acb2aba..2428750 100755
--- a/kokoro/macos/prepare_build_macos_rc
+++ b/kokoro/macos/prepare_build_macos_rc
@@ -5,11 +5,11 @@
##
# Select Xcode version
-# Remember to udpate the Xcode version when Xcode_11.0.app is not available.
-# If xcode is not available, it will probaly encounter the failure for
+# Remember to update the Xcode version when Xcode_11.3.app is not available.
+# If xcode is not available, it will probably encounter the failure for
# "autom4te: need GNU m4 1.4 or later: /usr/bin/m4"
# go/kokoro/userdocs/macos/selecting_xcode.md for more information.
-export DEVELOPER_DIR=/Applications/Xcode_11.0.app/Contents/Developer
+export DEVELOPER_DIR=/Applications/Xcode_11.3.app/Contents/Developer
##
# Select C/C++ compilers
diff --git a/kokoro/macos/ruby27/build.sh b/kokoro/macos/ruby27/build.sh
new file mode 100755
index 0000000..16bcbd6
--- /dev/null
+++ b/kokoro/macos/ruby27/build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+#
+# Build file to set up and run tests
+
+# Change to repo root
+cd $(dirname $0)/../../..
+
+# Prepare worker environment to run tests
+source kokoro/macos/prepare_build_macos_rc
+
+./tests.sh ruby27
diff --git a/kokoro/macos/ruby27/continuous.cfg b/kokoro/macos/ruby27/continuous.cfg
new file mode 100644
index 0000000..b10b455
--- /dev/null
+++ b/kokoro/macos/ruby27/continuous.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/ruby27/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/macos/ruby27/presubmit.cfg b/kokoro/macos/ruby27/presubmit.cfg
new file mode 100644
index 0000000..b10b455
--- /dev/null
+++ b/kokoro/macos/ruby27/presubmit.cfg
@@ -0,0 +1,5 @@
+# Config file for running tests in Kokoro
+
+# Location of the build script in repository
+build_file: "protobuf/kokoro/macos/ruby27/build.sh"
+timeout_mins: 1440
diff --git a/kokoro/release/collect_all_artifacts.sh b/kokoro/release/collect_all_artifacts.sh
index 0023937..3b7d7d4 100755
--- a/kokoro/release/collect_all_artifacts.sh
+++ b/kokoro/release/collect_all_artifacts.sh
@@ -43,9 +43,7 @@
cp ${INPUT_ARTIFACTS_DIR}/protoc-artifacts/target/linux/x86_32/protoc.exe protoc/linux_x86/protoc
cp ${INPUT_ARTIFACTS_DIR}/protoc-artifacts/target/linux/x86_64/protoc.exe protoc/linux_x64/protoc
-mkdir -p protoc/macosx_x86
mkdir -p protoc/macosx_x64
-cp ${INPUT_ARTIFACTS_DIR}/build32/src/protoc protoc/macosx_x86/protoc
cp ${INPUT_ARTIFACTS_DIR}/build64/src/protoc protoc/macosx_x64/protoc
# Install nuget (will also install mono)
diff --git a/kokoro/release/protoc/linux/build.sh b/kokoro/release/protoc/linux/build.sh
index d165a89..efc3ee6 100755
--- a/kokoro/release/protoc/linux/build.sh
+++ b/kokoro/release/protoc/linux/build.sh
@@ -23,7 +23,7 @@
protoc-artifacts/build-protoc.sh linux ppcle_64 protoc
sudo apt install -y g++-s390x-linux-gnu
-protoc-artifacts/build-protoc.sh linux s390x_64 protoc
+protoc-artifacts/build-protoc.sh linux s390x protoc
# Use docker image to build linux artifacts.
DOCKER_IMAGE_NAME=protobuf/protoc_$(sha1sum protoc-artifacts/Dockerfile | cut -f1 -d " ")
diff --git a/kokoro/release/protoc/macos/build.sh b/kokoro/release/protoc/macos/build.sh
old mode 100644
new mode 100755
index 6a4c79c..47c9bfa
--- a/kokoro/release/protoc/macos/build.sh
+++ b/kokoro/release/protoc/macos/build.sh
@@ -6,14 +6,6 @@
cd github/protobuf
./autogen.sh
-mkdir build32 && cd build32
-export CXXFLAGS="$CXXFLAGS_COMMON -m32"
-../configure --disable-shared
-make -j4
-file src/protoc
-otool -L src/protoc | grep dylib
-cd ..
-
mkdir build64 && cd build64
export CXXFLAGS="$CXXFLAGS_COMMON -m64"
../configure --disable-shared
diff --git a/kokoro/release/python/linux/build_artifacts.sh b/kokoro/release/python/linux/build_artifacts.sh
index 5f9eaa1..fd9d5a9 100755
--- a/kokoro/release/python/linux/build_artifacts.sh
+++ b/kokoro/release/python/linux/build_artifacts.sh
@@ -53,3 +53,4 @@
build_artifact_version 3.5
build_artifact_version 3.6
build_artifact_version 3.7
+build_artifact_version 3.8
diff --git a/kokoro/release/python/macos/build_artifacts.sh b/kokoro/release/python/macos/build_artifacts.sh
index 148d1f9..15aae39 100755
--- a/kokoro/release/python/macos/build_artifacts.sh
+++ b/kokoro/release/python/macos/build_artifacts.sh
@@ -50,7 +50,13 @@
mv wheelhouse/* $ARTIFACT_DIR
}
+export MB_PYTHON_OSX_VER=10.9
build_artifact_version 2.7
-build_artifact_version 3.5
build_artifact_version 3.6
build_artifact_version 3.7
+build_artifact_version 3.8
+
+# python OSX10.9 does not have python 3.5
+export MB_PYTHON_OSX_VER=10.6
+build_artifact_version 3.5
+
diff --git a/kokoro/release/python/windows/build_artifacts.bat b/kokoro/release/python/windows/build_artifacts.bat
index 9a6842a..70a86a1 100644
--- a/kokoro/release/python/windows/build_artifacts.bat
+++ b/kokoro/release/python/windows/build_artifacts.bat
@@ -62,6 +62,16 @@
SET PYTHON_ARCH=64
CALL build_single_artifact.bat || goto :error
+SET PYTHON=C:\python38_32bit
+SET PYTHON_VERSION=3.8
+SET PYTHON_ARCH=32
+CALL build_single_artifact.bat || goto :error
+
+SET PYTHON=C:\python38
+SET PYTHON_VERSION=3.8
+SET PYTHON_ARCH=64
+CALL build_single_artifact.bat || goto :error
+
goto :EOF
:error
diff --git a/kokoro/release/python/windows/build_single_artifact.bat b/kokoro/release/python/windows/build_single_artifact.bat
index d7cd062..45843e1 100644
--- a/kokoro/release/python/windows/build_single_artifact.bat
+++ b/kokoro/release/python/windows/build_single_artifact.bat
@@ -18,6 +18,12 @@
if %PYTHON%==C:\python37 set generator=Visual Studio 14 Win64
if %PYTHON%==C:\python37 set vcplatform=x64
+if %PYTHON%==C:\python38_32bit set generator=Visual Studio 14
+if %PYTHON%==C:\python38_32bit set vcplatform=Win32
+
+if %PYTHON%==C:\python38 set generator=Visual Studio 14 Win64
+if %PYTHON%==C:\python38 set vcplatform=x64
+
REM Prepend newly installed Python to the PATH of this build (this cannot be
REM done from inside the powershell script as it would require to restart
REM the parent CMD process).
diff --git a/kokoro/release/ruby/linux/prepare_build.sh b/kokoro/release/ruby/linux/prepare_build.sh
index f2257c3..91d1868 100755
--- a/kokoro/release/ruby/linux/prepare_build.sh
+++ b/kokoro/release/ruby/linux/prepare_build.sh
@@ -7,12 +7,6 @@
echo 'DOCKER_OPTS="${DOCKER_OPTS} --registry-mirror=https://mirror.gcr.io"' | sudo tee --append /etc/default/docker
sudo service docker restart
-# Download Docker images from DockerHub
-DOCKERHUB_ORGANIZATION=protobuftesting
-DOCKERFILE_DIR=kokoro/linux/dockerfile/release/ruby_rake_compiler
-DOCKERFILE_PREFIX=$(basename $DOCKERFILE_DIR)
-export RAKE_COMPILER_DOCK_IMAGE=${DOCKERHUB_ORGANIZATION}/${DOCKERFILE_PREFIX}_$(sha1sum $DOCKERFILE_DIR/Dockerfile | cut -f1 -d\ )
-
# All artifacts come here
mkdir artifacts
export ARTIFACT_DIR=$(pwd)/artifacts
diff --git a/kokoro/release/ruby/linux/ruby/ruby_build.sh b/kokoro/release/ruby/linux/ruby/ruby_build.sh
index 9fc42b1..95f1dea 100755
--- a/kokoro/release/ruby/linux/ruby/ruby_build.sh
+++ b/kokoro/release/ruby/linux/ruby/ruby_build.sh
@@ -11,6 +11,7 @@
umask 0022
pushd ruby
+gem install bundler -v 2.1.4
bundle install && bundle exec rake gem:native
ls pkg
mv pkg/* $ARTIFACT_DIR
diff --git a/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh b/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh
index ea04f90..87c0f75 100755
--- a/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh
+++ b/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh
@@ -4,5 +4,6 @@
[[ -s /etc/profile.d/rvm.sh ]] && . /etc/profile.d/rvm.sh
set -e # rvm commands are very verbose
rvm --default use ruby-2.4.1
-gem install bundler --update
+# The version needs to be updated if the version specified in Gemfile.lock is changed
+gem install bundler -v '1.17.3'
set -ex
diff --git a/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh b/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh
index 5776e3c..7ff1ce5 100755
--- a/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh
+++ b/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh
@@ -6,7 +6,11 @@
source $HOME/.rvm/scripts/rvm
set -e # rvm commands are very verbose
time rvm install 2.5.0
-rvm use 2.5.0 --default
+rvm use 2.5.0
+gem install rake-compiler --no-document
+gem install bundler --no-document
+time rvm install 2.7.0
+rvm use 2.7.0 --default
gem install rake-compiler --no-document
gem install bundler --no-document
rvm osx-ssl-certs status all
@@ -17,13 +21,13 @@
CROSS_RUBY=$(mktemp tmpfile.XXXXXXXX)
-curl https://raw.githubusercontent.com/rake-compiler/rake-compiler/v1.0.3/tasks/bin/cross-ruby.rake > "$CROSS_RUBY"
+curl https://raw.githubusercontent.com/rake-compiler/rake-compiler/v1.1.0/tasks/bin/cross-ruby.rake > "$CROSS_RUBY"
# See https://github.com/grpc/grpc/issues/12161 for verconf.h patch details
patch "$CROSS_RUBY" << EOF
--- cross-ruby.rake 2018-04-10 11:32:16.000000000 -0700
+++ patched 2018-04-10 11:40:25.000000000 -0700
-@@ -133,8 +133,10 @@
+@@ -141,8 +141,10 @@
"--host=#{MINGW_HOST}",
"--target=#{MINGW_TARGET}",
"--build=#{RUBY_BUILD}",
@@ -35,9 +39,9 @@
'--with-ext='
]
-@@ -151,6 +153,7 @@
+@@ -159,6 +161,7 @@
# make
- file "#{USER_HOME}/builds/#{MINGW_HOST}/#{RUBY_CC_VERSION}/ruby.exe" => ["#{USER_HOME}/builds/#{MINGW_HOST}/#{RUBY_CC_VERSION}/Makefile"] do |t|
+ file "#{build_dir}/ruby.exe" => ["#{build_dir}/Makefile"] do |t|
chdir File.dirname(t.prerequisites.first) do
+ sh "test -s verconf.h || rm -f verconf.h" # if verconf.h has size 0, make sure it gets re-built by make
sh MAKE
@@ -47,10 +51,25 @@
MAKE="make -j8"
-for v in 2.6.0 2.5.1 2.4.0 2.3.0 ; do
+set +x # rvm commands are very verbose
+rvm use 2.7.0
+set -x
+ruby --version | grep 'ruby 2.7.0'
+for v in 2.7.0 ; do
ccache -c
rake -f "$CROSS_RUBY" cross-ruby VERSION="$v" HOST=x86_64-darwin11 MAKE="$MAKE"
done
+set +x
+rvm use 2.5.0
+set -x
+ruby --version | grep 'ruby 2.5.0'
+for v in 2.6.0 2.5.1 ; do
+ ccache -c
+ rake -f "$CROSS_RUBY" cross-ruby VERSION="$v" HOST=x86_64-darwin11 MAKE="$MAKE"
+done
+set +x
+rvm use 2.7.0
+set -x
sed 's/x86_64-darwin-11/universal-darwin/' ~/.rake-compiler/config.yml > "$CROSS_RUBY"
mv "$CROSS_RUBY" ~/.rake-compiler/config.yml
diff --git a/objectivec/.clang-format b/objectivec/.clang-format
new file mode 100644
index 0000000..d3ff76b
--- /dev/null
+++ b/objectivec/.clang-format
@@ -0,0 +1,7 @@
+BasedOnStyle: Google
+
+# Ignore pddm directives.
+CommentPragmas: '^%'
+
+# Following the rest of the protobuf code.
+ColumnLimit: 80
diff --git a/objectivec/DevTools/compile_testing_protos.sh b/objectivec/DevTools/compile_testing_protos.sh
index 3070ba6..d04c5c5 100755
--- a/objectivec/DevTools/compile_testing_protos.sh
+++ b/objectivec/DevTools/compile_testing_protos.sh
@@ -26,71 +26,9 @@
esac
# -----------------------------------------------------------------------------
-# 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
-else
- # Find the newest input file (protos, compiler, and this script).
- # (these patterns catch some extra stuff, but better to over sample than
- # under)
- readonly NewestInput=$(find \
- src/google/protobuf/*.proto \
- objectivec/Tests/*.proto \
- src/.libs src/*.la src/protoc \
- objectivec/DevTools/compile_testing_protos.sh \
- -type f -print0 \
- | xargs -0 stat -f "%m %N" \
- | sort -n | tail -n1 | cut -f2- -d" ")
- # Find the oldest output file.
- readonly OldestOutput=$(find \
- "${OUTPUT_DIR}" \
- -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.
- if [[ "${NewestInput}" -nt "${OldestOutput}" ]] ; then
- RUN_PROTOC=yes
- fi
-fi
-
-if [[ "${RUN_PROTOC}" != "yes" ]] ; then
- # Up to date.
- exit 0
-fi
-
-# -----------------------------------------------------------------------------
-# 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.
+# Reusing a bunch of the protos from the protocolbuffers/protobuf tree, this
+# can include some extras as there is no harm in ensuring work for C++
+# generation.
CORE_PROTO_FILES=(
src/google/protobuf/any_test.proto
@@ -122,6 +60,111 @@
src/google/protobuf/descriptor.proto
)
+# -----------------------------------------------------------------------------
+# The objc unittest specific proto files.
+
+OBJC_TEST_PROTO_FILES=(
+ objectivec/Tests/unittest_cycle.proto
+ objectivec/Tests/unittest_deprecated.proto
+ objectivec/Tests/unittest_deprecated_file.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_objc_options.proto
+ objectivec/Tests/unittest_runtime_proto2.proto
+ objectivec/Tests/unittest_runtime_proto3.proto
+)
+
+OBJC_EXTENSIONS=( .pbobjc.h .pbobjc.m )
+
+# -----------------------------------------------------------------------------
+# 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)."
+
+# -----------------------------------------------------------------------------
+RUN_PROTOC=no
+
+# Check to if all the output files exist (incase a new one got added).
+
+for PROTO_FILE in "${CORE_PROTO_FILES[@]}" "${OBJC_TEST_PROTO_FILES[@]}"; do
+ DIR=${PROTO_FILE%/*}
+ BASE_NAME=${PROTO_FILE##*/}
+ # Drop the extension
+ BASE_NAME=${BASE_NAME%.*}
+ OBJC_NAME=$(echo "${BASE_NAME}" | awk -F _ '{for(i=1; i<=NF; i++) printf "%s", toupper(substr($i,1,1)) substr($i,2);}')
+
+ for EXT in "${OBJC_EXTENSIONS[@]}"; do
+ if [[ ! -f "${OUTPUT_DIR}/google/protobuf/${OBJC_NAME}${EXT}" ]]; then
+ RUN_PROTOC=yes
+ fi
+ done
+done
+
+# If we haven't decided to run protoc because of a missing file, check to see if
+# an input has changed.
+if [[ "${RUN_PROTOC}" != "yes" ]] ; then
+ # Find the newest input file (protos, compiler, and this script).
+ # (these patterns catch some extra stuff, but better to over sample than
+ # under)
+ readonly NewestInput=$(find \
+ src/google/protobuf/*.proto \
+ objectivec/Tests/*.proto \
+ src/.libs src/*.la src/protoc \
+ objectivec/DevTools/compile_testing_protos.sh \
+ -type f -print0 \
+ | xargs -0 stat -f "%m %N" \
+ | sort -n | tail -n1 | cut -f2- -d" ")
+ # Find the oldest output file.
+ readonly OldestOutput=$(find \
+ "${OUTPUT_DIR}" \
+ -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.
+ if [[ "${NewestInput}" -nt "${OldestOutput}" ]] ; then
+ RUN_PROTOC=yes
+ fi
+fi
+
+if [[ "${RUN_PROTOC}" != "yes" ]] ; then
+ # Up to date.
+ exit 0
+fi
+
+# -----------------------------------------------------------------------------
+# 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 \
+ --experimental_allow_proto3_optional \
+ "$@"
+}
+
+# -----------------------------------------------------------------------------
+# Generate most of the proto files that exist in the C++ src tree.
+
# 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.
@@ -133,18 +176,4 @@
# Generate the Objective C specific testing protos.
compile_protos \
--proto_path="objectivec/Tests" \
- objectivec/Tests/unittest_cycle.proto \
- objectivec/Tests/unittest_deprecated.proto \
- objectivec/Tests/unittest_deprecated_file.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 \
- objectivec/Tests/unittest_objc_options.proto
+ "${OBJC_TEST_PROTO_FILES[@]}"
diff --git a/objectivec/DevTools/full_mac_build.sh b/objectivec/DevTools/full_mac_build.sh
index 5584b0a..84ed8e9 100755
--- a/objectivec/DevTools/full_mac_build.sh
+++ b/objectivec/DevTools/full_mac_build.sh
@@ -290,12 +290,9 @@
)
;;
11.*)
+ # Dropped 32bit as Apple doesn't seem support the simulators either.
XCODEBUILD_TEST_BASE_IOS+=(
- -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
-destination "platform=iOS Simulator,name=iPhone 8,OS=latest" # 64bit
- # 10.x also seems to often fail running destinations in parallel (with
- # 32bit one include atleast)
- -disable-concurrent-destination-testing
)
;;
* )
diff --git a/objectivec/DevTools/pddm.py b/objectivec/DevTools/pddm.py
index 0b5b7b4..dacf7bb 100755
--- a/objectivec/DevTools/pddm.py
+++ b/objectivec/DevTools/pddm.py
@@ -288,7 +288,7 @@
name = macro_ref_match.group('name')
for prev_name, prev_macro_ref in macro_stack:
if name == prev_name:
- raise PDDMError('Found macro recusion, invoking "%s":%s' %
+ raise PDDMError('Found macro recursion, invoking "%s":%s' %
(macro_ref_str, self._FormatStack(macro_stack)))
macro = self._macros[name]
args_str = macro_ref_match.group('args').strip()
@@ -395,7 +395,7 @@
wasn't append. If SUCCESS is True, then CAN_ADD_MORE is True/False to
indicate if more lines can be added after this one.
"""
- assert False, "sublcass should have overridden"
+ assert False, "subclass should have overridden"
return (False, False)
def HitEOF(self):
@@ -482,13 +482,14 @@
if self._macro_collection:
# Always add a blank line, seems to read better. (If need be, add an
# option to the EXPAND to indicate if this should be done.)
- result.extend([_GENERATED_CODE_LINE, ''])
+ result.extend([_GENERATED_CODE_LINE, '// clang-format off', ''])
macro = line[directive_len:].strip()
try:
expand_result = self._macro_collection.Expand(macro)
# Since expansions are line oriented, strip trailing whitespace
# from the lines.
lines = [x.rstrip() for x in expand_result.split('\n')]
+ lines.append('// clang-format on')
result.append('\n'.join(lines))
except PDDMError as e:
raise PDDMError('%s\n...while expanding "%s" from the section'
@@ -503,7 +504,6 @@
else:
result.append('//%%PDDM-EXPAND-END (%s expansions)' %
len(captured_lines))
-
return result
class DefinitionSection(SectionBase):
diff --git a/objectivec/DevTools/pddm_tests.py b/objectivec/DevTools/pddm_tests.py
index 9ac6a85..8184209 100755
--- a/objectivec/DevTools/pddm_tests.py
+++ b/objectivec/DevTools/pddm_tests.py
@@ -314,7 +314,7 @@
self.fail('Should throw exception! Test failed to catch recursion.')
except pddm.PDDMError as e:
self.assertEqual(e.message,
- 'Found macro recusion, invoking "foo(1, A)":\n...while expanding "bar(1, A)".\n...while expanding "foo(A,B)".')
+ 'Found macro recursion, invoking "foo(1, A)":\n...while expanding "bar(1, A)".\n...while expanding "foo(A,B)".')
class TestParsingSource(unittest.TestCase):
@@ -394,6 +394,7 @@
class TestProcessingSource(unittest.TestCase):
def testBasics(self):
+ self.maxDiff = None
input_str = u"""
//%PDDM-IMPORT-DEFINES ImportFile
foo
@@ -417,18 +418,24 @@
foo
//%PDDM-EXPAND mumble(abc)
// This block of code is generated, do not edit it directly.
+// clang-format off
abc: doAbc(int abc);
+// clang-format on
//%PDDM-EXPAND-END mumble(abc)
bar
//%PDDM-EXPAND mumble(def)
// This block of code is generated, do not edit it directly.
+// clang-format off
def: doDef(int def);
+// clang-format on
//%PDDM-EXPAND mumble(ghi)
// This block of code is generated, do not edit it directly.
+// clang-format off
ghi: doGhi(int ghi);
+// clang-format on
//%PDDM-EXPAND-END (2 expansions)
baz
//%PDDM-DEFINE mumble(a_)
diff --git a/objectivec/GPBAny.pbobjc.h b/objectivec/GPBAny.pbobjc.h
new file mode 100644
index 0000000..288d552
--- /dev/null
+++ b/objectivec/GPBAny.pbobjc.h
@@ -0,0 +1,183 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/any.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+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.
+ **/
+GPB_FINAL @interface GPBAnyRoot : GPBRootObject
+@end
+
+#pragma mark - GPBAny
+
+typedef GPB_ENUM(GPBAny_FieldNumber) {
+ GPBAny_FieldNumber_TypeURL = 1,
+ 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)
+ * ...
+ *
+ * Example 4: Pack and unpack a message in Go
+ *
+ * foo := &pb.Foo{...}
+ * any, err := ptypes.MarshalAny(foo)
+ * ...
+ * foo := &pb.Foo{}
+ * if err := ptypes.UnmarshalAny(any, foo); err != nil {
+ * ...
+ * }
+ *
+ * The pack methods provided by protobuf library will by default use
+ * 'type.googleapis.com/full.type.name' as the type URL and the unpack
+ * methods only use the fully qualified type name after the last '/'
+ * 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"
+ * }
+ **/
+GPB_FINAL @interface GPBAny : GPBMessage
+
+/**
+ * A URL/resource name that uniquely identifies the type of the serialized
+ * protocol buffer message. This string must contain at least
+ * one "/" character. The last segment of the URL's path must represent
+ * the fully qualified name of the type (as in
+ * `path/google.protobuf.Duration`). The name should be in a canonical form
+ * (e.g., leading "." is not accepted).
+ *
+ * In practice, teams usually precompile into the binary all types that they
+ * expect it to use in the context of Any. However, for URLs which use the
+ * scheme `http`, `https`, or no scheme, one can optionally set up a type
+ * server that maps type URLs to message definitions as follows:
+ *
+ * * If no scheme is provided, `https` is assumed.
+ * * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ * value in binary format, or produce an error.
+ * * Applications are allowed to cache lookup results based on the
+ * URL, or have them precompiled into a binary to avoid any
+ * lookup. Therefore, binary compatibility needs to be preserved
+ * on changes to types. (Use versioned type names to manage
+ * breaking changes.)
+ *
+ * Note: this functionality is not currently available in the official
+ * protobuf release, and it is not used for type URLs beginning with
+ * type.googleapis.com.
+ *
+ * Schemes other than `http`, `https` (or the empty scheme) might be
+ * used with implementation specific semantics.
+ **/
+@property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL;
+
+/** Must be a valid serialized protocol buffer of the above specified type. */
+@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Any.pbobjc.m b/objectivec/GPBAny.pbobjc.m
similarity index 85%
rename from objectivec/google/protobuf/Any.pbobjc.m
rename to objectivec/GPBAny.pbobjc.m
index f1e815f..a5143f1 100644
--- a/objectivec/google/protobuf/Any.pbobjc.m
+++ b/objectivec/GPBAny.pbobjc.m
@@ -8,15 +8,15 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Any.pbobjc.h>
+ #import <Protobuf/GPBAny.pbobjc.h>
#else
- #import "google/protobuf/Any.pbobjc.h"
+ #import "GPBAny.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
@@ -68,20 +68,20 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "typeURL",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBAny_FieldNumber_TypeURL,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBAny__storage_, typeURL),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBAny_FieldNumber_Value,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBAny__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeBytes,
},
};
@@ -92,7 +92,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBAny__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS
static const char *extraTextFormatInfo =
"\001\001\004\241!!\000";
diff --git a/objectivec/GPBApi.pbobjc.h b/objectivec/GPBApi.pbobjc.h
new file mode 100644
index 0000000..287c051
--- /dev/null
+++ b/objectivec/GPBApi.pbobjc.h
@@ -0,0 +1,311 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/api.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+@class GPBMethod;
+@class GPBMixin;
+@class GPBOption;
+@class GPBSourceContext;
+GPB_ENUM_FWD_DECLARE(GPBSyntax);
+
+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.
+ **/
+GPB_FINAL @interface GPBApiRoot : GPBRootObject
+@end
+
+#pragma mark - GPBApi
+
+typedef GPB_ENUM(GPBApi_FieldNumber) {
+ GPBApi_FieldNumber_Name = 1,
+ GPBApi_FieldNumber_MethodsArray = 2,
+ GPBApi_FieldNumber_OptionsArray = 3,
+ GPBApi_FieldNumber_Version = 4,
+ GPBApi_FieldNumber_SourceContext = 5,
+ GPBApi_FieldNumber_MixinsArray = 6,
+ GPBApi_FieldNumber_Syntax = 7,
+};
+
+/**
+ * Api is a light-weight descriptor for an API Interface.
+ *
+ * Interfaces are also described as "protocol buffer services" in some contexts,
+ * such as by the "service" keyword in a .proto file, but they are different
+ * from API Services, which represent a concrete implementation of an interface
+ * as opposed to simply a description of methods and bindings. They are also
+ * sometimes simply referred to as "APIs" in other contexts, such as the name of
+ * this message itself. See https://cloud.google.com/apis/design/glossary for
+ * detailed terminology.
+ **/
+GPB_FINAL @interface GPBApi : GPBMessage
+
+/**
+ * The fully qualified name of this interface, including package name
+ * followed by the interface's simple name.
+ **/
+@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
+
+/** The methods of this interface, in unspecified order. */
+@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMethod*> *methodsArray;
+/** The number of items in @c methodsArray without causing the array to be created. */
+@property(nonatomic, readonly) NSUInteger methodsArray_Count;
+
+/** Any metadata attached to the interface. */
+@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
+/** The number of items in @c optionsArray without causing the array to be created. */
+@property(nonatomic, readonly) NSUInteger optionsArray_Count;
+
+/**
+ * A version string for this interface. If specified, must have the form
+ * `major-version.minor-version`, as in `1.10`. If the minor version is
+ * omitted, it defaults to zero. If the entire version field is empty, the
+ * major version is derived from the package name, as outlined below. If the
+ * field is not empty, the version in the package name will be verified to be
+ * consistent with what is provided here.
+ *
+ * The versioning schema uses [semantic
+ * versioning](http://semver.org) where the major version number
+ * indicates a breaking change and the minor version an additive,
+ * non-breaking change. Both version numbers are signals to users
+ * what to expect from different versions, and should be carefully
+ * chosen based on the product plan.
+ *
+ * The major version is also reflected in the package name of the
+ * interface, which must end in `v<major-version>`, as in
+ * `google.feature.v1`. For major versions 0 and 1, the suffix can
+ * be omitted. Zero major versions must only be used for
+ * experimental, non-GA interfaces.
+ **/
+@property(nonatomic, readwrite, copy, null_resettable) NSString *version;
+
+/**
+ * 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. */
+@property(nonatomic, readwrite) BOOL hasSourceContext;
+
+/** Included interfaces. See [Mixin][]. */
+@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMixin*> *mixinsArray;
+/** The number of items in @c mixinsArray without causing the array to be created. */
+@property(nonatomic, readonly) NSUInteger mixinsArray_Count;
+
+/** 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.
+ **/
+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.
+ **/
+void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value);
+
+#pragma mark - GPBMethod
+
+typedef GPB_ENUM(GPBMethod_FieldNumber) {
+ GPBMethod_FieldNumber_Name = 1,
+ GPBMethod_FieldNumber_RequestTypeURL = 2,
+ GPBMethod_FieldNumber_RequestStreaming = 3,
+ GPBMethod_FieldNumber_ResponseTypeURL = 4,
+ GPBMethod_FieldNumber_ResponseStreaming = 5,
+ GPBMethod_FieldNumber_OptionsArray = 6,
+ GPBMethod_FieldNumber_Syntax = 7,
+};
+
+/**
+ * Method represents a method of an API interface.
+ **/
+GPB_FINAL @interface GPBMethod : GPBMessage
+
+/** The simple name of this method. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
+
+/** A URL of the input message type. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *requestTypeURL;
+
+/** If true, the request is streamed. */
+@property(nonatomic, readwrite) BOOL requestStreaming;
+
+/** The URL of the output message type. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *responseTypeURL;
+
+/** If true, the response is streamed. */
+@property(nonatomic, readwrite) BOOL responseStreaming;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger optionsArray_Count;
+
+/** 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.
+ **/
+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.
+ **/
+void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value);
+
+#pragma mark - GPBMixin
+
+typedef GPB_ENUM(GPBMixin_FieldNumber) {
+ GPBMixin_FieldNumber_Name = 1,
+ GPBMixin_FieldNumber_Root = 2,
+};
+
+/**
+ * Declares an API Interface to be included in this interface. The including
+ * interface must redeclare all the methods from the included interface, but
+ * documentation and options are inherited as follows:
+ *
+ * - If after comment and whitespace stripping, the documentation
+ * string of the redeclared method is empty, it will be inherited
+ * from the original method.
+ *
+ * - Each annotation belonging to the service config (http,
+ * visibility) which is not set in the redeclared method will be
+ * inherited.
+ *
+ * - If an http annotation is inherited, the path pattern will be
+ * modified as follows. Any version prefix will be replaced by the
+ * version of the including interface plus the [root][] path if
+ * specified.
+ *
+ * Example of a simple mixin:
+ *
+ * package google.acl.v1;
+ * service AccessControl {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v1/{resource=**}:getAcl";
+ * }
+ * }
+ *
+ * package google.storage.v2;
+ * service Storage {
+ * rpc GetAcl(GetAclRequest) returns (Acl);
+ *
+ * // Get a data record.
+ * rpc GetData(GetDataRequest) returns (Data) {
+ * option (google.api.http).get = "/v2/{resource=**}";
+ * }
+ * }
+ *
+ * Example of a mixin configuration:
+ *
+ * apis:
+ * - name: google.storage.v2.Storage
+ * mixins:
+ * - name: google.acl.v1.AccessControl
+ *
+ * The mixin construct implies that all methods in `AccessControl` are
+ * also declared with same name and request/response types in
+ * `Storage`. A documentation generator or annotation processor will
+ * see the effective `Storage.GetAcl` method after inherting
+ * documentation and annotations as follows:
+ *
+ * service Storage {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v2/{resource=**}:getAcl";
+ * }
+ * ...
+ * }
+ *
+ * Note how the version in the path pattern changed from `v1` to `v2`.
+ *
+ * If the `root` field in the mixin is specified, it should be a
+ * relative path under which inherited HTTP paths are placed. Example:
+ *
+ * apis:
+ * - name: google.storage.v2.Storage
+ * mixins:
+ * - name: google.acl.v1.AccessControl
+ * root: acls
+ *
+ * This implies the following inherited HTTP annotation:
+ *
+ * service Storage {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
+ * }
+ * ...
+ * }
+ **/
+GPB_FINAL @interface GPBMixin : GPBMessage
+
+/** The fully qualified name of the interface which is included. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
+
+/**
+ * If non-empty specifies a path under which inherited HTTP paths
+ * are rooted.
+ **/
+@property(nonatomic, readwrite, copy, null_resettable) NSString *root;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Api.pbobjc.m b/objectivec/GPBApi.pbobjc.m
similarity index 78%
rename from objectivec/google/protobuf/Api.pbobjc.m
rename to objectivec/GPBApi.pbobjc.m
index 4102399..5915ce1 100644
--- a/objectivec/google/protobuf/Api.pbobjc.m
+++ b/objectivec/GPBApi.pbobjc.m
@@ -8,24 +8,34 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Api.pbobjc.h>
- #import <protobuf/SourceContext.pbobjc.h>
- #import <protobuf/Type.pbobjc.h>
+ #import <Protobuf/GPBApi.pbobjc.h>
+ #import <Protobuf/GPBSourceContext.pbobjc.h>
+ #import <Protobuf/GPBType.pbobjc.h>
#else
- #import "google/protobuf/Api.pbobjc.h"
- #import "google/protobuf/SourceContext.pbobjc.h"
- #import "google/protobuf/Type.pbobjc.h"
+ #import "GPBApi.pbobjc.h"
+ #import "GPBSourceContext.pbobjc.h"
+ #import "GPBType.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#pragma clang diagnostic ignored "-Wdollar-in-identifier-extension"
+
+#pragma mark - Objective C Class declarations
+// Forward declarations of Objective C classes that we can use as
+// static values in struct initializers.
+// We don't use [Foo class] because it is not a static value.
+GPBObjCClassDeclaration(GPBMethod);
+GPBObjCClassDeclaration(GPBMixin);
+GPBObjCClassDeclaration(GPBOption);
+GPBObjCClassDeclaration(GPBSourceContext);
#pragma mark - GPBApiRoot
@@ -82,16 +92,16 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBApi_FieldNumber_Name,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBApi__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "methodsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBMethod),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBMethod),
.number = GPBApi_FieldNumber_MethodsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBApi__storage_, methodsArray),
@@ -100,7 +110,7 @@
},
{
.name = "optionsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBOption),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBOption),
.number = GPBApi_FieldNumber_OptionsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBApi__storage_, optionsArray),
@@ -109,16 +119,16 @@
},
{
.name = "version",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBApi_FieldNumber_Version,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBApi__storage_, version),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "sourceContext",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBSourceContext),
.number = GPBApi_FieldNumber_SourceContext,
.hasIndex = 2,
.offset = (uint32_t)offsetof(GPBApi__storage_, sourceContext),
@@ -127,7 +137,7 @@
},
{
.name = "mixinsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBMixin),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBMixin),
.number = GPBApi_FieldNumber_MixinsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBApi__storage_, mixinsArray),
@@ -140,7 +150,7 @@
.number = GPBApi_FieldNumber_Syntax,
.hasIndex = 3,
.offset = (uint32_t)offsetof(GPBApi__storage_, syntax),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeEnum,
},
};
@@ -151,7 +161,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBApi__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -165,13 +175,13 @@
int32_t GPBApi_Syntax_RawValue(GPBApi *message) {
GPBDescriptor *descriptor = [GPBApi descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBApi_FieldNumber_Syntax];
- return GPBGetMessageInt32Field(message, field);
+ return GPBGetMessageRawEnumField(message, field);
}
void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value) {
GPBDescriptor *descriptor = [GPBApi descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBApi_FieldNumber_Syntax];
- GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);
+ GPBSetMessageRawEnumField(message, field, value);
}
#pragma mark - GPBMethod
@@ -203,52 +213,52 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBMethod_FieldNumber_Name,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBMethod__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "requestTypeURL",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBMethod_FieldNumber_RequestTypeURL,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBMethod__storage_, requestTypeURL),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "requestStreaming",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBMethod_FieldNumber_RequestStreaming,
.hasIndex = 2,
.offset = 3, // Stored in _has_storage_ to save space.
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeBool,
},
{
.name = "responseTypeURL",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBMethod_FieldNumber_ResponseTypeURL,
.hasIndex = 4,
.offset = (uint32_t)offsetof(GPBMethod__storage_, responseTypeURL),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "responseStreaming",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBMethod_FieldNumber_ResponseStreaming,
.hasIndex = 5,
.offset = 6, // Stored in _has_storage_ to save space.
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeBool,
},
{
.name = "optionsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBOption),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBOption),
.number = GPBMethod_FieldNumber_OptionsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBMethod__storage_, optionsArray),
@@ -261,7 +271,7 @@
.number = GPBMethod_FieldNumber_Syntax,
.hasIndex = 7,
.offset = (uint32_t)offsetof(GPBMethod__storage_, syntax),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeEnum,
},
};
@@ -272,7 +282,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBMethod__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS
static const char *extraTextFormatInfo =
"\002\002\007\244\241!!\000\004\010\244\241!!\000";
@@ -291,13 +301,13 @@
int32_t GPBMethod_Syntax_RawValue(GPBMethod *message) {
GPBDescriptor *descriptor = [GPBMethod descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBMethod_FieldNumber_Syntax];
- return GPBGetMessageInt32Field(message, field);
+ return GPBGetMessageRawEnumField(message, field);
}
void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value) {
GPBDescriptor *descriptor = [GPBMethod descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBMethod_FieldNumber_Syntax];
- GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);
+ GPBSetMessageRawEnumField(message, field, value);
}
#pragma mark - GPBMixin
@@ -321,20 +331,20 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBMixin_FieldNumber_Name,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBMixin__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "root",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBMixin_FieldNumber_Root,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBMixin__storage_, root),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
};
@@ -345,7 +355,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBMixin__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBArray.h b/objectivec/GPBArray.h
index 3d22cb8..5aea75c 100644
--- a/objectivec/GPBArray.h
+++ b/objectivec/GPBArray.h
@@ -36,6 +36,7 @@
//%PDDM-EXPAND DECLARE_ARRAYS()
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int32
@@ -1535,6 +1536,7 @@
@end
+// clang-format on
//%PDDM-EXPAND-END DECLARE_ARRAYS()
NS_ASSUME_NONNULL_END
diff --git a/objectivec/GPBArray.m b/objectivec/GPBArray.m
index 5ce1e59..bb9a077 100644
--- a/objectivec/GPBArray.m
+++ b/objectivec/GPBArray.m
@@ -295,6 +295,7 @@
//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int32, int32_t, %d)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int32
@@ -541,8 +542,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt32, uint32_t, %u)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - UInt32
@@ -789,8 +792,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int64, int64_t, %lld)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int64
@@ -1037,8 +1042,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt64, uint64_t, %llu)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - UInt64
@@ -1285,8 +1292,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Float, float, %f)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Float
@@ -1533,8 +1542,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Double, double, %lf)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Double
@@ -1781,8 +1792,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Bool, BOOL, %d)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool
@@ -2029,6 +2042,7 @@
@end
+// clang-format on
//%PDDM-EXPAND-END (7 expansions)
#pragma mark - Enum
@@ -2126,6 +2140,7 @@
//%PDDM-EXPAND ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)dealloc {
NSAssert(!_autocreator,
@@ -2185,17 +2200,20 @@
}
}
}
+// clang-format on
//%PDDM-EXPAND-END ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d)
- (int32_t)valueAtIndex:(NSUInteger)index {
//%PDDM-EXPAND VALIDATE_RANGE(index, _count)
// This block of code is generated, do not edit it directly.
+// clang-format off
if (index >= _count) {
[NSException raise:NSRangeException
format:@"Index (%lu) beyond bounds (%lu)",
(unsigned long)index, (unsigned long)_count];
}
+// clang-format on
//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count)
int32_t result = _values[index];
if (!_validationFunc(result)) {
@@ -2207,12 +2225,14 @@
- (int32_t)rawValueAtIndex:(NSUInteger)index {
//%PDDM-EXPAND VALIDATE_RANGE(index, _count)
// This block of code is generated, do not edit it directly.
+// clang-format off
if (index >= _count) {
[NSException raise:NSRangeException
format:@"Index (%lu) beyond bounds (%lu)",
(unsigned long)index, (unsigned long)_count];
}
+// clang-format on
//%PDDM-EXPAND-END VALIDATE_RANGE(index, _count)
return _values[index];
}
@@ -2253,6 +2273,7 @@
//%PDDM-EXPAND ARRAY_MUTABLE_CORE(Enum, int32_t, Raw, %d)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)internalResizeToCapacity:(NSUInteger)newCapacity {
_values = reallocf(_values, newCapacity * sizeof(int32_t));
@@ -2358,8 +2379,10 @@
_values[idx2] = temp;
}
+// clang-format on
//%PDDM-EXPAND MUTATION_METHODS(Enum, int32_t, , EnumValidationList, EnumValidationOne)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)addValue:(int32_t)value {
[self addValues:&value count:1];
@@ -2426,6 +2449,7 @@
}
_values[index] = value;
}
+// clang-format on
//%PDDM-EXPAND-END (2 expansions)
//%PDDM-DEFINE MUTATION_HOOK_EnumValidationList()
diff --git a/objectivec/GPBArray_PackagePrivate.h b/objectivec/GPBArray_PackagePrivate.h
index 35a4538..07eab89 100644
--- a/objectivec/GPBArray_PackagePrivate.h
+++ b/objectivec/GPBArray_PackagePrivate.h
@@ -54,6 +54,7 @@
//%PDDM-EXPAND DECLARE_ARRAY_EXTRAS()
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int32
@@ -119,6 +120,7 @@
}
@end
+// clang-format on
//%PDDM-EXPAND-END DECLARE_ARRAY_EXTRAS()
#pragma mark - NSArray Subclass
diff --git a/objectivec/GPBBootstrap.h b/objectivec/GPBBootstrap.h
index 0ebca25..ea5986b 100644
--- a/objectivec/GPBBootstrap.h
+++ b/objectivec/GPBBootstrap.h
@@ -46,7 +46,7 @@
#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++
+// where the definition 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
// doesn't allow us to forward declare. We work around this one case by
// providing a local definition. The default case has to use NS_ENUM for the
@@ -115,6 +115,11 @@
// Meant to be used internally by generated code.
#define GPB_METHOD_FAMILY_NONE __attribute__((objc_method_family(none)))
+// Prevent subclassing of generated proto classes.
+#ifndef GPB_FINAL
+#define GPB_FINAL __attribute__((objc_subclassing_restricted))
+#endif // GPB_FINAL
+
// ----------------------------------------------------------------------------
// These version numbers are all internal to the ObjC Protobuf runtime; they
// are used to ensure compatibility between the generated sources and the
@@ -127,7 +132,7 @@
// 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
+#define GOOGLE_PROTOBUF_OBJC_VERSION 30004
// Minimum runtime version supported for compiling/running against.
// - Gets changed when support for the older generated code is dropped.
diff --git a/objectivec/GPBCodedOutputStream.h b/objectivec/GPBCodedOutputStream.h
index 23c404b..5dde974 100644
--- a/objectivec/GPBCodedOutputStream.h
+++ b/objectivec/GPBCodedOutputStream.h
@@ -177,6 +177,7 @@
//%PDDM-EXPAND _WRITE_DECLS()
// This block of code is generated, do not edit it directly.
+// clang-format off
/**
* Write a double for the given field number.
@@ -527,7 +528,8 @@
* @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;
+- (void)writeStringArray:(int32_t)fieldNumber
+ values:(NSArray<NSString*> *)values;
/**
* Write a NSString without any tag.
*
@@ -548,7 +550,8 @@
* @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;
+- (void)writeMessageArray:(int32_t)fieldNumber
+ values:(NSArray<GPBMessage*> *)values;
/**
* Write a GPBMessage without any tag.
*
@@ -569,7 +572,8 @@
* @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;
+- (void)writeBytesArray:(int32_t)fieldNumber
+ values:(NSArray<NSData*> *)values;
/**
* Write a NSData without any tag.
*
@@ -591,7 +595,8 @@
* @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;
+- (void)writeGroupArray:(int32_t)fieldNumber
+ values:(NSArray<GPBMessage*> *)values;
/**
* Write a GPBMessage without any tag (but does write the endGroup tag).
*
@@ -615,7 +620,8 @@
* @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;
+- (void)writeUnknownGroupArray:(int32_t)fieldNumber
+ values:(NSArray<GPBUnknownFieldSet*> *)values;
/**
* Write a GPBUnknownFieldSet without any tag (but does write the endGroup tag).
*
@@ -625,6 +631,7 @@
- (void)writeUnknownGroupNoTag:(int32_t)fieldNumber
value:(GPBUnknownFieldSet *)value;
+// clang-format on
//%PDDM-EXPAND-END _WRITE_DECLS()
/**
@@ -690,7 +697,8 @@
//% * @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;
+//%- (void)write##NAME##Array:(int32_t)fieldNumber
+//% NAME$S values:(NSArray<##TYPE##*> *)values;
//%/**
//% * Write a TYPE without any tag.
//% *
@@ -714,7 +722,8 @@
//% * @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;
+//%- (void)write##NAME##Array:(int32_t)fieldNumber
+//% NAME$S values:(NSArray<##TYPE##*> *)values;
//%/**
//% * Write a TYPE without any tag (but does write the endGroup tag).
//% *
diff --git a/objectivec/GPBCodedOutputStream.m b/objectivec/GPBCodedOutputStream.m
index 0693906..4e2a514 100644
--- a/objectivec/GPBCodedOutputStream.m
+++ b/objectivec/GPBCodedOutputStream.m
@@ -452,6 +452,7 @@
//%
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Double, Double, double, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeDoubleArray:(int32_t)fieldNumber
values:(GPBDoubleArray *)values
@@ -477,8 +478,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Float, Float, float, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeFloatArray:(int32_t)fieldNumber
values:(GPBFloatArray *)values
@@ -504,8 +507,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt64, UInt64, uint64_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeUInt64Array:(int32_t)fieldNumber
values:(GPBUInt64Array *)values
@@ -531,8 +536,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int64, Int64, int64_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeInt64Array:(int32_t)fieldNumber
values:(GPBInt64Array *)values
@@ -558,8 +565,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int32, Int32, int32_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeInt32Array:(int32_t)fieldNumber
values:(GPBInt32Array *)values
@@ -585,8 +594,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt32, UInt32, uint32_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeUInt32Array:(int32_t)fieldNumber
values:(GPBUInt32Array *)values
@@ -612,8 +623,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed64, UInt64, uint64_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeFixed64Array:(int32_t)fieldNumber
values:(GPBUInt64Array *)values
@@ -639,8 +652,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed32, UInt32, uint32_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeFixed32Array:(int32_t)fieldNumber
values:(GPBUInt32Array *)values
@@ -666,8 +681,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt32, Int32, int32_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeSInt32Array:(int32_t)fieldNumber
values:(GPBInt32Array *)values
@@ -693,8 +710,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt64, Int64, int64_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeSInt64Array:(int32_t)fieldNumber
values:(GPBInt64Array *)values
@@ -720,8 +739,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed64, Int64, int64_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeSFixed64Array:(int32_t)fieldNumber
values:(GPBInt64Array *)values
@@ -747,8 +768,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed32, Int32, int32_t, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeSFixed32Array:(int32_t)fieldNumber
values:(GPBInt32Array *)values
@@ -774,8 +797,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Bool, Bool, BOOL, )
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeBoolArray:(int32_t)fieldNumber
values:(GPBBoolArray *)values
@@ -801,8 +826,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Enum, Enum, int32_t, Raw)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeEnumArray:(int32_t)fieldNumber
values:(GPBEnumArray *)values
@@ -828,8 +855,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(String, NSString)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeStringArray:(int32_t)fieldNumber values:(NSArray *)values {
for (NSString *value in values) {
@@ -837,8 +866,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Message, GPBMessage)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeMessageArray:(int32_t)fieldNumber values:(NSArray *)values {
for (GPBMessage *value in values) {
@@ -846,8 +877,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Bytes, NSData)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeBytesArray:(int32_t)fieldNumber values:(NSArray *)values {
for (NSData *value in values) {
@@ -855,8 +888,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Group, GPBMessage)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeGroupArray:(int32_t)fieldNumber values:(NSArray *)values {
for (GPBMessage *value in values) {
@@ -864,8 +899,10 @@
}
}
+// clang-format on
//%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(UnknownGroup, GPBUnknownFieldSet)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)writeUnknownGroupArray:(int32_t)fieldNumber values:(NSArray *)values {
for (GPBUnknownFieldSet *value in values) {
@@ -873,6 +910,7 @@
}
}
+// clang-format on
//%PDDM-EXPAND-END (19 expansions)
- (void)writeMessageSetExtension:(int32_t)fieldNumber
diff --git a/objectivec/GPBDescriptor.m b/objectivec/GPBDescriptor.m
index 41bf5ad..c29b955 100644
--- a/objectivec/GPBDescriptor.m
+++ b/objectivec/GPBDescriptor.m
@@ -44,7 +44,7 @@
// 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 kParentClassValueKey = 0;
static const char kClassNameSuffixKey = 0;
// Utility function to generate selectors on the fly.
@@ -126,6 +126,10 @@
GPBFileSyntax syntax = file.syntax;
BOOL fieldsIncludeDefault =
(flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0;
+ BOOL usesClassRefs =
+ (flags & GPBDescriptorInitializationFlag_UsesClassRefs) != 0;
+ BOOL proto3OptionalKnown =
+ (flags & GPBDescriptorInitializationFlag_Proto3OptionalKnown) != 0;
void *desc;
for (uint32_t i = 0; i < fieldCount; ++i) {
@@ -143,6 +147,8 @@
GPBFieldDescriptor *fieldDescriptor =
[[GPBFieldDescriptor alloc] initWithFieldDescription:desc
includesDefault:fieldsIncludeDefault
+ usesClassRefs:usesClassRefs
+ proto3OptionalKnown:proto3OptionalKnown
syntax:syntax];
[fields addObject:fieldDescriptor];
[fieldDescriptor release];
@@ -217,15 +223,19 @@
extensionRangesCount_ = count;
}
+- (void)setupContainingMessageClass:(Class)messageClass {
+ objc_setAssociatedObject(self, &kParentClassValueKey,
+ messageClass,
+ OBJC_ASSOCIATION_ASSIGN);
+}
+
- (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);
+ Class clazz = objc_getClass(msgClassName);
+ NSAssert(clazz, @"Class %s not defined", msgClassName);
+ [self setupContainingMessageClass:clazz];
}
- (void)setupMessageClassNameSuffix:(NSString *)suffix {
@@ -241,14 +251,7 @@
}
- (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);
+ Class parentClass = objc_getAssociatedObject(self, &kParentClassValueKey);
return [parentClass descriptor];
}
@@ -487,6 +490,8 @@
- (instancetype)initWithFieldDescription:(void *)description
includesDefault:(BOOL)includesDefault
+ usesClassRefs:(BOOL)usesClassRefs
+ proto3OptionalKnown:(BOOL)proto3OptionalKnown
syntax:(GPBFileSyntax)syntax {
if ((self = [super init])) {
GPBMessageFieldDescription *coreDesc;
@@ -503,20 +508,34 @@
BOOL isMessage = GPBDataTypeIsMessage(dataType);
BOOL isMapOrArray = GPBFieldIsMapOrArray(self);
+ // If proto3 optionals weren't known (i.e. generated code from an
+ // older version), compute the flag for the rest of the runtime.
+ if (!proto3OptionalKnown) {
+ // If it was...
+ // - proto3 syntax
+ // - not repeated/map
+ // - not in a oneof (negative has index)
+ // - not a message (the flag doesn't make sense for messages)
+ BOOL clearOnZero = ((syntax == GPBFileSyntaxProto3) &&
+ !isMapOrArray &&
+ (coreDesc->hasIndex >= 0) &&
+ !isMessage);
+ if (clearOnZero) {
+ coreDesc->flags |= GPBFieldClearHasIvarOnZero;
+ }
+ }
+
if (isMapOrArray) {
// map<>/repeated fields get a *Count property (inplace of a has*) to
// support checking if there are any entries without triggering
// autocreation.
hasOrCountSel_ = SelFromStrings(NULL, coreDesc->name, "_Count", NO);
} else {
- // If there is a positive hasIndex, then:
- // - All fields types for proto2 messages get has* selectors.
- // - Only message fields for proto3 messages get has* selectors.
- // Note: the positive check is to handle oneOfs, we can't check
- // containingOneof_ because it isn't set until after initialization.
+ // It is a single field; it gets has/setHas selectors if...
+ // - not in a oneof (negative has index)
+ // - not clearing on zero
if ((coreDesc->hasIndex >= 0) &&
- (coreDesc->hasIndex != GPBNoHasBit) &&
- ((syntax != GPBFileSyntaxProto3) || isMessage)) {
+ ((coreDesc->flags & GPBFieldClearHasIvarOnZero) == 0)) {
hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO);
setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES);
}
@@ -524,12 +543,17 @@
// 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);
+ if (usesClassRefs) {
+ msgClass_ = coreDesc->dataTypeSpecific.clazz;
+ } else {
+ // Backwards compatibility for sources generated with older protoc.
+ const char *className = coreDesc->dataTypeSpecific.className;
+ msgClass_ = objc_getClass(className);
+ NSAssert(msgClass_, @"Class %s not defined", className);
+ }
} else if (dataType == GPBDataTypeEnum) {
if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) {
enumHandling_.enumDescriptor_ =
@@ -957,33 +981,32 @@
GPBGenericValue defaultValue_;
}
-@synthesize containingMessageClass = containingMessageClass_;
-
-- (instancetype)initWithExtensionDescription:
- (GPBExtensionDescription *)description {
+- (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc
+ usesClassRefs:(BOOL)usesClassRefs {
if ((self = [super init])) {
- description_ = description;
+ description_ = desc;
+ if (!usesClassRefs) {
+ // Legacy without class ref support.
+ const char *className = description_->messageOrGroupClass.name;
+ if (className) {
+ Class clazz = objc_lookUpClass(className);
+ NSAssert(clazz != Nil, @"Class %s not defined", className);
+ description_->messageOrGroupClass.clazz = clazz;
+ }
-#if defined(DEBUG) && DEBUG
- const char *className = description->messageOrGroupClassName;
- if (className) {
- NSAssert(objc_lookUpClass(className) != Nil,
- @"Class %s not defined", className);
- }
-#endif
-
- if (description->extendedClass) {
- Class containingClass = objc_lookUpClass(description->extendedClass);
- NSAssert(containingClass, @"Class %s not defined",
- description->extendedClass);
- containingMessageClass_ = containingClass;
+ const char *extendedClassName = description_->extendedClass.name;
+ if (extendedClassName) {
+ Class clazz = objc_lookUpClass(extendedClassName);
+ NSAssert(clazz, @"Class %s not defined", extendedClassName);
+ description_->extendedClass.clazz = clazz;
+ }
}
GPBDataType type = description_->dataType;
if (type == GPBDataTypeBytes) {
// Data stored as a length prefixed c-string in descriptor records.
const uint8_t *bytes =
- (const uint8_t *)description->defaultValue.valueData;
+ (const uint8_t *)description_->defaultValue.valueData;
if (bytes) {
uint32_t length;
memcpy(&length, bytes, sizeof(length));
@@ -998,12 +1021,16 @@
// aren't common, we avoid the hit startup hit and it avoid initialization
// order issues.
} else {
- defaultValue_ = description->defaultValue;
+ defaultValue_ = description_->defaultValue;
}
}
return self;
}
+- (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc {
+ return [self initWithExtensionDescription:desc usesClassRefs:NO];
+}
+
- (void)dealloc {
if ((description_->dataType == GPBDataTypeBytes) &&
!GPBExtensionIsRepeated(description_)) {
@@ -1055,7 +1082,11 @@
}
- (Class)msgClass {
- return objc_getClass(description_->messageOrGroupClassName);
+ return description_->messageOrGroupClass.clazz;
+}
+
+- (Class)containingMessageClass {
+ return description_->extendedClass.clazz;
}
- (GPBEnumDescriptor *)enumDescriptor {
diff --git a/objectivec/GPBDescriptor_PackagePrivate.h b/objectivec/GPBDescriptor_PackagePrivate.h
index 452b3f8..b3d6730 100644
--- a/objectivec/GPBDescriptor_PackagePrivate.h
+++ b/objectivec/GPBDescriptor_PackagePrivate.h
@@ -45,6 +45,10 @@
GPBFieldOptional = 1 << 3,
GPBFieldHasDefaultValue = 1 << 4,
+ // Indicate that the field should "clear" when set to zero value. This is the
+ // proto3 non optional behavior for singular data (ints, data, string, enum)
+ // fields.
+ GPBFieldClearHasIvarOnZero = 1 << 5,
// Indicates the field needs custom handling for the TextFormat name, if not
// set, the name can be derived from the ObjC name.
GPBFieldTextFormatNameCustom = 1 << 6,
@@ -80,7 +84,11 @@
// Name of ivar.
const char *name;
union {
- const char *className; // Name for message class.
+ // className is deprecated and will be removed in favor of clazz.
+ // kept around right now for backwards compatibility.
+ // clazz is used iff GPBDescriptorInitializationFlag_UsesClassRefs is set.
+ char *className; // Name of the class of the message.
+ Class clazz; // Class of the message.
// For enums only: If EnumDescriptors are compiled in, it will be that,
// otherwise it will be the verifier.
GPBEnumDescriptorFunc enumDescFunc;
@@ -123,8 +131,14 @@
typedef struct GPBExtensionDescription {
GPBGenericValue defaultValue;
const char *singletonName;
- const char *extendedClass;
- const char *messageOrGroupClassName;
+ union {
+ const char *name;
+ Class clazz;
+ } extendedClass;
+ union {
+ const char *name;
+ Class clazz;
+ } messageOrGroupClass;
GPBEnumDescriptorFunc enumDescriptorFunc;
int32_t fieldNumber;
GPBDataType dataType;
@@ -135,6 +149,17 @@
GPBDescriptorInitializationFlag_None = 0,
GPBDescriptorInitializationFlag_FieldsWithDefault = 1 << 0,
GPBDescriptorInitializationFlag_WireFormat = 1 << 1,
+
+ // This is used as a stopgap as we move from using class names to class
+ // references. The runtime needs to support both until we allow a
+ // breaking change in the runtime.
+ GPBDescriptorInitializationFlag_UsesClassRefs = 1 << 2,
+
+ // This flag is used to indicate that the generated sources already contain
+ // the `GPBFieldClearHasIvarOnZero` flag and it doesn't have to be computed
+ // at startup. This allows older generated code to still work with the
+ // current runtime library.
+ GPBDescriptorInitializationFlag_Proto3OptionalKnown = 1 << 3,
};
@interface GPBDescriptor () {
@@ -168,9 +193,12 @@
firstHasIndex:(int32_t)firstHasIndex;
- (void)setupExtraTextInfo:(const char *)extraTextFormatInfo;
- (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count;
-- (void)setupContainingMessageClassName:(const char *)msgClassName;
+- (void)setupContainingMessageClass:(Class)msgClass;
- (void)setupMessageClassNameSuffix:(NSString *)suffix;
+// Deprecated. Use setupContainingMessageClass instead.
+- (void)setupContainingMessageClassName:(const char *)msgClassName;
+
@end
@interface GPBFileDescriptor ()
@@ -206,7 +234,10 @@
// description has to be long lived, it is held as a raw pointer.
- (instancetype)initWithFieldDescription:(void *)description
includesDefault:(BOOL)includesDefault
+ usesClassRefs:(BOOL)usesClassRefs
+ proto3OptionalKnown:(BOOL)proto3OptionalKnown
syntax:(GPBFileSyntax)syntax;
+
@end
@interface GPBEnumDescriptor ()
@@ -246,8 +277,11 @@
@property(nonatomic, readonly) GPBWireFormat alternateWireType;
// description has to be long lived, it is held as a raw pointer.
-- (instancetype)initWithExtensionDescription:
- (GPBExtensionDescription *)description;
+- (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc
+ usesClassRefs:(BOOL)usesClassRefs;
+// Deprecated. Calls above with `usesClassRefs = NO`
+- (instancetype)initWithExtensionDescription:(GPBExtensionDescription *)desc;
+
- (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other;
@end
diff --git a/objectivec/GPBDictionary.h b/objectivec/GPBDictionary.h
index d00b5b3..28d880d 100644
--- a/objectivec/GPBDictionary.h
+++ b/objectivec/GPBDictionary.h
@@ -45,6 +45,7 @@
//%PDDM-EXPAND DECLARE_DICTIONARIES()
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - UInt32 -> UInt32
@@ -5478,6 +5479,7 @@
@end
+// clang-format on
//%PDDM-EXPAND-END DECLARE_DICTIONARIES()
NS_ASSUME_NONNULL_END
diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m
index 1bb24be..187a970 100644
--- a/objectivec/GPBDictionary.m
+++ b/objectivec/GPBDictionary.m
@@ -147,6 +147,7 @@
//%SERIALIZE_SUPPORT_3_TYPE(Object, id, Message, String, Bytes)
//%PDDM-EXPAND SERIALIZE_SUPPORT_HELPERS()
// This block of code is generated, do not edit it directly.
+// clang-format off
static size_t ComputeDictInt32FieldSize(int32_t value, uint32_t fieldNum, GPBDataType dataType) {
if (dataType == GPBDataTypeInt32) {
@@ -325,6 +326,7 @@
}
}
+// clang-format on
//%PDDM-EXPAND-END SERIALIZE_SUPPORT_HELPERS()
size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) {
@@ -508,7 +510,7 @@
#if defined(__clang_analyzer__)
case GPBDataTypeGroup:
// Maps can't really have Groups as the value type, but this case is needed
- // so the analyzer won't report the posibility of send nil in for the value
+ // so the analyzer won't report the possibility of send nil in for the value
// in the NSMutableDictionary case below.
#endif
case GPBDataTypeMessage: {
@@ -1427,6 +1429,7 @@
//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt32, uint32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - UInt32 -> UInt32
@@ -3173,8 +3176,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int32, int32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int32 -> UInt32
@@ -4921,8 +4926,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt64, uint64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - UInt64 -> UInt32
@@ -6669,8 +6676,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int64, int64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int64 -> UInt32
@@ -8417,8 +8426,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_POD_IMPL_FOR_KEY(String, NSString, *, OBJECT)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - String -> UInt32
@@ -10021,11 +10032,13 @@
@end
+// clang-format on
//%PDDM-EXPAND-END (5 expansions)
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt32, uint32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> UInt32
@@ -10233,8 +10246,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int32, int32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Int32
@@ -10442,8 +10457,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt64, uint64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> UInt64
@@ -10651,8 +10668,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int64, int64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Int64
@@ -10860,8 +10879,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Bool, BOOL)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Bool
@@ -11069,8 +11090,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Float, float)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Float
@@ -11278,8 +11301,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Double, double)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Double
@@ -11487,8 +11512,10 @@
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_OBJECT_IMPL(Object, id)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Object
@@ -11717,6 +11744,7 @@
@end
+// clang-format on
//%PDDM-EXPAND-END (8 expansions)
#pragma mark - Bool -> Enum
@@ -11890,6 +11918,7 @@
//%PDDM-EXPAND SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (NSData *)serializedDataForUnknownValue:(int32_t)value
forKey:(GPBGenericValue *)key
@@ -11904,6 +11933,7 @@
return data;
}
+// clang-format on
//%PDDM-EXPAND-END SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool)
- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field {
diff --git a/objectivec/GPBDictionary_PackagePrivate.h b/objectivec/GPBDictionary_PackagePrivate.h
index 7b921e8..15e4283 100644
--- a/objectivec/GPBDictionary_PackagePrivate.h
+++ b/objectivec/GPBDictionary_PackagePrivate.h
@@ -82,6 +82,7 @@
//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt32)
// This block of code is generated, do not edit it directly.
+// clang-format off
@interface GPBUInt32UInt32Dictionary () <GPBDictionaryInternalsProtocol> {
@package
@@ -143,8 +144,10 @@
__attribute__((ns_returns_retained));
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int32)
// This block of code is generated, do not edit it directly.
+// clang-format off
@interface GPBInt32UInt32Dictionary () <GPBDictionaryInternalsProtocol> {
@package
@@ -206,8 +209,10 @@
__attribute__((ns_returns_retained));
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt64)
// This block of code is generated, do not edit it directly.
+// clang-format off
@interface GPBUInt64UInt32Dictionary () <GPBDictionaryInternalsProtocol> {
@package
@@ -269,8 +274,10 @@
__attribute__((ns_returns_retained));
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int64)
// This block of code is generated, do not edit it directly.
+// clang-format off
@interface GPBInt64UInt32Dictionary () <GPBDictionaryInternalsProtocol> {
@package
@@ -332,8 +339,10 @@
__attribute__((ns_returns_retained));
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Bool)
// This block of code is generated, do not edit it directly.
+// clang-format off
@interface GPBBoolUInt32Dictionary () <GPBDictionaryInternalsProtocol> {
@package
@@ -395,8 +404,10 @@
__attribute__((ns_returns_retained));
@end
+// clang-format on
//%PDDM-EXPAND DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(String)
// This block of code is generated, do not edit it directly.
+// clang-format off
@interface GPBStringUInt32Dictionary () <GPBDictionaryInternalsProtocol> {
@package
@@ -449,6 +460,7 @@
keyDataType:(GPBDataType)keyDataType;
@end
+// clang-format on
//%PDDM-EXPAND-END (6 expansions)
#pragma mark - NSDictionary Subclass
diff --git a/objectivec/GPBDuration.pbobjc.h b/objectivec/GPBDuration.pbobjc.h
new file mode 100644
index 0000000..88527f5
--- /dev/null
+++ b/objectivec/GPBDuration.pbobjc.h
@@ -0,0 +1,145 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/duration.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+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.
+ **/
+GPB_FINAL @interface GPBDurationRoot : GPBRootObject
+@end
+
+#pragma mark - GPBDuration
+
+typedef GPB_ENUM(GPBDuration_FieldNumber) {
+ GPBDuration_FieldNumber_Seconds = 1,
+ 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.
+ *
+ * # Examples
+ *
+ * Example 1: Compute Duration from two Timestamps in pseudo code.
+ *
+ * Timestamp start = ...;
+ * Timestamp end = ...;
+ * Duration duration = ...;
+ *
+ * duration.seconds = end.seconds - start.seconds;
+ * duration.nanos = end.nanos - start.nanos;
+ *
+ * if (duration.seconds < 0 && duration.nanos > 0) {
+ * duration.seconds += 1;
+ * duration.nanos -= 1000000000;
+ * } else if (duration.seconds > 0 && duration.nanos < 0) {
+ * duration.seconds -= 1;
+ * duration.nanos += 1000000000;
+ * }
+ *
+ * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+ *
+ * Timestamp start = ...;
+ * Duration duration = ...;
+ * Timestamp end = ...;
+ *
+ * end.seconds = start.seconds + duration.seconds;
+ * end.nanos = start.nanos + duration.nanos;
+ *
+ * if (end.nanos < 0) {
+ * end.seconds -= 1;
+ * end.nanos += 1000000000;
+ * } else if (end.nanos >= 1000000000) {
+ * end.seconds += 1;
+ * end.nanos -= 1000000000;
+ * }
+ *
+ * Example 3: Compute Duration from datetime.timedelta in Python.
+ *
+ * td = datetime.timedelta(days=3, minutes=10)
+ * duration = Duration()
+ * duration.FromTimedelta(td)
+ *
+ * # JSON Mapping
+ *
+ * In JSON format, the Duration type is encoded as a string rather than an
+ * object, where the string ends in the suffix "s" (indicating seconds) and
+ * is preceded by the number of seconds, with nanoseconds expressed as
+ * fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+ * encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+ * be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+ * microsecond should be expressed in JSON format as "3.000001s".
+ **/
+GPB_FINAL @interface GPBDuration : GPBMessage
+
+/**
+ * Signed seconds of the span of time. Must be from -315,576,000,000
+ * to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ **/
+@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.
+ **/
+@property(nonatomic, readwrite) int32_t nanos;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Duration.pbobjc.m b/objectivec/GPBDuration.pbobjc.m
similarity index 84%
rename from objectivec/google/protobuf/Duration.pbobjc.m
rename to objectivec/GPBDuration.pbobjc.m
index 1b718a1..d3cc7e3 100644
--- a/objectivec/google/protobuf/Duration.pbobjc.m
+++ b/objectivec/GPBDuration.pbobjc.m
@@ -8,15 +8,15 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Duration.pbobjc.h>
+ #import <Protobuf/GPBDuration.pbobjc.h>
#else
- #import "google/protobuf/Duration.pbobjc.h"
+ #import "GPBDuration.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
@@ -68,20 +68,20 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "seconds",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBDuration_FieldNumber_Seconds,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBDuration__storage_, seconds),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt64,
},
{
.name = "nanos",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBDuration_FieldNumber_Nanos,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBDuration__storage_, nanos),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt32,
},
};
@@ -92,7 +92,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBDuration__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBEmpty.pbobjc.h b/objectivec/GPBEmpty.pbobjc.h
new file mode 100644
index 0000000..45600ea
--- /dev/null
+++ b/objectivec/GPBEmpty.pbobjc.h
@@ -0,0 +1,74 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/empty.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+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.
+ **/
+GPB_FINAL @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 `{}`.
+ **/
+GPB_FINAL @interface GPBEmpty : GPBMessage
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Empty.pbobjc.m b/objectivec/GPBEmpty.pbobjc.m
similarity index 88%
rename from objectivec/google/protobuf/Empty.pbobjc.m
rename to objectivec/GPBEmpty.pbobjc.m
index 4cb0f12..df3e398 100644
--- a/objectivec/google/protobuf/Empty.pbobjc.m
+++ b/objectivec/GPBEmpty.pbobjc.m
@@ -8,15 +8,15 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Empty.pbobjc.h>
+ #import <Protobuf/GPBEmpty.pbobjc.h>
#else
- #import "google/protobuf/Empty.pbobjc.h"
+ #import "GPBEmpty.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
@@ -68,7 +68,7 @@
fields:NULL
fieldCount:0
storageSize:sizeof(GPBEmpty__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBFieldMask.pbobjc.h b/objectivec/GPBFieldMask.pbobjc.h
new file mode 100644
index 0000000..3028b77
--- /dev/null
+++ b/objectivec/GPBFieldMask.pbobjc.h
@@ -0,0 +1,273 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/field_mask.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+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.
+ **/
+GPB_FINAL @interface GPBFieldMaskRoot : GPBRootObject
+@end
+
+#pragma mark - GPBFieldMask
+
+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
+ * 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, new values will
+ * be appended to the existing repeated field in the target resource. Note that
+ * a repeated field is only allowed in the last position of a `paths` string.
+ *
+ * If a sub-message is specified in the last position of the field mask for an
+ * update operation, then new value will be merged into the existing sub-message
+ * in the target resource.
+ *
+ * For example, given the target message:
+ *
+ * f {
+ * b {
+ * d: 1
+ * x: 2
+ * }
+ * c: [1]
+ * }
+ *
+ * And an update message:
+ *
+ * f {
+ * b {
+ * d: 10
+ * }
+ * c: [2]
+ * }
+ *
+ * then if the field mask is:
+ *
+ * paths: ["f.b", "f.c"]
+ *
+ * then the result will be:
+ *
+ * f {
+ * b {
+ * d: 10
+ * x: 2
+ * }
+ * c: [1, 2]
+ * }
+ *
+ * An implementation may provide options to override this default behavior for
+ * repeated and message fields.
+ *
+ * In order to reset a field's value to the default, the field must
+ * be in the mask and set to the default value in the provided resource.
+ * 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.
+ *
+ * ## Field Mask Verification
+ *
+ * The implementation of any API method which has a FieldMask type field in the
+ * request should verify the included field paths, and return an
+ * `INVALID_ARGUMENT` error if any path is unmappable.
+ **/
+GPB_FINAL @interface GPBFieldMask : GPBMessage
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger pathsArray_Count;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.m b/objectivec/GPBFieldMask.pbobjc.m
similarity index 88%
rename from objectivec/google/protobuf/FieldMask.pbobjc.m
rename to objectivec/GPBFieldMask.pbobjc.m
index 2e6b2ee..3605f89 100644
--- a/objectivec/google/protobuf/FieldMask.pbobjc.m
+++ b/objectivec/GPBFieldMask.pbobjc.m
@@ -8,15 +8,15 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/FieldMask.pbobjc.h>
+ #import <Protobuf/GPBFieldMask.pbobjc.h>
#else
- #import "google/protobuf/FieldMask.pbobjc.h"
+ #import "GPBFieldMask.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
@@ -66,7 +66,7 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "pathsArray",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBFieldMask_FieldNumber_PathsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBFieldMask__storage_, pathsArray),
@@ -81,7 +81,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBFieldMask__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBMessage.m b/objectivec/GPBMessage.m
index 3d5eccd..8e6aaf1 100644
--- a/objectivec/GPBMessage.m
+++ b/objectivec/GPBMessage.m
@@ -99,15 +99,13 @@
GPBMessage *autocreator)
__attribute__((ns_returns_retained));
static id GetOrCreateArrayIvarWithField(GPBMessage *self,
- GPBFieldDescriptor *field,
- GPBFileSyntax syntax);
+ GPBFieldDescriptor *field);
static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static id CreateMapForField(GPBFieldDescriptor *field,
GPBMessage *autocreator)
__attribute__((ns_returns_retained));
static id GetOrCreateMapIvarWithField(GPBMessage *self,
- GPBFieldDescriptor *field,
- GPBFileSyntax syntax);
+ GPBFieldDescriptor *field);
static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap,
NSZone *zone)
@@ -560,25 +558,24 @@
#if !defined(__clang_analyzer__)
// These functions are blocked from the analyzer because the analyzer sees the
-// GPBSetRetainedObjectIvarWithFieldInternal() call as consuming the array/map,
+// GPBSetRetainedObjectIvarWithFieldPrivate() call as consuming the array/map,
// so use of the array/map after the call returns is flagged as a use after
// free.
-// But GPBSetRetainedObjectIvarWithFieldInternal() is "consuming" the retain
-// count be holding onto the object (it is transfering it), the object is
+// But GPBSetRetainedObjectIvarWithFieldPrivate() is "consuming" the retain
+// count be holding onto the object (it is transferring it), the object is
// still valid after returning from the call. The other way to avoid this
// would be to add a -retain/-autorelease, but that would force every
// repeated/map field parsed into the autorelease pool which is both a memory
// and performance hit.
static id GetOrCreateArrayIvarWithField(GPBMessage *self,
- GPBFieldDescriptor *field,
- GPBFileSyntax syntax) {
+ GPBFieldDescriptor *field) {
id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (!array) {
// No lock needed, this is called from places expecting to mutate
// so no threading protection is needed.
array = CreateArrayForField(field, nil);
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, array, syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, array);
}
return array;
}
@@ -602,14 +599,13 @@
}
static id GetOrCreateMapIvarWithField(GPBMessage *self,
- GPBFieldDescriptor *field,
- GPBFileSyntax syntax) {
+ GPBFieldDescriptor *field) {
id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (!dict) {
// No lock needed, this is called from places expecting to mutate
// so no threading protection is needed.
dict = CreateMapForField(field, nil);
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, dict, syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, dict);
}
return dict;
}
@@ -668,9 +664,8 @@
// This will recursively make all parent messages visible until it reaches a
// super-creator that's visible.
if (self->autocreatorField_) {
- GPBFileSyntax syntax = [self->autocreator_ descriptor].file.syntax;
- GPBSetObjectIvarWithFieldInternal(self->autocreator_,
- self->autocreatorField_, self, syntax);
+ GPBSetObjectIvarWithFieldPrivate(self->autocreator_,
+ self->autocreatorField_, self);
} else {
[self->autocreator_ setExtension:self->autocreatorExtension_ value:self];
}
@@ -936,8 +931,6 @@
// Copy all the storage...
memcpy(message->messageStorage_, messageStorage_, descriptor->storageSize_);
- GPBFileSyntax syntax = descriptor.file.syntax;
-
// Loop over the fields doing fixup...
for (GPBFieldDescriptor *field in descriptor->fields_) {
if (GPBFieldIsMapOrArray(field)) {
@@ -1005,8 +998,7 @@
// We retain here because the memcpy picked up the pointer value and
// the next call to SetRetainedObject... will release the current value.
[value retain];
- GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue,
- syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(message, field, newValue);
}
} else if (GPBFieldDataTypeIsMessage(field)) {
// For object types, if we have a value, copy it. If we don't,
@@ -1018,8 +1010,7 @@
// We retain here because the memcpy picked up the pointer value and
// the next call to SetRetainedObject... will release the current value.
[value retain];
- GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue,
- syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(message, field, newValue);
} else {
uint8_t *storage = (uint8_t *)message->messageStorage_;
id *typePtr = (id *)&storage[field->description_->offset];
@@ -1033,8 +1024,7 @@
// We retain here because the memcpy picked up the pointer value and
// the next call to SetRetainedObject... will release the current value.
[value retain];
- GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue,
- syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(message, field, newValue);
} else {
// memcpy took care of the rest of the primitive fields if they were set.
}
@@ -1376,6 +1366,7 @@
//%PDDM-EXPAND FIELD_CASE(Bool, Bool)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeBool:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1394,8 +1385,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(Fixed32, UInt32)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeFixed32:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1414,8 +1407,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(SFixed32, Int32)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeSFixed32:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1434,8 +1429,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(Float, Float)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeFloat:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1454,8 +1451,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(Fixed64, UInt64)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeFixed64:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1474,8 +1473,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(SFixed64, Int64)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeSFixed64:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1494,8 +1495,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(Double, Double)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeDouble:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1514,8 +1517,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(Int32, Int32)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeInt32:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1534,8 +1539,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(Int64, Int64)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeInt64:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1554,8 +1561,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(SInt32, Int32)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeSInt32:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1574,8 +1583,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(SInt64, Int64)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeSInt64:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1594,8 +1605,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(UInt32, UInt32)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeUInt32:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1614,8 +1627,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE(UInt64, UInt64)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeUInt64:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1634,8 +1649,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE_FULL(Enum, Int32, Enum)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeEnum:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1654,8 +1671,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE2(Bytes)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeBytes:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1678,8 +1697,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE2(String)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeString:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1702,8 +1723,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE2(Message)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeMessage:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1726,8 +1749,10 @@
}
break;
+// clang-format on
//%PDDM-EXPAND FIELD_CASE2(Group)
// This block of code is generated, do not edit it directly.
+// clang-format off
case GPBDataTypeGroup:
if (fieldType == GPBFieldTypeRepeated) {
@@ -1750,6 +1775,7 @@
}
break;
+// clang-format on
//%PDDM-EXPAND-END (18 expansions)
}
}
@@ -2125,13 +2151,13 @@
#define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \
case GPBDataType##NAME: { \
TYPE val = GPBCodedInputStreamRead##NAME(&input->state_); \
- GPBSet##FUNC_TYPE##IvarWithFieldInternal(self, field, val, syntax); \
+ GPBSet##FUNC_TYPE##IvarWithFieldPrivate(self, field, val); \
break; \
}
#define CASE_SINGLE_OBJECT(NAME) \
case GPBDataType##NAME: { \
id val = GPBCodedInputStreamReadRetained##NAME(&input->state_); \
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, val, syntax); \
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, val); \
break; \
}
CASE_SINGLE_POD(Bool, BOOL, Bool)
@@ -2162,7 +2188,7 @@
} else {
GPBMessage *message = [[field.msgClass alloc] init];
[input readMessage:message extensionRegistry:extensionRegistry];
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, message);
}
break;
}
@@ -2181,7 +2207,7 @@
[input readGroup:GPBFieldNumber(field)
message:message
extensionRegistry:extensionRegistry];
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, message);
}
break;
}
@@ -2190,7 +2216,7 @@
int32_t val = GPBCodedInputStreamReadEnum(&input->state_);
if (GPBHasPreservingUnknownEnumSemantics(syntax) ||
[field isValidEnumValue:val]) {
- GPBSetInt32IvarWithFieldInternal(self, field, val, syntax);
+ GPBSetInt32IvarWithFieldPrivate(self, field, val);
} else {
GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self);
[unknownFields mergeVarintField:GPBFieldNumber(field) value:val];
@@ -2204,7 +2230,7 @@
GPBCodedInputStream *input) {
GPBDataType fieldDataType = GPBGetFieldDataType(field);
GPBCodedInputStreamState *state = &input->state_;
- id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax);
+ id genericArray = GetOrCreateArrayIvarWithField(self, field);
int32_t length = GPBCodedInputStreamReadInt32(state);
size_t limit = GPBCodedInputStreamPushLimit(state, length);
while (GPBCodedInputStreamBytesUntilLimit(state) > 0) {
@@ -2257,7 +2283,7 @@
GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax,
GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) {
GPBCodedInputStreamState *state = &input->state_;
- id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax);
+ id genericArray = GetOrCreateArrayIvarWithField(self, field);
switch (GPBGetFieldDataType(field)) {
#define CASE_REPEATED_NOT_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \
case GPBDataType##NAME: { \
@@ -2359,7 +2385,7 @@
} else { // fieldType == GPBFieldTypeMap
// GPB*Dictionary or NSDictionary, exact type doesn't matter at this
// point.
- id map = GetOrCreateMapIvarWithField(self, fieldDescriptor, syntax);
+ id map = GetOrCreateMapIvarWithField(self, fieldDescriptor);
[input readMapEntry:map
extensionRegistry:extensionRegistry
field:fieldDescriptor
@@ -2433,7 +2459,6 @@
GPBBecomeVisibleToAutocreator(self);
GPBDescriptor *descriptor = [[self class] descriptor];
- GPBFileSyntax syntax = descriptor.file.syntax;
for (GPBFieldDescriptor *field in descriptor->fields_) {
GPBFieldType fieldType = field.fieldType;
@@ -2447,44 +2472,44 @@
GPBDataType fieldDataType = GPBGetFieldDataType(field);
switch (fieldDataType) {
case GPBDataTypeBool:
- GPBSetBoolIvarWithFieldInternal(
- self, field, GPBGetMessageBoolField(other, field), syntax);
+ GPBSetBoolIvarWithFieldPrivate(
+ self, field, GPBGetMessageBoolField(other, field));
break;
case GPBDataTypeSFixed32:
case GPBDataTypeEnum:
case GPBDataTypeInt32:
case GPBDataTypeSInt32:
- GPBSetInt32IvarWithFieldInternal(
- self, field, GPBGetMessageInt32Field(other, field), syntax);
+ GPBSetInt32IvarWithFieldPrivate(
+ self, field, GPBGetMessageInt32Field(other, field));
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
- GPBSetUInt32IvarWithFieldInternal(
- self, field, GPBGetMessageUInt32Field(other, field), syntax);
+ GPBSetUInt32IvarWithFieldPrivate(
+ self, field, GPBGetMessageUInt32Field(other, field));
break;
case GPBDataTypeSFixed64:
case GPBDataTypeInt64:
case GPBDataTypeSInt64:
- GPBSetInt64IvarWithFieldInternal(
- self, field, GPBGetMessageInt64Field(other, field), syntax);
+ GPBSetInt64IvarWithFieldPrivate(
+ self, field, GPBGetMessageInt64Field(other, field));
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
- GPBSetUInt64IvarWithFieldInternal(
- self, field, GPBGetMessageUInt64Field(other, field), syntax);
+ GPBSetUInt64IvarWithFieldPrivate(
+ self, field, GPBGetMessageUInt64Field(other, field));
break;
case GPBDataTypeFloat:
- GPBSetFloatIvarWithFieldInternal(
- self, field, GPBGetMessageFloatField(other, field), syntax);
+ GPBSetFloatIvarWithFieldPrivate(
+ self, field, GPBGetMessageFloatField(other, field));
break;
case GPBDataTypeDouble:
- GPBSetDoubleIvarWithFieldInternal(
- self, field, GPBGetMessageDoubleField(other, field), syntax);
+ GPBSetDoubleIvarWithFieldPrivate(
+ self, field, GPBGetMessageDoubleField(other, field));
break;
case GPBDataTypeBytes:
case GPBDataTypeString: {
id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field);
- GPBSetObjectIvarWithFieldInternal(self, field, otherVal, syntax);
+ GPBSetObjectIvarWithFieldPrivate(self, field, otherVal);
break;
}
case GPBDataTypeMessage:
@@ -2496,8 +2521,7 @@
[message mergeFrom:otherVal];
} else {
GPBMessage *message = [otherVal copy];
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, message,
- syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, message);
}
break;
}
@@ -2511,17 +2535,17 @@
GPBDataType fieldDataType = field->description_->dataType;
if (GPBDataTypeIsObject(fieldDataType)) {
NSMutableArray *resultArray =
- GetOrCreateArrayIvarWithField(self, field, syntax);
+ GetOrCreateArrayIvarWithField(self, field);
[resultArray addObjectsFromArray:otherArray];
} else if (fieldDataType == GPBDataTypeEnum) {
GPBEnumArray *resultArray =
- GetOrCreateArrayIvarWithField(self, field, syntax);
+ GetOrCreateArrayIvarWithField(self, field);
[resultArray addRawValuesFromArray:otherArray];
} else {
- // The array type doesn't matter, that all implment
+ // The array type doesn't matter, that all implement
// -addValuesFromArray:.
GPBInt32Array *resultArray =
- GetOrCreateArrayIvarWithField(self, field, syntax);
+ GetOrCreateArrayIvarWithField(self, field);
[resultArray addValuesFromArray:otherArray];
}
}
@@ -2535,19 +2559,19 @@
if (GPBDataTypeIsObject(keyDataType) &&
GPBDataTypeIsObject(valueDataType)) {
NSMutableDictionary *resultDict =
- GetOrCreateMapIvarWithField(self, field, syntax);
+ GetOrCreateMapIvarWithField(self, field);
[resultDict addEntriesFromDictionary:otherDict];
} else if (valueDataType == GPBDataTypeEnum) {
// The exact type doesn't matter, just need to know it is a
// GPB*EnumDictionary.
GPBInt32EnumDictionary *resultDict =
- GetOrCreateMapIvarWithField(self, field, syntax);
+ GetOrCreateMapIvarWithField(self, field);
[resultDict addRawEntriesFromDictionary:otherDict];
} else {
// The exact type doesn't matter, they all implement
// -addEntriesFromDictionary:.
GPBInt32Int32Dictionary *resultDict =
- GetOrCreateMapIvarWithField(self, field, syntax);
+ GetOrCreateMapIvarWithField(self, field);
[resultDict addEntriesFromDictionary:otherDict];
}
}
@@ -3079,14 +3103,13 @@
// See comment about __unsafe_unretained on ResolveIvarGet.
static void ResolveIvarSet(__unsafe_unretained GPBFieldDescriptor *field,
- GPBFileSyntax syntax,
ResolveIvarAccessorMethodResult *result) {
GPBDataType fieldDataType = GPBGetFieldDataType(field);
switch (fieldDataType) {
#define CASE_SET(NAME, TYPE, TRUE_NAME) \
case GPBDataType##NAME: { \
result->impToAdd = imp_implementationWithBlock(^(id obj, TYPE value) { \
- return GPBSet##TRUE_NAME##IvarWithFieldInternal(obj, field, value, syntax); \
+ return GPBSet##TRUE_NAME##IvarWithFieldPrivate(obj, field, value); \
}); \
result->encodingSelector = @selector(set##NAME:); \
break; \
@@ -3094,7 +3117,7 @@
#define CASE_SET_COPY(NAME) \
case GPBDataType##NAME: { \
result->impToAdd = imp_implementationWithBlock(^(id obj, id value) { \
- return GPBSetRetainedObjectIvarWithFieldInternal(obj, field, [value copy], syntax); \
+ return GPBSetRetainedObjectIvarWithFieldPrivate(obj, field, [value copy]); \
}); \
result->encodingSelector = @selector(set##NAME:); \
break; \
@@ -3141,7 +3164,7 @@
ResolveIvarGet(field, &result);
break;
} else if (sel == field->setSel_) {
- ResolveIvarSet(field, descriptor.file.syntax, &result);
+ ResolveIvarSet(field, &result);
break;
} else if (sel == field->hasOrCountSel_) {
int32_t index = GPBFieldHasIndex(field);
@@ -3191,9 +3214,8 @@
} else if (sel == field->setSel_) {
// Local for syntax so the block can directly capture it and not the
// full lookup.
- const GPBFileSyntax syntax = descriptor.file.syntax;
result.impToAdd = imp_implementationWithBlock(^(id obj, id value) {
- GPBSetObjectIvarWithFieldInternal(obj, field, value, syntax);
+ GPBSetObjectIvarWithFieldPrivate(obj, field, value);
});
result.encodingSelector = @selector(setArray:);
break;
@@ -3231,7 +3253,7 @@
+ (BOOL)resolveClassMethod:(SEL)sel {
// Extensions scoped to a Message and looked up via class methods.
- if (GPBResolveExtensionClassMethod([self descriptor].messageClass, sel)) {
+ if (GPBResolveExtensionClassMethod(self, sel)) {
return YES;
}
return [super resolveClassMethod:sel];
@@ -3298,9 +3320,7 @@
[self class], field.name];
}
#endif
- GPBDescriptor *descriptor = [[self class] descriptor];
- GPBFileSyntax syntax = descriptor.file.syntax;
- return GetOrCreateArrayIvarWithField(self, field, syntax);
+ return GetOrCreateArrayIvarWithField(self, field);
}
// Only exists for public api, no core code should use this.
@@ -3312,9 +3332,7 @@
[self class], field.name];
}
#endif
- GPBDescriptor *descriptor = [[self class] descriptor];
- GPBFileSyntax syntax = descriptor.file.syntax;
- return GetOrCreateMapIvarWithField(self, field, syntax);
+ return GetOrCreateMapIvarWithField(self, field);
}
id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
diff --git a/objectivec/GPBProtocolBuffers.h b/objectivec/GPBProtocolBuffers.h
index 32f9f5d..c5df916 100644
--- a/objectivec/GPBProtocolBuffers.h
+++ b/objectivec/GPBProtocolBuffers.h
@@ -52,25 +52,25 @@
// Well-known proto types
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Any.pbobjc.h>
- #import <protobuf/Api.pbobjc.h>
- #import <protobuf/Duration.pbobjc.h>
- #import <protobuf/Empty.pbobjc.h>
- #import <protobuf/FieldMask.pbobjc.h>
- #import <protobuf/SourceContext.pbobjc.h>
- #import <protobuf/Struct.pbobjc.h>
- #import <protobuf/Timestamp.pbobjc.h>
- #import <protobuf/Type.pbobjc.h>
- #import <protobuf/Wrappers.pbobjc.h>
+ #import <Protobuf/GPBAny.pbobjc.h>
+ #import <Protobuf/GPBApi.pbobjc.h>
+ #import <Protobuf/GPBDuration.pbobjc.h>
+ #import <Protobuf/GPBEmpty.pbobjc.h>
+ #import <Protobuf/GPBFieldMask.pbobjc.h>
+ #import <Protobuf/GPBSourceContext.pbobjc.h>
+ #import <Protobuf/GPBStruct.pbobjc.h>
+ #import <Protobuf/GPBTimestamp.pbobjc.h>
+ #import <Protobuf/GPBType.pbobjc.h>
+ #import <Protobuf/GPBWrappers.pbobjc.h>
#else
- #import "google/protobuf/Any.pbobjc.h"
- #import "google/protobuf/Api.pbobjc.h"
- #import "google/protobuf/Duration.pbobjc.h"
- #import "google/protobuf/Empty.pbobjc.h"
- #import "google/protobuf/FieldMask.pbobjc.h"
- #import "google/protobuf/SourceContext.pbobjc.h"
- #import "google/protobuf/Struct.pbobjc.h"
- #import "google/protobuf/Timestamp.pbobjc.h"
- #import "google/protobuf/Type.pbobjc.h"
- #import "google/protobuf/Wrappers.pbobjc.h"
+ #import "GPBAny.pbobjc.h"
+ #import "GPBApi.pbobjc.h"
+ #import "GPBDuration.pbobjc.h"
+ #import "GPBEmpty.pbobjc.h"
+ #import "GPBFieldMask.pbobjc.h"
+ #import "GPBSourceContext.pbobjc.h"
+ #import "GPBStruct.pbobjc.h"
+ #import "GPBTimestamp.pbobjc.h"
+ #import "GPBType.pbobjc.h"
+ #import "GPBWrappers.pbobjc.h"
#endif
diff --git a/objectivec/GPBProtocolBuffers.m b/objectivec/GPBProtocolBuffers.m
index d04c8be..0545ae9 100644
--- a/objectivec/GPBProtocolBuffers.m
+++ b/objectivec/GPBProtocolBuffers.m
@@ -54,13 +54,13 @@
#import "GPBWellKnownTypes.m"
#import "GPBWireFormat.m"
-#import "google/protobuf/Any.pbobjc.m"
-#import "google/protobuf/Api.pbobjc.m"
-#import "google/protobuf/Duration.pbobjc.m"
-#import "google/protobuf/Empty.pbobjc.m"
-#import "google/protobuf/FieldMask.pbobjc.m"
-#import "google/protobuf/SourceContext.pbobjc.m"
-#import "google/protobuf/Struct.pbobjc.m"
-#import "google/protobuf/Timestamp.pbobjc.m"
-#import "google/protobuf/Type.pbobjc.m"
-#import "google/protobuf/Wrappers.pbobjc.m"
+#import "GPBAny.pbobjc.m"
+#import "GPBApi.pbobjc.m"
+#import "GPBDuration.pbobjc.m"
+#import "GPBEmpty.pbobjc.m"
+#import "GPBFieldMask.pbobjc.m"
+#import "GPBSourceContext.pbobjc.m"
+#import "GPBStruct.pbobjc.m"
+#import "GPBTimestamp.pbobjc.m"
+#import "GPBType.pbobjc.m"
+#import "GPBWrappers.pbobjc.m"
diff --git a/objectivec/GPBRuntimeTypes.h b/objectivec/GPBRuntimeTypes.h
index 8148054..9c1083a 100644
--- a/objectivec/GPBRuntimeTypes.h
+++ b/objectivec/GPBRuntimeTypes.h
@@ -142,3 +142,10 @@
/** Exclusive. */
uint32_t end;
} GPBExtensionRange;
+
+/**
+ A type to represent an Objective C class.
+ This is actually an `objc_class` but the runtime headers will not allow us to
+ reference `objc_class`, so we have defined our own.
+*/
+typedef struct GPBObjcClass_t GPBObjcClass_t;
diff --git a/objectivec/GPBSourceContext.pbobjc.h b/objectivec/GPBSourceContext.pbobjc.h
new file mode 100644
index 0000000..7a10336
--- /dev/null
+++ b/objectivec/GPBSourceContext.pbobjc.h
@@ -0,0 +1,77 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/source_context.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+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.
+ **/
+GPB_FINAL @interface GPBSourceContextRoot : GPBRootObject
+@end
+
+#pragma mark - GPBSourceContext
+
+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.
+ **/
+GPB_FINAL @interface GPBSourceContext : GPBMessage
+
+/**
+ * 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
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/SourceContext.pbobjc.m b/objectivec/GPBSourceContext.pbobjc.m
similarity index 86%
rename from objectivec/google/protobuf/SourceContext.pbobjc.m
rename to objectivec/GPBSourceContext.pbobjc.m
index c955f2b..b3e6fa7 100644
--- a/objectivec/google/protobuf/SourceContext.pbobjc.m
+++ b/objectivec/GPBSourceContext.pbobjc.m
@@ -8,15 +8,15 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/SourceContext.pbobjc.h>
+ #import <Protobuf/GPBSourceContext.pbobjc.h>
#else
- #import "google/protobuf/SourceContext.pbobjc.h"
+ #import "GPBSourceContext.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
@@ -66,11 +66,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "fileName",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBSourceContext_FieldNumber_FileName,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBSourceContext__storage_, fileName),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
};
@@ -81,7 +81,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBSourceContext__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBStruct.pbobjc.h b/objectivec/GPBStruct.pbobjc.h
new file mode 100644
index 0000000..e36df3f
--- /dev/null
+++ b/objectivec/GPBStruct.pbobjc.h
@@ -0,0 +1,204 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/struct.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+@class GPBListValue;
+@class GPBStruct;
+@class GPBValue;
+
+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`.
+ **/
+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.
+ **/
+ GPBNullValue_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
+ /** 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.
+ **/
+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.
+ **/
+GPB_FINAL @interface GPBStructRoot : GPBRootObject
+@end
+
+#pragma mark - GPBStruct
+
+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.
+ **/
+GPB_FINAL @interface GPBStruct : GPBMessage
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger fields_Count;
+
+@end
+
+#pragma mark - GPBValue
+
+typedef GPB_ENUM(GPBValue_FieldNumber) {
+ GPBValue_FieldNumber_NullValue = 1,
+ GPBValue_FieldNumber_NumberValue = 2,
+ GPBValue_FieldNumber_StringValue = 3,
+ GPBValue_FieldNumber_BoolValue = 4,
+ GPBValue_FieldNumber_StructValue = 5,
+ GPBValue_FieldNumber_ListValue = 6,
+};
+
+typedef GPB_ENUM(GPBValue_Kind_OneOfCase) {
+ GPBValue_Kind_OneOfCase_GPBUnsetOneOfCase = 0,
+ GPBValue_Kind_OneOfCase_NullValue = 1,
+ GPBValue_Kind_OneOfCase_NumberValue = 2,
+ GPBValue_Kind_OneOfCase_StringValue = 3,
+ GPBValue_Kind_OneOfCase_BoolValue = 4,
+ GPBValue_Kind_OneOfCase_StructValue = 5,
+ 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.
+ **/
+GPB_FINAL @interface GPBValue : GPBMessage
+
+/** The kind of value. */
+@property(nonatomic, readonly) GPBValue_Kind_OneOfCase kindOneOfCase;
+
+/** Represents a null value. */
+@property(nonatomic, readwrite) GPBNullValue nullValue;
+
+/** Represents a double value. */
+@property(nonatomic, readwrite) double numberValue;
+
+/** Represents a string value. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *stringValue;
+
+/** Represents a boolean value. */
+@property(nonatomic, readwrite) BOOL boolValue;
+
+/** Represents a structured value. */
+@property(nonatomic, readwrite, strong, null_resettable) GPBStruct *structValue;
+
+/** 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.
+ **/
+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.
+ **/
+void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value);
+
+/**
+ * Clears whatever value was set for the oneof 'kind'.
+ **/
+void GPBValue_ClearKindOneOfCase(GPBValue *message);
+
+#pragma mark - GPBListValue
+
+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.
+ **/
+GPB_FINAL @interface GPBListValue : GPBMessage
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger valuesArray_Count;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Struct.pbobjc.m b/objectivec/GPBStruct.pbobjc.m
similarity index 84%
rename from objectivec/google/protobuf/Struct.pbobjc.m
rename to objectivec/GPBStruct.pbobjc.m
index 3873f5a..554046a 100644
--- a/objectivec/google/protobuf/Struct.pbobjc.m
+++ b/objectivec/GPBStruct.pbobjc.m
@@ -8,7 +8,7 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
@@ -16,15 +16,24 @@
#import <stdatomic.h>
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Struct.pbobjc.h>
+ #import <Protobuf/GPBStruct.pbobjc.h>
#else
- #import "google/protobuf/Struct.pbobjc.h"
+ #import "GPBStruct.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
+#pragma clang diagnostic ignored "-Wdollar-in-identifier-extension"
+
+#pragma mark - Objective C Class declarations
+// Forward declarations of Objective C classes that we can use as
+// static values in struct initializers.
+// We don't use [Foo class] because it is not a static value.
+GPBObjCClassDeclaration(GPBListValue);
+GPBObjCClassDeclaration(GPBStruct);
+GPBObjCClassDeclaration(GPBValue);
#pragma mark - GPBStructRoot
@@ -102,7 +111,7 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "fields",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBValue),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBValue),
.number = GPBStruct_FieldNumber_Fields,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBStruct__storage_, fields),
@@ -117,7 +126,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBStruct__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -166,7 +175,7 @@
},
{
.name = "numberValue",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBValue_FieldNumber_NumberValue,
.hasIndex = -1,
.offset = (uint32_t)offsetof(GPBValue__storage_, numberValue),
@@ -175,7 +184,7 @@
},
{
.name = "stringValue",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBValue_FieldNumber_StringValue,
.hasIndex = -1,
.offset = (uint32_t)offsetof(GPBValue__storage_, stringValue),
@@ -184,7 +193,7 @@
},
{
.name = "boolValue",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBValue_FieldNumber_BoolValue,
.hasIndex = -1,
.offset = 0, // Stored in _has_storage_ to save space.
@@ -193,7 +202,7 @@
},
{
.name = "structValue",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBStruct),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBStruct),
.number = GPBValue_FieldNumber_StructValue,
.hasIndex = -1,
.offset = (uint32_t)offsetof(GPBValue__storage_, structValue),
@@ -202,7 +211,7 @@
},
{
.name = "listValue",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBListValue),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBListValue),
.number = GPBValue_FieldNumber_ListValue,
.hasIndex = -1,
.offset = (uint32_t)offsetof(GPBValue__storage_, listValue),
@@ -217,7 +226,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
static const char *oneofs[] = {
"kind",
};
@@ -237,19 +246,19 @@
int32_t GPBValue_NullValue_RawValue(GPBValue *message) {
GPBDescriptor *descriptor = [GPBValue descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBValue_FieldNumber_NullValue];
- return GPBGetMessageInt32Field(message, field);
+ return GPBGetMessageRawEnumField(message, field);
}
void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value) {
GPBDescriptor *descriptor = [GPBValue descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBValue_FieldNumber_NullValue];
- GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);
+ GPBSetMessageRawEnumField(message, field, value);
}
void GPBValue_ClearKindOneOfCase(GPBValue *message) {
- GPBDescriptor *descriptor = [message descriptor];
+ GPBDescriptor *descriptor = [GPBValue descriptor];
GPBOneofDescriptor *oneof = [descriptor.oneofs objectAtIndex:0];
- GPBMaybeClearOneof(message, oneof, -1, 0);
+ GPBClearOneof(message, oneof);
}
#pragma mark - GPBListValue
@@ -270,7 +279,7 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "valuesArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBValue),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBValue),
.number = GPBListValue_FieldNumber_ValuesArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBListValue__storage_, valuesArray),
@@ -285,7 +294,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBListValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBTimestamp.pbobjc.h b/objectivec/GPBTimestamp.pbobjc.h
new file mode 100644
index 0000000..92f0bac
--- /dev/null
+++ b/objectivec/GPBTimestamp.pbobjc.h
@@ -0,0 +1,167 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/timestamp.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+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.
+ **/
+GPB_FINAL @interface GPBTimestampRoot : GPBRootObject
+@end
+
+#pragma mark - GPBTimestamp
+
+typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
+ GPBTimestamp_FieldNumber_Seconds = 1,
+ GPBTimestamp_FieldNumber_Nanos = 2,
+};
+
+/**
+ * A Timestamp represents a point in time independent of any time zone or local
+ * calendar, encoded as a count of seconds and fractions of seconds at
+ * nanosecond resolution. The count is relative to an epoch at UTC midnight on
+ * January 1, 1970, in the proleptic Gregorian calendar which extends the
+ * Gregorian calendar backwards to year one.
+ *
+ * All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
+ * second table is needed for interpretation, using a [24-hour linear
+ * smear](https://developers.google.com/time/smear).
+ *
+ * The 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](https://www.ietf.org/rfc/rfc3339.txt) date strings.
+ *
+ * # Examples
+ *
+ * Example 1: Compute Timestamp from POSIX `time()`.
+ *
+ * Timestamp timestamp;
+ * timestamp.set_seconds(time(NULL));
+ * timestamp.set_nanos(0);
+ *
+ * Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+ *
+ * struct timeval tv;
+ * gettimeofday(&tv, NULL);
+ *
+ * Timestamp timestamp;
+ * timestamp.set_seconds(tv.tv_sec);
+ * timestamp.set_nanos(tv.tv_usec * 1000);
+ *
+ * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+ *
+ * FILETIME ft;
+ * GetSystemTimeAsFileTime(&ft);
+ * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+ *
+ * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+ * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+ * Timestamp timestamp;
+ * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+ * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+ *
+ * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+ *
+ * long millis = System.currentTimeMillis();
+ *
+ * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+ * .setNanos((int) ((millis % 1000) * 1000000)).build();
+ *
+ *
+ * Example 5: Compute Timestamp from current time in Python.
+ *
+ * timestamp = Timestamp()
+ * timestamp.GetCurrentTime()
+ *
+ * # JSON Mapping
+ *
+ * In JSON format, the Timestamp type is encoded as a string in the
+ * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+ * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+ * where {year} is always expressed using four digits while {month}, {day},
+ * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+ * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+ * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+ * is required. A proto3 JSON serializer should always use UTC (as indicated by
+ * "Z") when printing the Timestamp type and a proto3 JSON parser should be
+ * able to accept both UTC and other timezones (as indicated by an offset).
+ *
+ * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+ * 01:30 UTC on January 15, 2017.
+ *
+ * In JavaScript, one can convert a Date object to this format using the
+ * standard
+ * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
+ * method. In Python, a standard `datetime.datetime` object can be converted
+ * to this format using
+ * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
+ * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
+ * the Joda Time's [`ISODateTimeFormat.dateTime()`](
+ * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
+ * ) to obtain a formatter capable of generating timestamps in this format.
+ **/
+GPB_FINAL @interface GPBTimestamp : GPBMessage
+
+/**
+ * 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.
+ **/
+@property(nonatomic, readwrite) int32_t nanos;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.m b/objectivec/GPBTimestamp.pbobjc.m
similarity index 84%
rename from objectivec/google/protobuf/Timestamp.pbobjc.m
rename to objectivec/GPBTimestamp.pbobjc.m
index 05eb3a5..736a75d 100644
--- a/objectivec/google/protobuf/Timestamp.pbobjc.m
+++ b/objectivec/GPBTimestamp.pbobjc.m
@@ -8,15 +8,15 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Timestamp.pbobjc.h>
+ #import <Protobuf/GPBTimestamp.pbobjc.h>
#else
- #import "google/protobuf/Timestamp.pbobjc.h"
+ #import "GPBTimestamp.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
@@ -68,20 +68,20 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "seconds",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBTimestamp_FieldNumber_Seconds,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBTimestamp__storage_, seconds),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt64,
},
{
.name = "nanos",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBTimestamp_FieldNumber_Nanos,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBTimestamp__storage_, nanos),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt32,
},
};
@@ -92,7 +92,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBTimestamp__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBType.pbobjc.h b/objectivec/GPBType.pbobjc.h
new file mode 100644
index 0000000..747e15d
--- /dev/null
+++ b/objectivec/GPBType.pbobjc.h
@@ -0,0 +1,444 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/type.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+@class GPBAny;
+@class GPBEnumValue;
+@class GPBField;
+@class GPBOption;
+@class GPBSourceContext;
+
+NS_ASSUME_NONNULL_BEGIN
+
+#pragma mark - Enum GPBSyntax
+
+/** 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.
+ **/
+ GPBSyntax_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
+ /** Syntax `proto2`. */
+ GPBSyntax_SyntaxProto2 = 0,
+
+ /** 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.
+ **/
+BOOL GPBSyntax_IsValidValue(int32_t value);
+
+#pragma mark - Enum GPBField_Kind
+
+/** 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.
+ **/
+ GPBField_Kind_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
+ /** Field type unknown. */
+ GPBField_Kind_TypeUnknown = 0,
+
+ /** Field type double. */
+ GPBField_Kind_TypeDouble = 1,
+
+ /** Field type float. */
+ GPBField_Kind_TypeFloat = 2,
+
+ /** Field type int64. */
+ GPBField_Kind_TypeInt64 = 3,
+
+ /** Field type uint64. */
+ GPBField_Kind_TypeUint64 = 4,
+
+ /** Field type int32. */
+ GPBField_Kind_TypeInt32 = 5,
+
+ /** Field type fixed64. */
+ GPBField_Kind_TypeFixed64 = 6,
+
+ /** Field type fixed32. */
+ GPBField_Kind_TypeFixed32 = 7,
+
+ /** Field type bool. */
+ GPBField_Kind_TypeBool = 8,
+
+ /** Field type string. */
+ GPBField_Kind_TypeString = 9,
+
+ /** Field type group. Proto2 syntax only, and deprecated. */
+ GPBField_Kind_TypeGroup = 10,
+
+ /** Field type message. */
+ GPBField_Kind_TypeMessage = 11,
+
+ /** Field type bytes. */
+ GPBField_Kind_TypeBytes = 12,
+
+ /** Field type uint32. */
+ GPBField_Kind_TypeUint32 = 13,
+
+ /** Field type enum. */
+ GPBField_Kind_TypeEnum = 14,
+
+ /** Field type sfixed32. */
+ GPBField_Kind_TypeSfixed32 = 15,
+
+ /** Field type sfixed64. */
+ GPBField_Kind_TypeSfixed64 = 16,
+
+ /** Field type sint32. */
+ GPBField_Kind_TypeSint32 = 17,
+
+ /** 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.
+ **/
+BOOL GPBField_Kind_IsValidValue(int32_t value);
+
+#pragma mark - Enum GPBField_Cardinality
+
+/** 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.
+ **/
+ GPBField_Cardinality_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
+ /** For fields with unknown cardinality. */
+ GPBField_Cardinality_CardinalityUnknown = 0,
+
+ /** For optional fields. */
+ GPBField_Cardinality_CardinalityOptional = 1,
+
+ /** For required fields. Proto2 syntax only. */
+ GPBField_Cardinality_CardinalityRequired = 2,
+
+ /** 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.
+ **/
+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.
+ **/
+GPB_FINAL @interface GPBTypeRoot : GPBRootObject
+@end
+
+#pragma mark - GPBType
+
+typedef GPB_ENUM(GPBType_FieldNumber) {
+ GPBType_FieldNumber_Name = 1,
+ GPBType_FieldNumber_FieldsArray = 2,
+ GPBType_FieldNumber_OneofsArray = 3,
+ GPBType_FieldNumber_OptionsArray = 4,
+ GPBType_FieldNumber_SourceContext = 5,
+ GPBType_FieldNumber_Syntax = 6,
+};
+
+/**
+ * A protocol buffer message type.
+ **/
+GPB_FINAL @interface GPBType : GPBMessage
+
+/** The fully qualified message name. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger fieldsArray_Count;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger oneofsArray_Count;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger optionsArray_Count;
+
+/** The source context. */
+@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext;
+/** Test to see if @c sourceContext has been set. */
+@property(nonatomic, readwrite) BOOL hasSourceContext;
+
+/** 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.
+ **/
+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.
+ **/
+void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value);
+
+#pragma mark - GPBField
+
+typedef GPB_ENUM(GPBField_FieldNumber) {
+ GPBField_FieldNumber_Kind = 1,
+ GPBField_FieldNumber_Cardinality = 2,
+ GPBField_FieldNumber_Number = 3,
+ GPBField_FieldNumber_Name = 4,
+ GPBField_FieldNumber_TypeURL = 6,
+ GPBField_FieldNumber_OneofIndex = 7,
+ GPBField_FieldNumber_Packed = 8,
+ GPBField_FieldNumber_OptionsArray = 9,
+ GPBField_FieldNumber_JsonName = 10,
+ GPBField_FieldNumber_DefaultValue = 11,
+};
+
+/**
+ * A single field of a message type.
+ **/
+GPB_FINAL @interface GPBField : GPBMessage
+
+/** The field type. */
+@property(nonatomic, readwrite) GPBField_Kind kind;
+
+/** The field cardinality. */
+@property(nonatomic, readwrite) GPBField_Cardinality cardinality;
+
+/** The field number. */
+@property(nonatomic, readwrite) int32_t number;
+
+/** 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"`.
+ **/
+@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.
+ **/
+@property(nonatomic, readwrite) int32_t oneofIndex;
+
+/** Whether to use alternative packed wire representation. */
+@property(nonatomic, readwrite) BOOL packed;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger optionsArray_Count;
+
+/** 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. */
+@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.
+ **/
+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.
+ **/
+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.
+ **/
+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.
+ **/
+void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value);
+
+#pragma mark - GPBEnum
+
+typedef GPB_ENUM(GPBEnum_FieldNumber) {
+ GPBEnum_FieldNumber_Name = 1,
+ GPBEnum_FieldNumber_EnumvalueArray = 2,
+ GPBEnum_FieldNumber_OptionsArray = 3,
+ GPBEnum_FieldNumber_SourceContext = 4,
+ GPBEnum_FieldNumber_Syntax = 5,
+};
+
+/**
+ * Enum type definition.
+ **/
+GPB_FINAL @interface GPBEnum : GPBMessage
+
+/** Enum type name. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger enumvalueArray_Count;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger optionsArray_Count;
+
+/** The source context. */
+@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext;
+/** Test to see if @c sourceContext has been set. */
+@property(nonatomic, readwrite) BOOL hasSourceContext;
+
+/** 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.
+ **/
+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.
+ **/
+void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value);
+
+#pragma mark - GPBEnumValue
+
+typedef GPB_ENUM(GPBEnumValue_FieldNumber) {
+ GPBEnumValue_FieldNumber_Name = 1,
+ GPBEnumValue_FieldNumber_Number = 2,
+ GPBEnumValue_FieldNumber_OptionsArray = 3,
+};
+
+/**
+ * Enum value definition.
+ **/
+GPB_FINAL @interface GPBEnumValue : GPBMessage
+
+/** Enum value name. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
+
+/** Enum value number. */
+@property(nonatomic, readwrite) int32_t number;
+
+/** 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. */
+@property(nonatomic, readonly) NSUInteger optionsArray_Count;
+
+@end
+
+#pragma mark - GPBOption
+
+typedef GPB_ENUM(GPBOption_FieldNumber) {
+ GPBOption_FieldNumber_Name = 1,
+ GPBOption_FieldNumber_Value = 2,
+};
+
+/**
+ * A protocol buffer option, which can be attached to a message, field,
+ * enumeration, etc.
+ **/
+GPB_FINAL @interface GPBOption : GPBMessage
+
+/**
+ * The option's name. For protobuf built-in options (options defined in
+ * descriptor.proto), this is the short name. For example, `"map_entry"`.
+ * For custom options, it should be the fully-qualified name. For example,
+ * `"google.api.http"`.
+ **/
+@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
+
+/**
+ * The option's value packed in an Any message. If the value is a primitive,
+ * the corresponding wrapper type defined in google/protobuf/wrappers.proto
+ * should be used. If the value is an enum, it should be stored as an int32
+ * value using the google.protobuf.Int32Value type.
+ **/
+@property(nonatomic, readwrite, strong, null_resettable) GPBAny *value;
+/** Test to see if @c value has been set. */
+@property(nonatomic, readwrite) BOOL hasValue;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Type.pbobjc.m b/objectivec/GPBType.pbobjc.m
similarity index 83%
rename from objectivec/google/protobuf/Type.pbobjc.m
rename to objectivec/GPBType.pbobjc.m
index 7451edc..70dae31 100644
--- a/objectivec/google/protobuf/Type.pbobjc.m
+++ b/objectivec/GPBType.pbobjc.m
@@ -8,7 +8,7 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
@@ -16,18 +16,29 @@
#import <stdatomic.h>
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Type.pbobjc.h>
- #import <protobuf/Any.pbobjc.h>
- #import <protobuf/SourceContext.pbobjc.h>
+ #import <Protobuf/GPBType.pbobjc.h>
+ #import <Protobuf/GPBAny.pbobjc.h>
+ #import <Protobuf/GPBSourceContext.pbobjc.h>
#else
- #import "google/protobuf/Type.pbobjc.h"
- #import "google/protobuf/Any.pbobjc.h"
- #import "google/protobuf/SourceContext.pbobjc.h"
+ #import "GPBType.pbobjc.h"
+ #import "GPBAny.pbobjc.h"
+ #import "GPBSourceContext.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#pragma clang diagnostic ignored "-Wdollar-in-identifier-extension"
+
+#pragma mark - Objective C Class declarations
+// Forward declarations of Objective C classes that we can use as
+// static values in struct initializers.
+// We don't use [Foo class] because it is not a static value.
+GPBObjCClassDeclaration(GPBAny);
+GPBObjCClassDeclaration(GPBEnumValue);
+GPBObjCClassDeclaration(GPBField);
+GPBObjCClassDeclaration(GPBOption);
+GPBObjCClassDeclaration(GPBSourceContext);
#pragma mark - GPBTypeRoot
@@ -117,16 +128,16 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBType_FieldNumber_Name,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBType__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "fieldsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBField),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBField),
.number = GPBType_FieldNumber_FieldsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBType__storage_, fieldsArray),
@@ -135,7 +146,7 @@
},
{
.name = "oneofsArray",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBType_FieldNumber_OneofsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBType__storage_, oneofsArray),
@@ -144,7 +155,7 @@
},
{
.name = "optionsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBOption),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBOption),
.number = GPBType_FieldNumber_OptionsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBType__storage_, optionsArray),
@@ -153,7 +164,7 @@
},
{
.name = "sourceContext",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBSourceContext),
.number = GPBType_FieldNumber_SourceContext,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBType__storage_, sourceContext),
@@ -166,7 +177,7 @@
.number = GPBType_FieldNumber_Syntax,
.hasIndex = 2,
.offset = (uint32_t)offsetof(GPBType__storage_, syntax),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeEnum,
},
};
@@ -177,7 +188,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBType__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -191,13 +202,13 @@
int32_t GPBType_Syntax_RawValue(GPBType *message) {
GPBDescriptor *descriptor = [GPBType descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax];
- return GPBGetMessageInt32Field(message, field);
+ return GPBGetMessageRawEnumField(message, field);
}
void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value) {
GPBDescriptor *descriptor = [GPBType descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax];
- GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);
+ GPBSetMessageRawEnumField(message, field, value);
}
#pragma mark - GPBField
@@ -240,7 +251,7 @@
.number = GPBField_FieldNumber_Kind,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBField__storage_, kind),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeEnum,
},
{
@@ -249,57 +260,57 @@
.number = GPBField_FieldNumber_Cardinality,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBField__storage_, cardinality),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeEnum,
},
{
.name = "number",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBField_FieldNumber_Number,
.hasIndex = 2,
.offset = (uint32_t)offsetof(GPBField__storage_, number),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt32,
},
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBField_FieldNumber_Name,
.hasIndex = 3,
.offset = (uint32_t)offsetof(GPBField__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "typeURL",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBField_FieldNumber_TypeURL,
.hasIndex = 4,
.offset = (uint32_t)offsetof(GPBField__storage_, typeURL),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "oneofIndex",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBField_FieldNumber_OneofIndex,
.hasIndex = 5,
.offset = (uint32_t)offsetof(GPBField__storage_, oneofIndex),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt32,
},
{
.name = "packed",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBField_FieldNumber_Packed,
.hasIndex = 6,
.offset = 7, // Stored in _has_storage_ to save space.
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeBool,
},
{
.name = "optionsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBOption),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBOption),
.number = GPBField_FieldNumber_OptionsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBField__storage_, optionsArray),
@@ -308,20 +319,20 @@
},
{
.name = "jsonName",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBField_FieldNumber_JsonName,
.hasIndex = 8,
.offset = (uint32_t)offsetof(GPBField__storage_, jsonName),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "defaultValue",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBField_FieldNumber_DefaultValue,
.hasIndex = 9,
.offset = (uint32_t)offsetof(GPBField__storage_, defaultValue),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
};
@@ -332,7 +343,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBField__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS
static const char *extraTextFormatInfo =
"\001\006\004\241!!\000";
@@ -351,25 +362,25 @@
int32_t GPBField_Kind_RawValue(GPBField *message) {
GPBDescriptor *descriptor = [GPBField descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind];
- return GPBGetMessageInt32Field(message, field);
+ return GPBGetMessageRawEnumField(message, field);
}
void SetGPBField_Kind_RawValue(GPBField *message, int32_t value) {
GPBDescriptor *descriptor = [GPBField descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind];
- GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);
+ GPBSetMessageRawEnumField(message, field, value);
}
int32_t GPBField_Cardinality_RawValue(GPBField *message) {
GPBDescriptor *descriptor = [GPBField descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality];
- return GPBGetMessageInt32Field(message, field);
+ return GPBGetMessageRawEnumField(message, field);
}
void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value) {
GPBDescriptor *descriptor = [GPBField descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality];
- GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);
+ GPBSetMessageRawEnumField(message, field, value);
}
#pragma mark - Enum GPBField_Kind
@@ -513,16 +524,16 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBEnum_FieldNumber_Name,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBEnum__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "enumvalueArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBEnumValue),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBEnumValue),
.number = GPBEnum_FieldNumber_EnumvalueArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBEnum__storage_, enumvalueArray),
@@ -531,7 +542,7 @@
},
{
.name = "optionsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBOption),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBOption),
.number = GPBEnum_FieldNumber_OptionsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBEnum__storage_, optionsArray),
@@ -540,7 +551,7 @@
},
{
.name = "sourceContext",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBSourceContext),
.number = GPBEnum_FieldNumber_SourceContext,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBEnum__storage_, sourceContext),
@@ -553,7 +564,7 @@
.number = GPBEnum_FieldNumber_Syntax,
.hasIndex = 2,
.offset = (uint32_t)offsetof(GPBEnum__storage_, syntax),
- .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeEnum,
},
};
@@ -564,7 +575,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBEnum__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -578,13 +589,13 @@
int32_t GPBEnum_Syntax_RawValue(GPBEnum *message) {
GPBDescriptor *descriptor = [GPBEnum descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax];
- return GPBGetMessageInt32Field(message, field);
+ return GPBGetMessageRawEnumField(message, field);
}
void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value) {
GPBDescriptor *descriptor = [GPBEnum descriptor];
GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax];
- GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);
+ GPBSetMessageRawEnumField(message, field, value);
}
#pragma mark - GPBEnumValue
@@ -610,25 +621,25 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBEnumValue_FieldNumber_Name,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBEnumValue__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "number",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBEnumValue_FieldNumber_Number,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBEnumValue__storage_, number),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt32,
},
{
.name = "optionsArray",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBOption),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBOption),
.number = GPBEnumValue_FieldNumber_OptionsArray,
.hasIndex = GPBNoHasBit,
.offset = (uint32_t)offsetof(GPBEnumValue__storage_, optionsArray),
@@ -643,7 +654,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBEnumValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -675,16 +686,16 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "name",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBOption_FieldNumber_Name,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBOption__storage_, name),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
{
.name = "value",
- .dataTypeSpecific.className = GPBStringifySymbol(GPBAny),
+ .dataTypeSpecific.clazz = GPBObjCClass(GPBAny),
.number = GPBOption_FieldNumber_Value,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBOption__storage_, value),
@@ -699,7 +710,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBOption__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/GPBUtilities.h b/objectivec/GPBUtilities.h
index 5464dfb..75759b2 100644
--- a/objectivec/GPBUtilities.h
+++ b/objectivec/GPBUtilities.h
@@ -34,6 +34,8 @@
#import "GPBMessage.h"
#import "GPBRuntimeTypes.h"
+@class GPBOneofDescriptor;
+
CF_EXTERN_C_BEGIN
NS_ASSUME_NONNULL_BEGIN
@@ -92,8 +94,17 @@
**/
void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field);
+/**
+ * Clears the given oneof field for the given message.
+ *
+ * @param self The message for which to clear the field.
+ * @param oneof The oneof to clear.
+ **/
+void GPBClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof);
+
//%PDDM-EXPAND GPB_ACCESSORS()
// This block of code is generated, do not edit it directly.
+// clang-format off
//
@@ -384,6 +395,7 @@
GPBFieldDescriptor *field,
id dictionary);
+// clang-format on
//%PDDM-EXPAND-END GPB_ACCESSORS()
/**
diff --git a/objectivec/GPBUtilities.m b/objectivec/GPBUtilities.m
index 0d3a080..ee79d00 100644
--- a/objectivec/GPBUtilities.m
+++ b/objectivec/GPBUtilities.m
@@ -62,6 +62,12 @@
// Marked unused because currently only called from asserts/debug.
static NSString *TypeToString(GPBDataType dataType) __attribute__ ((unused));
+// Helper for clearing oneofs.
+static void GPBMaybeClearOneofPrivate(GPBMessage *self,
+ GPBOneofDescriptor *oneof,
+ int32_t oneofHasIndex,
+ uint32_t fieldNumberNotToClear);
+
NSData *GPBEmptyNSData(void) {
static dispatch_once_t onceToken;
static NSData *defaultNSData = nil;
@@ -267,17 +273,28 @@
return;
}
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (GPBFieldStoresObject(field)) {
// Object types are handled slightly differently, they need to be released.
uint8_t *storage = (uint8_t *)self->messageStorage_;
- id *typePtr = (id *)&storage[field->description_->offset];
+ id *typePtr = (id *)&storage[fieldDesc->offset];
[*typePtr release];
*typePtr = nil;
} else {
// POD types just need to clear the has bit as the Get* method will
// fetch the default when needed.
}
- GPBSetHasIvarField(self, field, NO);
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, NO);
+}
+
+void GPBClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof) {
+ #if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof,
+ @"OneofDescriptor %@ doesn't appear to be for %@ messages.",
+ oneof.name, [self class]);
+ #endif
+ GPBFieldDescriptor *firstField = oneof->fields_[0];
+ GPBMaybeClearOneofPrivate(self, oneof, firstField->description_->hasIndex, 0);
}
BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) {
@@ -324,8 +341,10 @@
}
}
-void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
- int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) {
+static void GPBMaybeClearOneofPrivate(GPBMessage *self,
+ GPBOneofDescriptor *oneof,
+ int32_t oneofHasIndex,
+ uint32_t fieldNumberNotToClear) {
uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex);
if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) {
// Do nothing/nothing set in the oneof.
@@ -356,6 +375,9 @@
//%TYPE GPBGetMessage##NAME##Field(GPBMessage *self,
//% TYPE$S NAME$S GPBFieldDescriptor *field) {
//%#if defined(DEBUG) && DEBUG
+//% NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+//% @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+//% field.name, [self class]);
//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
//% GPBDataType##NAME),
//% @"Attempting to get value of TYPE from field %@ "
@@ -377,15 +399,10 @@
//% NAME$S GPBFieldDescriptor *field,
//% NAME$S TYPE value) {
//% if (self == nil || field == nil) return;
-//% GPBFileSyntax syntax = [self descriptor].file.syntax;
-//% GPBSet##NAME##IvarWithFieldInternal(self, field, value, syntax);
-//%}
-//%
-//%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self,
-//% NAME$S GPBFieldDescriptor *field,
-//% NAME$S TYPE value,
-//% NAME$S GPBFileSyntax syntax) {
//%#if defined(DEBUG) && DEBUG
+//% NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+//% @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+//% field.name, [self class]);
//% NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
//% GPBDataType##NAME),
//% @"Attempting to set field %@ of %@ which is of type %@ with "
@@ -393,10 +410,16 @@
//% [self class], field.name,
//% TypeToString(GPBGetFieldDataType(field)));
//%#endif
+//% GPBSet##NAME##IvarWithFieldPrivate(self, field, value);
+//%}
+//%
+//%void GPBSet##NAME##IvarWithFieldPrivate(GPBMessage *self,
+//% NAME$S GPBFieldDescriptor *field,
+//% NAME$S TYPE value) {
//% GPBOneofDescriptor *oneof = field->containingOneof_;
+//% GPBMessageFieldDescription *fieldDesc = field->description_;
//% if (oneof) {
-//% GPBMessageFieldDescription *fieldDesc = field->description_;
-//% GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+//% GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
//% }
//%#if defined(DEBUG) && DEBUG
//% NSCAssert(self->messageStorage_ != NULL,
@@ -407,14 +430,13 @@
//% if (self->messageStorage_ == NULL) return;
//%#endif
//% uint8_t *storage = (uint8_t *)self->messageStorage_;
-//% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
+//% TYPE *typePtr = (TYPE *)&storage[fieldDesc->offset];
//% *typePtr = value;
-//% // proto2: any value counts as having been set; proto3, it
-//% // 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);
+//% // If the value is zero, then we only count the field as "set" if the field
+//% // shouldn't auto clear on zero.
+//% BOOL hasValue = ((value != (TYPE)0)
+//% || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+//% GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
//% GPBBecomeVisibleToAutocreator(self);
//%}
//%
@@ -504,43 +526,37 @@
[oldValue release];
}
-// This exists only for briging some aliased types, nothing else should use it.
+// This exists only for bridging some aliased types, nothing else should use it.
static void GPBSetObjectIvarWithField(GPBMessage *self,
GPBFieldDescriptor *field, id value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain],
- syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]);
}
static void GPBSetCopyObjectIvarWithField(GPBMessage *self,
GPBFieldDescriptor *field, id value);
// GPBSetCopyObjectIvarWithField is blocked from the analyzer because it flags
-// a leak for the -copy even though GPBSetRetainedObjectIvarWithFieldInternal
+// a leak for the -copy even though GPBSetRetainedObjectIvarWithFieldPrivate
// is marked as consuming the value. Note: For some reason this doesn't happen
// with the -retain in GPBSetObjectIvarWithField.
#if !defined(__clang_analyzer__)
-// This exists only for briging some aliased types, nothing else should use it.
+// This exists only for bridging some aliased types, nothing else should use it.
static void GPBSetCopyObjectIvarWithField(GPBMessage *self,
GPBFieldDescriptor *field, id value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value copy],
- syntax);
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value copy]);
}
#endif // !defined(__clang_analyzer__)
-void GPBSetObjectIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field, id value,
- GPBFileSyntax syntax) {
- GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain],
- syntax);
+void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field, id value) {
+ GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]);
}
-void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- id value, GPBFileSyntax syntax) {
+void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ id value) {
NSCAssert(self->messageStorage_ != NULL,
@"%@: All messages should have storage (from init)",
[self class]);
@@ -579,39 +595,30 @@
// valueData/valueMessage.
}
#endif // DEBUG
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (!isMapOrArray) {
// Non repeated/map can be in an oneof, clear any existing value from the
// oneof.
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
// Clear "has" if they are being set to nil.
BOOL setHasValue = (value != nil);
- // Under proto3, Bytes & String fields get cleared by resetting them to
- // their default (empty) values, so if they are set to something of length
- // zero, they are being cleared.
- if ((syntax == GPBFileSyntaxProto3) && !fieldIsMessage &&
+ // If the field should clear on a "zero" value, then check if the string/data
+ // was zero length, and clear instead.
+ if (((fieldDesc->flags & GPBFieldClearHasIvarOnZero) != 0) &&
([value length] == 0)) {
- // 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;
- }
+ setHasValue = NO;
+ // 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);
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, setHasValue);
}
uint8_t *storage = (uint8_t *)self->messageStorage_;
- id *typePtr = (id *)&storage[field->description_->offset];
+ id *typePtr = (id *)&storage[fieldDesc->offset];
id oldValue = *typePtr;
@@ -678,23 +685,22 @@
// Only exists for public api, no core code should use this.
int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) {
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- return GPBGetEnumIvarWithFieldInternal(self, field, syntax);
-}
+ #if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
+ NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
+ @"Attempting to get value of type Enum from field %@ "
+ @"of %@ which is of type %@.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+ #endif
-int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- GPBFileSyntax syntax) {
-#if defined(DEBUG) && DEBUG
- NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
- @"Attempting to get value of type Enum from field %@ "
- @"of %@ which is of type %@.",
- [self class], field.name,
- TypeToString(GPBGetFieldDataType(field)));
-#endif
int32_t result = GPBGetMessageInt32Field(self, field);
// If this is presevering unknown enums, make sure the value is valid before
// returning it.
+
+ GPBFileSyntax syntax = [self descriptor].file.syntax;
if (GPBHasPreservingUnknownEnumSemantics(syntax) &&
![field isValidEnumValue:result]) {
result = kGPBUnrecognizedEnumeratorValue;
@@ -705,27 +711,28 @@
// Only exists for public api, no core code should use this.
void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field,
int32_t value) {
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
+ #if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
+ NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type Enum.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+ #endif
+ GPBSetEnumIvarWithFieldPrivate(self, field, value);
}
-void GPBSetEnumIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field, int32_t value,
- GPBFileSyntax syntax) {
-#if defined(DEBUG) && DEBUG
- NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum,
- @"Attempting to set field %@ of %@ which is of type %@ with "
- @"value of type Enum.",
- [self class], field.name,
- TypeToString(GPBGetFieldDataType(field)));
-#endif
+void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field, int32_t value) {
// Don't allow in unknown values. Proto3 can use the Raw method.
if (![field isValidEnumValue:value]) {
[NSException raise:NSInvalidArgumentException
format:@"%@.%@: Attempt to set an unknown enum value (%d)",
[self class], field.name, value];
}
- GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
+ GPBSetInt32IvarWithFieldPrivate(self, field, value);
}
// Only exists for public api, no core code should use this.
@@ -738,13 +745,15 @@
// Only exists for public api, no core code should use this.
void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field,
int32_t value) {
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
+ GPBSetInt32IvarWithFieldPrivate(self, field, value);
}
BOOL GPBGetMessageBoolField(GPBMessage *self,
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
@"Attempting to get value of type bool from field %@ "
@"of %@ which is of type %@.",
@@ -768,25 +777,26 @@
GPBFieldDescriptor *field,
BOOL value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetBoolIvarWithFieldInternal(self, field, value, syntax);
+ #if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
+ NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
+ @"Attempting to set field %@ of %@ which is of type %@ with "
+ @"value of type bool.",
+ [self class], field.name,
+ TypeToString(GPBGetFieldDataType(field)));
+ #endif
+ GPBSetBoolIvarWithFieldPrivate(self, field, value);
}
-void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- BOOL value,
- GPBFileSyntax syntax) {
-#if defined(DEBUG) && DEBUG
- NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool),
- @"Attempting to set field %@ of %@ which is of type %@ with "
- @"value of type bool.",
- [self class], field.name,
- TypeToString(GPBGetFieldDataType(field)));
-#endif
+void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ BOOL value) {
GPBMessageFieldDescription *fieldDesc = field->description_;
GPBOneofDescriptor *oneof = field->containingOneof_;
if (oneof) {
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
// Bools are stored in the has bits to avoid needing explicit space in the
@@ -795,21 +805,24 @@
// the offset is never negative)
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 or be in a oneof.
- BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
- || (value != (BOOL)0)
- || (field->containingOneof_ != NULL));
- GPBSetHasIvarField(self, field, hasValue);
+ // If the value is zero, then we only count the field as "set" if the field
+ // shouldn't auto clear on zero.
+ BOOL hasValue = ((value != (BOOL)0)
+ || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int32, int32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
int32_t GPBGetMessageInt32Field(GPBMessage *self,
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeInt32),
@"Attempting to get value of int32_t from field %@ "
@@ -831,15 +844,10 @@
GPBFieldDescriptor *field,
int32_t value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetInt32IvarWithFieldInternal(self, field, value, syntax);
-}
-
-void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- int32_t value,
- GPBFileSyntax syntax) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeInt32),
@"Attempting to set field %@ of %@ which is of type %@ with "
@@ -847,10 +855,16 @@
[self class], field.name,
TypeToString(GPBGetFieldDataType(field)));
#endif
+ GPBSetInt32IvarWithFieldPrivate(self, field, value);
+}
+
+void GPBSetInt32IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int32_t value) {
GPBOneofDescriptor *oneof = field->containingOneof_;
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (oneof) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@@ -861,23 +875,27 @@
if (self->messageStorage_ == NULL) return;
#endif
uint8_t *storage = (uint8_t *)self->messageStorage_;
- int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
+ int32_t *typePtr = (int32_t *)&storage[fieldDesc->offset];
*typePtr = value;
- // proto2: any value counts as having been set; proto3, it
- // 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);
+ // If the value is zero, then we only count the field as "set" if the field
+ // shouldn't auto clear on zero.
+ BOOL hasValue = ((value != (int32_t)0)
+ || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
+// clang-format on
//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt32, uint32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
uint32_t GPBGetMessageUInt32Field(GPBMessage *self,
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeUInt32),
@"Attempting to get value of uint32_t from field %@ "
@@ -899,15 +917,10 @@
GPBFieldDescriptor *field,
uint32_t value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetUInt32IvarWithFieldInternal(self, field, value, syntax);
-}
-
-void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- uint32_t value,
- GPBFileSyntax syntax) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeUInt32),
@"Attempting to set field %@ of %@ which is of type %@ with "
@@ -915,10 +928,16 @@
[self class], field.name,
TypeToString(GPBGetFieldDataType(field)));
#endif
+ GPBSetUInt32IvarWithFieldPrivate(self, field, value);
+}
+
+void GPBSetUInt32IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ uint32_t value) {
GPBOneofDescriptor *oneof = field->containingOneof_;
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (oneof) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@@ -929,23 +948,27 @@
if (self->messageStorage_ == NULL) return;
#endif
uint8_t *storage = (uint8_t *)self->messageStorage_;
- uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
+ uint32_t *typePtr = (uint32_t *)&storage[fieldDesc->offset];
*typePtr = value;
- // proto2: any value counts as having been set; proto3, it
- // 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);
+ // If the value is zero, then we only count the field as "set" if the field
+ // shouldn't auto clear on zero.
+ BOOL hasValue = ((value != (uint32_t)0)
+ || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
+// clang-format on
//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int64, int64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
int64_t GPBGetMessageInt64Field(GPBMessage *self,
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeInt64),
@"Attempting to get value of int64_t from field %@ "
@@ -967,15 +990,10 @@
GPBFieldDescriptor *field,
int64_t value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetInt64IvarWithFieldInternal(self, field, value, syntax);
-}
-
-void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- int64_t value,
- GPBFileSyntax syntax) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeInt64),
@"Attempting to set field %@ of %@ which is of type %@ with "
@@ -983,10 +1001,16 @@
[self class], field.name,
TypeToString(GPBGetFieldDataType(field)));
#endif
+ GPBSetInt64IvarWithFieldPrivate(self, field, value);
+}
+
+void GPBSetInt64IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int64_t value) {
GPBOneofDescriptor *oneof = field->containingOneof_;
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (oneof) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@@ -997,23 +1021,27 @@
if (self->messageStorage_ == NULL) return;
#endif
uint8_t *storage = (uint8_t *)self->messageStorage_;
- int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
+ int64_t *typePtr = (int64_t *)&storage[fieldDesc->offset];
*typePtr = value;
- // proto2: any value counts as having been set; proto3, it
- // 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);
+ // If the value is zero, then we only count the field as "set" if the field
+ // shouldn't auto clear on zero.
+ BOOL hasValue = ((value != (int64_t)0)
+ || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
+// clang-format on
//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt64, uint64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
uint64_t GPBGetMessageUInt64Field(GPBMessage *self,
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeUInt64),
@"Attempting to get value of uint64_t from field %@ "
@@ -1035,15 +1063,10 @@
GPBFieldDescriptor *field,
uint64_t value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetUInt64IvarWithFieldInternal(self, field, value, syntax);
-}
-
-void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- uint64_t value,
- GPBFileSyntax syntax) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeUInt64),
@"Attempting to set field %@ of %@ which is of type %@ with "
@@ -1051,10 +1074,16 @@
[self class], field.name,
TypeToString(GPBGetFieldDataType(field)));
#endif
+ GPBSetUInt64IvarWithFieldPrivate(self, field, value);
+}
+
+void GPBSetUInt64IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ uint64_t value) {
GPBOneofDescriptor *oneof = field->containingOneof_;
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (oneof) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@@ -1065,23 +1094,27 @@
if (self->messageStorage_ == NULL) return;
#endif
uint8_t *storage = (uint8_t *)self->messageStorage_;
- uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
+ uint64_t *typePtr = (uint64_t *)&storage[fieldDesc->offset];
*typePtr = value;
- // proto2: any value counts as having been set; proto3, it
- // 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);
+ // If the value is zero, then we only count the field as "set" if the field
+ // shouldn't auto clear on zero.
+ BOOL hasValue = ((value != (uint64_t)0)
+ || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
+// clang-format on
//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Float, float)
// This block of code is generated, do not edit it directly.
+// clang-format off
float GPBGetMessageFloatField(GPBMessage *self,
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeFloat),
@"Attempting to get value of float from field %@ "
@@ -1103,15 +1136,10 @@
GPBFieldDescriptor *field,
float value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetFloatIvarWithFieldInternal(self, field, value, syntax);
-}
-
-void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- float value,
- GPBFileSyntax syntax) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeFloat),
@"Attempting to set field %@ of %@ which is of type %@ with "
@@ -1119,10 +1147,16 @@
[self class], field.name,
TypeToString(GPBGetFieldDataType(field)));
#endif
+ GPBSetFloatIvarWithFieldPrivate(self, field, value);
+}
+
+void GPBSetFloatIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ float value) {
GPBOneofDescriptor *oneof = field->containingOneof_;
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (oneof) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@@ -1133,23 +1167,27 @@
if (self->messageStorage_ == NULL) return;
#endif
uint8_t *storage = (uint8_t *)self->messageStorage_;
- float *typePtr = (float *)&storage[field->description_->offset];
+ float *typePtr = (float *)&storage[fieldDesc->offset];
*typePtr = value;
- // proto2: any value counts as having been set; proto3, it
- // 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);
+ // If the value is zero, then we only count the field as "set" if the field
+ // shouldn't auto clear on zero.
+ BOOL hasValue = ((value != (float)0)
+ || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
+// clang-format on
//%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Double, double)
// This block of code is generated, do not edit it directly.
+// clang-format off
double GPBGetMessageDoubleField(GPBMessage *self,
GPBFieldDescriptor *field) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeDouble),
@"Attempting to get value of double from field %@ "
@@ -1171,15 +1209,10 @@
GPBFieldDescriptor *field,
double value) {
if (self == nil || field == nil) return;
- GPBFileSyntax syntax = [self descriptor].file.syntax;
- GPBSetDoubleIvarWithFieldInternal(self, field, value, syntax);
-}
-
-void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- double value,
- GPBFileSyntax syntax) {
#if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] fieldWithNumber:field.number] == field,
+ @"FieldDescriptor %@ doesn't appear to be for %@ messages.",
+ field.name, [self class]);
NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field),
GPBDataTypeDouble),
@"Attempting to set field %@ of %@ which is of type %@ with "
@@ -1187,10 +1220,16 @@
[self class], field.name,
TypeToString(GPBGetFieldDataType(field)));
#endif
+ GPBSetDoubleIvarWithFieldPrivate(self, field, value);
+}
+
+void GPBSetDoubleIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ double value) {
GPBOneofDescriptor *oneof = field->containingOneof_;
+ GPBMessageFieldDescription *fieldDesc = field->description_;
if (oneof) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
+ GPBMaybeClearOneofPrivate(self, oneof, fieldDesc->hasIndex, fieldDesc->number);
}
#if defined(DEBUG) && DEBUG
NSCAssert(self->messageStorage_ != NULL,
@@ -1201,23 +1240,24 @@
if (self->messageStorage_ == NULL) return;
#endif
uint8_t *storage = (uint8_t *)self->messageStorage_;
- double *typePtr = (double *)&storage[field->description_->offset];
+ double *typePtr = (double *)&storage[fieldDesc->offset];
*typePtr = value;
- // proto2: any value counts as having been set; proto3, it
- // 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);
+ // If the value is zero, then we only count the field as "set" if the field
+ // shouldn't auto clear on zero.
+ BOOL hasValue = ((value != (double)0)
+ || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0));
+ GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
+// clang-format on
//%PDDM-EXPAND-END (6 expansions)
// Aliases are function calls that are virtually the same.
//%PDDM-EXPAND IVAR_ALIAS_DEFN_COPY_OBJECT(String, NSString)
// This block of code is generated, do not edit it directly.
+// clang-format off
// Only exists for public api, no core code should use this.
NSString *GPBGetMessageStringField(GPBMessage *self,
@@ -1248,8 +1288,10 @@
GPBSetCopyObjectIvarWithField(self, field, (id)value);
}
+// clang-format on
//%PDDM-EXPAND IVAR_ALIAS_DEFN_COPY_OBJECT(Bytes, NSData)
// This block of code is generated, do not edit it directly.
+// clang-format off
// Only exists for public api, no core code should use this.
NSData *GPBGetMessageBytesField(GPBMessage *self,
@@ -1280,8 +1322,10 @@
GPBSetCopyObjectIvarWithField(self, field, (id)value);
}
+// clang-format on
//%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Message, GPBMessage)
// This block of code is generated, do not edit it directly.
+// clang-format off
// Only exists for public api, no core code should use this.
GPBMessage *GPBGetMessageMessageField(GPBMessage *self,
@@ -1312,8 +1356,10 @@
GPBSetObjectIvarWithField(self, field, (id)value);
}
+// clang-format on
//%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Group, GPBMessage)
// This block of code is generated, do not edit it directly.
+// clang-format off
// Only exists for public api, no core code should use this.
GPBMessage *GPBGetMessageGroupField(GPBMessage *self,
@@ -1344,6 +1390,7 @@
GPBSetObjectIvarWithField(self, field, (id)value);
}
+// clang-format on
//%PDDM-EXPAND-END (4 expansions)
// GPBGetMessageRepeatedField is defined in GPBMessage.m
@@ -2192,8 +2239,36 @@
return result;
}
+#pragma mark Legacy methods old generated code calls
+
+// Shim from the older generated code into the runtime.
+void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int32_t value,
+ GPBFileSyntax syntax) {
+#pragma unused(syntax)
+ GPBSetMessageInt32Field(self, field, value);
+}
+
+void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
+ int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) {
+#pragma unused(fieldNumberNotToClear)
+ #if defined(DEBUG) && DEBUG
+ NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof,
+ @"OneofDescriptor %@ doesn't appear to be for %@ messages.",
+ oneof.name, [self class]);
+ GPBFieldDescriptor *firstField = oneof->fields_[0];
+ NSCAssert(firstField->description_->hasIndex == oneofHasIndex,
+ @"Internal error, oneofHasIndex (%d) doesn't match (%d).",
+ firstField->description_->hasIndex, oneofHasIndex);
+ #endif
+ GPBMaybeClearOneofPrivate(self, oneof, oneofHasIndex, 0);
+}
+
#pragma clang diagnostic pop
+#pragma mark Misc Helpers
+
BOOL GPBClassHasSel(Class aClass, SEL sel) {
// NOTE: We have to use class_copyMethodList, all other runtime method
// lookups actually also resolve the method implementation and this
diff --git a/objectivec/GPBUtilities_PackagePrivate.h b/objectivec/GPBUtilities_PackagePrivate.h
index 336a745..9c29c39 100644
--- a/objectivec/GPBUtilities_PackagePrivate.h
+++ b/objectivec/GPBUtilities_PackagePrivate.h
@@ -35,14 +35,23 @@
#import "GPBDescriptor_PackagePrivate.h"
// Macros for stringifying library symbols. These are used in the generated
-// PB descriptor classes wherever a library symbol name is represented as a
-// string. See README.google for more information.
+// GPB descriptor classes wherever a library symbol name is represented as a
+// string.
#define GPBStringify(S) #S
#define GPBStringifySymbol(S) GPBStringify(S)
#define GPBNSStringify(S) @#S
#define GPBNSStringifySymbol(S) GPBNSStringify(S)
+// Macros for generating a Class from a class name. These are used in
+// the generated GPB descriptor classes wherever an Objective C class
+// reference is needed for a generated class.
+#define GPBObjCClassSymbol(name) OBJC_CLASS_$_##name
+#define GPBObjCClass(name) \
+ ((__bridge Class)&(GPBObjCClassSymbol(name)))
+#define GPBObjCClassDeclaration(name) \
+ extern const GPBObjcClass_t GPBObjCClassSymbol(name)
+
// Constant to internally mark when there is no has bit.
#define GPBNoHasBit INT32_MAX
@@ -197,94 +206,83 @@
GPBMessageFieldDescription *fieldDesc = field->description_;
return GPBGetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number);
}
-GPB_INLINE void GPBSetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field,
- BOOL value) {
- GPBMessageFieldDescription *fieldDesc = field->description_;
- GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, value);
-}
-
-void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
- int32_t oneofHasIndex, uint32_t fieldNumberNotToClear);
#pragma clang diagnostic pop
//%PDDM-DEFINE GPB_IVAR_SET_DECL(NAME, TYPE)
-//%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self,
-//% NAME$S GPBFieldDescriptor *field,
-//% NAME$S TYPE value,
-//% NAME$S GPBFileSyntax syntax);
+//%void GPBSet##NAME##IvarWithFieldPrivate(GPBMessage *self,
+//% NAME$S GPBFieldDescriptor *field,
+//% NAME$S TYPE value);
//%PDDM-EXPAND GPB_IVAR_SET_DECL(Bool, BOOL)
// This block of code is generated, do not edit it directly.
+// clang-format off
-void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- BOOL value,
- GPBFileSyntax syntax);
+void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ BOOL value);
+// clang-format on
//%PDDM-EXPAND GPB_IVAR_SET_DECL(Int32, int32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
-void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- int32_t value,
- GPBFileSyntax syntax);
+void GPBSetInt32IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int32_t value);
+// clang-format on
//%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt32, uint32_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
-void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- uint32_t value,
- GPBFileSyntax syntax);
+void GPBSetUInt32IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ uint32_t value);
+// clang-format on
//%PDDM-EXPAND GPB_IVAR_SET_DECL(Int64, int64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
-void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- int64_t value,
- GPBFileSyntax syntax);
+void GPBSetInt64IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int64_t value);
+// clang-format on
//%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt64, uint64_t)
// This block of code is generated, do not edit it directly.
+// clang-format off
-void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- uint64_t value,
- GPBFileSyntax syntax);
+void GPBSetUInt64IvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ uint64_t value);
+// clang-format on
//%PDDM-EXPAND GPB_IVAR_SET_DECL(Float, float)
// This block of code is generated, do not edit it directly.
+// clang-format off
-void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- float value,
- GPBFileSyntax syntax);
+void GPBSetFloatIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ float value);
+// clang-format on
//%PDDM-EXPAND GPB_IVAR_SET_DECL(Double, double)
// This block of code is generated, do not edit it directly.
+// clang-format off
-void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- double value,
- GPBFileSyntax syntax);
-//%PDDM-EXPAND GPB_IVAR_SET_DECL(Enum, int32_t)
-// This block of code is generated, do not edit it directly.
+void GPBSetDoubleIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ double value);
+// clang-format on
+//%PDDM-EXPAND-END (7 expansions)
-void GPBSetEnumIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- int32_t value,
- GPBFileSyntax syntax);
-//%PDDM-EXPAND-END (8 expansions)
-
-int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- GPBFileSyntax syntax);
+void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int32_t value);
id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
-void GPBSetObjectIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field, id value,
- GPBFileSyntax syntax);
-void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
- GPBFieldDescriptor *field,
- id __attribute__((ns_consumed))
- value,
- GPBFileSyntax syntax);
+void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field, id value);
+void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ id __attribute__((ns_consumed))
+ value);
// GPBGetObjectIvarWithField will automatically create the field (message) if
// it doesn't exist. GPBGetObjectIvarWithFieldNoAutocreate will return nil.
@@ -311,6 +309,15 @@
NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key,
NSString *inputString);
+
+// Shims from the older generated code into the runtime.
+void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int32_t value,
+ GPBFileSyntax syntax);
+void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
+ int32_t oneofHasIndex, uint32_t fieldNumberNotToClear);
+
// A series of selectors that are used solely to get @encoding values
// for them by the dynamic protobuf runtime code. See
// GPBMessageEncodingForSelector for details. GPBRootObject conforms to
diff --git a/objectivec/GPBWellKnownTypes.h b/objectivec/GPBWellKnownTypes.h
index bb6c780..784ba9f 100644
--- a/objectivec/GPBWellKnownTypes.h
+++ b/objectivec/GPBWellKnownTypes.h
@@ -37,13 +37,13 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Any.pbobjc.h>
- #import <protobuf/Duration.pbobjc.h>
- #import <protobuf/Timestamp.pbobjc.h>
+ #import <Protobuf/GPBAny.pbobjc.h>
+ #import <Protobuf/GPBDuration.pbobjc.h>
+ #import <Protobuf/GPBTimestamp.pbobjc.h>
#else
- #import "google/protobuf/Any.pbobjc.h"
- #import "google/protobuf/Duration.pbobjc.h"
- #import "google/protobuf/Timestamp.pbobjc.h"
+ #import "GPBAny.pbobjc.h"
+ #import "GPBDuration.pbobjc.h"
+ #import "GPBTimestamp.pbobjc.h"
#endif
NS_ASSUME_NONNULL_BEGIN
diff --git a/objectivec/GPBWrappers.pbobjc.h b/objectivec/GPBWrappers.pbobjc.h
new file mode 100644
index 0000000..713bafc
--- /dev/null
+++ b/objectivec/GPBWrappers.pbobjc.h
@@ -0,0 +1,219 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: google/protobuf/wrappers.proto
+
+// This CPP symbol can be defined to use imports that match up to the framework
+// imports needed when using CocoaPods.
+#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
+ #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
+#endif
+
+#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/GPBDescriptor.h>
+ #import <Protobuf/GPBMessage.h>
+ #import <Protobuf/GPBRootObject.h>
+#else
+ #import "GPBDescriptor.h"
+ #import "GPBMessage.h"
+ #import "GPBRootObject.h"
+#endif
+
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30004 < 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)
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+
+CF_EXTERN_C_BEGIN
+
+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.
+ **/
+GPB_FINAL @interface GPBWrappersRoot : GPBRootObject
+@end
+
+#pragma mark - GPBDoubleValue
+
+typedef GPB_ENUM(GPBDoubleValue_FieldNumber) {
+ GPBDoubleValue_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `double`.
+ *
+ * The JSON representation for `DoubleValue` is JSON number.
+ **/
+GPB_FINAL @interface GPBDoubleValue : GPBMessage
+
+/** The double value. */
+@property(nonatomic, readwrite) double value;
+
+@end
+
+#pragma mark - GPBFloatValue
+
+typedef GPB_ENUM(GPBFloatValue_FieldNumber) {
+ GPBFloatValue_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `float`.
+ *
+ * The JSON representation for `FloatValue` is JSON number.
+ **/
+GPB_FINAL @interface GPBFloatValue : GPBMessage
+
+/** The float value. */
+@property(nonatomic, readwrite) float value;
+
+@end
+
+#pragma mark - GPBInt64Value
+
+typedef GPB_ENUM(GPBInt64Value_FieldNumber) {
+ GPBInt64Value_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `int64`.
+ *
+ * The JSON representation for `Int64Value` is JSON string.
+ **/
+GPB_FINAL @interface GPBInt64Value : GPBMessage
+
+/** The int64 value. */
+@property(nonatomic, readwrite) int64_t value;
+
+@end
+
+#pragma mark - GPBUInt64Value
+
+typedef GPB_ENUM(GPBUInt64Value_FieldNumber) {
+ GPBUInt64Value_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `uint64`.
+ *
+ * The JSON representation for `UInt64Value` is JSON string.
+ **/
+GPB_FINAL @interface GPBUInt64Value : GPBMessage
+
+/** The uint64 value. */
+@property(nonatomic, readwrite) uint64_t value;
+
+@end
+
+#pragma mark - GPBInt32Value
+
+typedef GPB_ENUM(GPBInt32Value_FieldNumber) {
+ GPBInt32Value_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `int32`.
+ *
+ * The JSON representation for `Int32Value` is JSON number.
+ **/
+GPB_FINAL @interface GPBInt32Value : GPBMessage
+
+/** The int32 value. */
+@property(nonatomic, readwrite) int32_t value;
+
+@end
+
+#pragma mark - GPBUInt32Value
+
+typedef GPB_ENUM(GPBUInt32Value_FieldNumber) {
+ GPBUInt32Value_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `uint32`.
+ *
+ * The JSON representation for `UInt32Value` is JSON number.
+ **/
+GPB_FINAL @interface GPBUInt32Value : GPBMessage
+
+/** The uint32 value. */
+@property(nonatomic, readwrite) uint32_t value;
+
+@end
+
+#pragma mark - GPBBoolValue
+
+typedef GPB_ENUM(GPBBoolValue_FieldNumber) {
+ GPBBoolValue_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `bool`.
+ *
+ * The JSON representation for `BoolValue` is JSON `true` and `false`.
+ **/
+GPB_FINAL @interface GPBBoolValue : GPBMessage
+
+/** The bool value. */
+@property(nonatomic, readwrite) BOOL value;
+
+@end
+
+#pragma mark - GPBStringValue
+
+typedef GPB_ENUM(GPBStringValue_FieldNumber) {
+ GPBStringValue_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `string`.
+ *
+ * The JSON representation for `StringValue` is JSON string.
+ **/
+GPB_FINAL @interface GPBStringValue : GPBMessage
+
+/** The string value. */
+@property(nonatomic, readwrite, copy, null_resettable) NSString *value;
+
+@end
+
+#pragma mark - GPBBytesValue
+
+typedef GPB_ENUM(GPBBytesValue_FieldNumber) {
+ GPBBytesValue_FieldNumber_Value = 1,
+};
+
+/**
+ * Wrapper message for `bytes`.
+ *
+ * The JSON representation for `BytesValue` is JSON string.
+ **/
+GPB_FINAL @interface GPBBytesValue : GPBMessage
+
+/** The bytes value. */
+@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
+
+@end
+
+NS_ASSUME_NONNULL_END
+
+CF_EXTERN_C_END
+
+#pragma clang diagnostic pop
+
+// @@protoc_insertion_point(global_scope)
diff --git a/objectivec/google/protobuf/Wrappers.pbobjc.m b/objectivec/GPBWrappers.pbobjc.m
similarity index 82%
rename from objectivec/google/protobuf/Wrappers.pbobjc.m
rename to objectivec/GPBWrappers.pbobjc.m
index f91d345..32201d4 100644
--- a/objectivec/google/protobuf/Wrappers.pbobjc.m
+++ b/objectivec/GPBWrappers.pbobjc.m
@@ -8,15 +8,15 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBProtocolBuffers_RuntimeSupport.h>
+ #import <Protobuf/GPBProtocolBuffers_RuntimeSupport.h>
#else
#import "GPBProtocolBuffers_RuntimeSupport.h"
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/Wrappers.pbobjc.h>
+ #import <Protobuf/GPBWrappers.pbobjc.h>
#else
- #import "google/protobuf/Wrappers.pbobjc.h"
+ #import "GPBWrappers.pbobjc.h"
#endif
// @@protoc_insertion_point(imports)
@@ -66,11 +66,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBDoubleValue_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBDoubleValue__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeDouble,
},
};
@@ -81,7 +81,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBDoubleValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -111,11 +111,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBFloatValue_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBFloatValue__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeFloat,
},
};
@@ -126,7 +126,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBFloatValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -156,11 +156,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBInt64Value_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBInt64Value__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt64,
},
};
@@ -171,7 +171,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBInt64Value__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -201,11 +201,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBUInt64Value_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBUInt64Value__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeUInt64,
},
};
@@ -216,7 +216,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBUInt64Value__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -246,11 +246,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBInt32Value_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBInt32Value__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeInt32,
},
};
@@ -261,7 +261,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBInt32Value__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -291,11 +291,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBUInt32Value_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBUInt32Value__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeUInt32,
},
};
@@ -306,7 +306,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBUInt32Value__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -335,11 +335,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBBoolValue_FieldNumber_Value,
.hasIndex = 0,
.offset = 1, // Stored in _has_storage_ to save space.
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeBool,
},
};
@@ -350,7 +350,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBBoolValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -380,11 +380,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBStringValue_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBStringValue__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeString,
},
};
@@ -395,7 +395,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBStringValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
@@ -425,11 +425,11 @@
static GPBMessageFieldDescription fields[] = {
{
.name = "value",
- .dataTypeSpecific.className = NULL,
+ .dataTypeSpecific.clazz = Nil,
.number = GPBBytesValue_FieldNumber_Value,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBBytesValue__storage_, value),
- .flags = GPBFieldOptional,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero),
.dataType = GPBDataTypeBytes,
},
};
@@ -440,7 +440,7 @@
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBBytesValue__storage_)
- flags:GPBDescriptorInitializationFlag_None];
+ flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)];
#if defined(DEBUG) && DEBUG
NSAssert(descriptor == nil, @"Startup recursed!");
#endif // DEBUG
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
index 9b0af31..365fdc3 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
@@ -35,6 +35,7 @@
8BBEA4BB147C729200C4ADB7 /* libProtocolBuffers.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7461B52E0F94FAF800A0C422 /* libProtocolBuffers.a */; };
8BD3981F14BE59D70081D629 /* GPBUnittestProtos.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */; };
8BF8193514A0DDA600A2C982 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
+ 8BFF9D1A23AD582300E63E32 /* GPBMessageTests+ClassNames.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BFF9D1923AD582200E63E32 /* GPBMessageTests+ClassNames.m */; };
F401DC2D1A8D444600FCC765 /* GPBArray.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC2B1A8D444600FCC765 /* GPBArray.m */; };
F401DC331A8E5C0200FCC765 /* GPBArrayTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */; };
F40EE4AB206BF8B90071091A /* GPBCompileTest01.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE488206BF8B00071091A /* GPBCompileTest01.m */; };
@@ -80,18 +81,18 @@
F4584D821ECCB52A00803AB6 /* GPBExtensionRegistryTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F4584D7E1ECCB38900803AB6 /* GPBExtensionRegistryTest.m */; };
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */; };
F45E57C71AE6DC6A000B7D99 /* text_format_map_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F45E57C61AE6DC6A000B7D99 /* text_format_map_unittest_data.txt */; };
- F47476E51D21A524007C7B1A /* Duration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248D41A92826400BC1EC6 /* Duration.pbobjc.m */; };
- F47476E61D21A524007C7B1A /* Timestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248D61A92826400BC1EC6 /* Timestamp.pbobjc.m */; };
+ F47CF92B23D9006000C7B24C /* GPBStruct.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF91F23D9005F00C7B24C /* GPBStruct.pbobjc.m */; };
+ F47CF92F23D9006000C7B24C /* GPBSourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF92323D9006000C7B24C /* GPBSourceContext.pbobjc.m */; };
+ F47CF93123D9006000C7B24C /* GPBType.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF92523D9006000C7B24C /* GPBType.pbobjc.m */; };
+ F47CF93223D9006000C7B24C /* GPBWrappers.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF92623D9006000C7B24C /* GPBWrappers.pbobjc.m */; };
+ F47CF93423D9006000C7B24C /* GPBFieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF92823D9006000C7B24C /* GPBFieldMask.pbobjc.m */; };
+ F47CF93523D9006000C7B24C /* GPBTimestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF92923D9006000C7B24C /* GPBTimestamp.pbobjc.m */; };
+ F47CF94123D902D500C7B24C /* GPBEmpty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF93923D902D500C7B24C /* GPBEmpty.pbobjc.m */; };
+ F47CF94223D902D500C7B24C /* GPBApi.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF93A23D902D500C7B24C /* GPBApi.pbobjc.m */; };
+ F47CF94323D902D500C7B24C /* GPBAny.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF93B23D902D500C7B24C /* GPBAny.pbobjc.m */; };
+ F47CF94623D902D500C7B24C /* GPBDuration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF93E23D902D500C7B24C /* GPBDuration.pbobjc.m */; };
F4B51B1E1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4B51B1D1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm */; };
F4C4B9E41E1D976300D3B61D /* GPBDictionaryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4C4B9E21E1D974F00D3B61D /* GPBDictionaryTests.m */; };
- F4E675971B21D0000054530B /* Any.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675871B21D0000054530B /* Any.pbobjc.m */; };
- F4E675991B21D0000054530B /* Api.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675891B21D0000054530B /* Api.pbobjc.m */; };
- F4E6759B1B21D0000054530B /* Empty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E6758B1B21D0000054530B /* Empty.pbobjc.m */; };
- F4E6759D1B21D0000054530B /* FieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E6758D1B21D0000054530B /* FieldMask.pbobjc.m */; };
- F4E6759F1B21D0000054530B /* SourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E6758F1B21D0000054530B /* SourceContext.pbobjc.m */; };
- 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 */; };
F4F53F8A219CC4F2001EABF4 /* text_format_extensions_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F4F53F89219CC4F2001EABF4 /* text_format_extensions_unittest_data.txt */; };
F4F8D8831D789FD9002CE128 /* GPBUnittestProtos2.m in Sources */ = {isa = PBXBuildFile; fileRef = F4F8D8811D789FCE002CE128 /* GPBUnittestProtos2.m */; };
/* End PBXBuildFile section */
@@ -155,10 +156,6 @@
8B4248BA1A8C256A00BC1EC6 /* GPBSwiftTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GPBSwiftTests.swift; sourceTree = "<group>"; };
8B4248CF1A927E1500BC1EC6 /* GPBWellKnownTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBWellKnownTypes.h; sourceTree = "<group>"; };
8B4248D01A927E1500BC1EC6 /* GPBWellKnownTypes.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWellKnownTypes.m; sourceTree = "<group>"; };
- 8B4248D31A92826400BC1EC6 /* Duration.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Duration.pbobjc.h; path = google/protobuf/Duration.pbobjc.h; sourceTree = "<group>"; };
- 8B4248D41A92826400BC1EC6 /* Duration.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Duration.pbobjc.m; path = google/protobuf/Duration.pbobjc.m; sourceTree = "<group>"; };
- 8B4248D51A92826400BC1EC6 /* Timestamp.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Timestamp.pbobjc.h; path = google/protobuf/Timestamp.pbobjc.h; sourceTree = "<group>"; };
- 8B4248D61A92826400BC1EC6 /* Timestamp.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Timestamp.pbobjc.m; path = google/protobuf/Timestamp.pbobjc.m; sourceTree = "<group>"; };
8B4248DB1A92933A00BC1EC6 /* GPBWellKnownTypesTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWellKnownTypesTest.m; sourceTree = "<group>"; };
8B42494C1A92A16600BC1EC6 /* duration.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = duration.proto; path = ../src/google/protobuf/duration.proto; sourceTree = "<group>"; };
8B42494D1A92A16600BC1EC6 /* timestamp.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = timestamp.proto; path = ../src/google/protobuf/timestamp.proto; sourceTree = "<group>"; };
@@ -181,6 +178,7 @@
8BD3981D14BE54220081D629 /* unittest_enormous_descriptor.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = unittest_enormous_descriptor.proto; path = ../../src/google/protobuf/unittest_enormous_descriptor.proto; sourceTree = "<group>"; };
8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBUnittestProtos.m; sourceTree = "<group>"; };
8BEB5AE01498033E0078BF9D /* GPBRuntimeTypes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRuntimeTypes.h; sourceTree = "<group>"; };
+ 8BFF9D1923AD582200E63E32 /* GPBMessageTests+ClassNames.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GPBMessageTests+ClassNames.m"; sourceTree = "<group>"; };
F401DC2A1A8D444600FCC765 /* GPBArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBArray.h; sourceTree = "<group>"; };
F401DC2B1A8D444600FCC765 /* GPBArray.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArray.m; sourceTree = "<group>"; };
F401DC321A8E5C0200FCC765 /* GPBArrayTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArrayTests.m; sourceTree = "<group>"; };
@@ -235,6 +233,26 @@
F4584D7E1ECCB38900803AB6 /* GPBExtensionRegistryTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBExtensionRegistryTest.m; sourceTree = "<group>"; };
F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBExtensionInternals.m; sourceTree = "<group>"; };
F45E57C61AE6DC6A000B7D99 /* text_format_map_unittest_data.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = text_format_map_unittest_data.txt; sourceTree = "<group>"; };
+ F47CF91F23D9005F00C7B24C /* GPBStruct.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBStruct.pbobjc.m; sourceTree = "<group>"; };
+ F47CF92023D9006000C7B24C /* GPBSourceContext.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBSourceContext.pbobjc.h; sourceTree = "<group>"; };
+ F47CF92123D9006000C7B24C /* GPBStruct.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBStruct.pbobjc.h; sourceTree = "<group>"; };
+ F47CF92223D9006000C7B24C /* GPBFieldMask.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBFieldMask.pbobjc.h; sourceTree = "<group>"; };
+ F47CF92323D9006000C7B24C /* GPBSourceContext.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBSourceContext.pbobjc.m; sourceTree = "<group>"; };
+ F47CF92423D9006000C7B24C /* GPBTimestamp.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBTimestamp.pbobjc.h; sourceTree = "<group>"; };
+ F47CF92523D9006000C7B24C /* GPBType.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBType.pbobjc.m; sourceTree = "<group>"; };
+ F47CF92623D9006000C7B24C /* GPBWrappers.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWrappers.pbobjc.m; sourceTree = "<group>"; };
+ F47CF92723D9006000C7B24C /* GPBWrappers.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBWrappers.pbobjc.h; sourceTree = "<group>"; };
+ F47CF92823D9006000C7B24C /* GPBFieldMask.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBFieldMask.pbobjc.m; sourceTree = "<group>"; };
+ F47CF92923D9006000C7B24C /* GPBTimestamp.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBTimestamp.pbobjc.m; sourceTree = "<group>"; };
+ F47CF92A23D9006000C7B24C /* GPBType.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBType.pbobjc.h; sourceTree = "<group>"; };
+ F47CF93723D902D500C7B24C /* GPBAny.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBAny.pbobjc.h; sourceTree = "<group>"; };
+ F47CF93823D902D500C7B24C /* GPBEmpty.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBEmpty.pbobjc.h; sourceTree = "<group>"; };
+ F47CF93923D902D500C7B24C /* GPBEmpty.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBEmpty.pbobjc.m; sourceTree = "<group>"; };
+ F47CF93A23D902D500C7B24C /* GPBApi.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBApi.pbobjc.m; sourceTree = "<group>"; };
+ F47CF93B23D902D500C7B24C /* GPBAny.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBAny.pbobjc.m; sourceTree = "<group>"; };
+ F47CF93C23D902D500C7B24C /* GPBDuration.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBDuration.pbobjc.h; sourceTree = "<group>"; };
+ F47CF93D23D902D500C7B24C /* GPBApi.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBApi.pbobjc.h; sourceTree = "<group>"; };
+ F47CF93E23D902D500C7B24C /* GPBDuration.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDuration.pbobjc.m; sourceTree = "<group>"; };
F4AC9E1D1A8BEB3500BD6E83 /* unittest_cycle.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_cycle.proto; sourceTree = "<group>"; };
F4B51B1D1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = GPBObjectiveCPlusPlusTest.mm; sourceTree = "<group>"; };
F4B6B8AF1A9CC98000892426 /* GPBUnknownField_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBUnknownField_PackagePrivate.h; sourceTree = "<group>"; };
@@ -243,22 +261,6 @@
F4B6B8B81A9CD1DE00892426 /* GPBRootObject_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRootObject_PackagePrivate.h; sourceTree = "<group>"; };
F4C4B9E21E1D974F00D3B61D /* GPBDictionaryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDictionaryTests.m; sourceTree = "<group>"; };
F4CF31701B162ED800BD9B06 /* unittest_objc_startup.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_objc_startup.proto; sourceTree = "<group>"; };
- F4E675861B21D0000054530B /* Any.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Any.pbobjc.h; path = google/protobuf/Any.pbobjc.h; sourceTree = "<group>"; };
- F4E675871B21D0000054530B /* Any.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Any.pbobjc.m; path = google/protobuf/Any.pbobjc.m; sourceTree = "<group>"; };
- F4E675881B21D0000054530B /* Api.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Api.pbobjc.h; path = google/protobuf/Api.pbobjc.h; sourceTree = "<group>"; };
- F4E675891B21D0000054530B /* Api.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Api.pbobjc.m; path = google/protobuf/Api.pbobjc.m; sourceTree = "<group>"; };
- F4E6758A1B21D0000054530B /* Empty.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Empty.pbobjc.h; path = google/protobuf/Empty.pbobjc.h; sourceTree = "<group>"; };
- F4E6758B1B21D0000054530B /* Empty.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Empty.pbobjc.m; path = google/protobuf/Empty.pbobjc.m; sourceTree = "<group>"; };
- F4E6758C1B21D0000054530B /* FieldMask.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FieldMask.pbobjc.h; path = google/protobuf/FieldMask.pbobjc.h; sourceTree = "<group>"; };
- F4E6758D1B21D0000054530B /* FieldMask.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FieldMask.pbobjc.m; path = google/protobuf/FieldMask.pbobjc.m; sourceTree = "<group>"; };
- F4E6758E1B21D0000054530B /* SourceContext.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SourceContext.pbobjc.h; path = google/protobuf/SourceContext.pbobjc.h; sourceTree = "<group>"; };
- F4E6758F1B21D0000054530B /* SourceContext.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SourceContext.pbobjc.m; path = google/protobuf/SourceContext.pbobjc.m; sourceTree = "<group>"; };
- F4E675901B21D0000054530B /* Struct.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Struct.pbobjc.h; path = google/protobuf/Struct.pbobjc.h; sourceTree = "<group>"; };
- F4E675911B21D0000054530B /* Struct.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Struct.pbobjc.m; path = google/protobuf/Struct.pbobjc.m; sourceTree = "<group>"; };
- F4E675921B21D0000054530B /* Type.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Type.pbobjc.h; path = google/protobuf/Type.pbobjc.h; sourceTree = "<group>"; };
- F4E675931B21D0000054530B /* Type.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Type.pbobjc.m; path = google/protobuf/Type.pbobjc.m; sourceTree = "<group>"; };
- F4E675941B21D0000054530B /* Wrappers.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Wrappers.pbobjc.h; path = google/protobuf/Wrappers.pbobjc.h; sourceTree = "<group>"; };
- F4E675951B21D0000054530B /* Wrappers.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Wrappers.pbobjc.m; path = google/protobuf/Wrappers.pbobjc.m; sourceTree = "<group>"; };
F4E675A61B21D05C0054530B /* any.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = any.proto; path = ../src/google/protobuf/any.proto; sourceTree = "<group>"; };
F4E675A71B21D05C0054530B /* api.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = api.proto; path = ../src/google/protobuf/api.proto; sourceTree = "<group>"; };
F4E675A81B21D05C0054530B /* empty.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = empty.proto; path = ../src/google/protobuf/empty.proto; sourceTree = "<group>"; };
@@ -340,35 +342,35 @@
29B97315FDCFA39411CA2CEA /* Generated */ = {
isa = PBXGroup;
children = (
- F4E675861B21D0000054530B /* Any.pbobjc.h */,
- F4E675871B21D0000054530B /* Any.pbobjc.m */,
+ F47CF93723D902D500C7B24C /* GPBAny.pbobjc.h */,
+ F47CF93B23D902D500C7B24C /* GPBAny.pbobjc.m */,
+ F47CF93D23D902D500C7B24C /* GPBApi.pbobjc.h */,
+ F47CF93A23D902D500C7B24C /* GPBApi.pbobjc.m */,
+ F47CF93C23D902D500C7B24C /* GPBDuration.pbobjc.h */,
+ F47CF93E23D902D500C7B24C /* GPBDuration.pbobjc.m */,
+ F47CF93823D902D500C7B24C /* GPBEmpty.pbobjc.h */,
+ F47CF93923D902D500C7B24C /* GPBEmpty.pbobjc.m */,
+ F47CF92223D9006000C7B24C /* GPBFieldMask.pbobjc.h */,
+ F47CF92823D9006000C7B24C /* GPBFieldMask.pbobjc.m */,
+ F47CF92023D9006000C7B24C /* GPBSourceContext.pbobjc.h */,
+ F47CF92323D9006000C7B24C /* GPBSourceContext.pbobjc.m */,
+ F47CF92123D9006000C7B24C /* GPBStruct.pbobjc.h */,
+ F47CF91F23D9005F00C7B24C /* GPBStruct.pbobjc.m */,
+ F47CF92423D9006000C7B24C /* GPBTimestamp.pbobjc.h */,
+ F47CF92923D9006000C7B24C /* GPBTimestamp.pbobjc.m */,
+ F47CF92A23D9006000C7B24C /* GPBType.pbobjc.h */,
+ F47CF92523D9006000C7B24C /* GPBType.pbobjc.m */,
+ F47CF92723D9006000C7B24C /* GPBWrappers.pbobjc.h */,
+ F47CF92623D9006000C7B24C /* GPBWrappers.pbobjc.m */,
F4E675A61B21D05C0054530B /* any.proto */,
- F4E675881B21D0000054530B /* Api.pbobjc.h */,
- F4E675891B21D0000054530B /* Api.pbobjc.m */,
F4E675A71B21D05C0054530B /* api.proto */,
- 8B4248D31A92826400BC1EC6 /* Duration.pbobjc.h */,
- 8B4248D41A92826400BC1EC6 /* Duration.pbobjc.m */,
8B42494C1A92A16600BC1EC6 /* duration.proto */,
- F4E6758A1B21D0000054530B /* Empty.pbobjc.h */,
- F4E6758B1B21D0000054530B /* Empty.pbobjc.m */,
F4E675A81B21D05C0054530B /* empty.proto */,
F4E675A91B21D05C0054530B /* field_mask.proto */,
- F4E6758C1B21D0000054530B /* FieldMask.pbobjc.h */,
- F4E6758D1B21D0000054530B /* FieldMask.pbobjc.m */,
F4E675AA1B21D05C0054530B /* source_context.proto */,
- F4E6758E1B21D0000054530B /* SourceContext.pbobjc.h */,
- F4E6758F1B21D0000054530B /* SourceContext.pbobjc.m */,
- F4E675901B21D0000054530B /* Struct.pbobjc.h */,
- F4E675911B21D0000054530B /* Struct.pbobjc.m */,
F4E675AB1B21D05C0054530B /* struct.proto */,
- 8B4248D51A92826400BC1EC6 /* Timestamp.pbobjc.h */,
- 8B4248D61A92826400BC1EC6 /* Timestamp.pbobjc.m */,
8B42494D1A92A16600BC1EC6 /* timestamp.proto */,
- F4E675921B21D0000054530B /* Type.pbobjc.h */,
- F4E675931B21D0000054530B /* Type.pbobjc.m */,
F4E675AC1B21D05C0054530B /* type.proto */,
- F4E675941B21D0000054530B /* Wrappers.pbobjc.h */,
- F4E675951B21D0000054530B /* Wrappers.pbobjc.m */,
F4E675AD1B21D05C0054530B /* wrappers.proto */,
);
name = Generated;
@@ -485,6 +487,7 @@
7461B6A30F94FDF800A0C422 /* GPBMessageTests.m */,
F4487C821AAF6AB300531423 /* GPBMessageTests+Merge.m */,
F4487C741AADF7F500531423 /* GPBMessageTests+Runtime.m */,
+ 8BFF9D1923AD582200E63E32 /* GPBMessageTests+ClassNames.m */,
F4487C7E1AAF62CD00531423 /* GPBMessageTests+Serialization.m */,
F4B51B1D1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm */,
F41C175C1833D3310064ED4D /* GPBPerfTests.m */,
@@ -656,6 +659,7 @@
developmentRegion = English;
hasScannedForEncodings = 1;
knownRegions = (
+ English,
en,
);
mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */;
@@ -708,30 +712,30 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ F47CF93123D9006000C7B24C /* GPBType.pbobjc.m in Sources */,
7461B53C0F94FB4E00A0C422 /* GPBCodedInputStream.m in Sources */,
- F4E6759B1B21D0000054530B /* Empty.pbobjc.m in Sources */,
+ F47CF93223D9006000C7B24C /* GPBWrappers.pbobjc.m in Sources */,
+ F47CF94123D902D500C7B24C /* GPBEmpty.pbobjc.m in Sources */,
+ F47CF94623D902D500C7B24C /* GPBDuration.pbobjc.m in Sources */,
+ F47CF92F23D9006000C7B24C /* GPBSourceContext.pbobjc.m in Sources */,
7461B53D0F94FB4E00A0C422 /* GPBCodedOutputStream.m in Sources */,
F401DC2D1A8D444600FCC765 /* GPBArray.m in Sources */,
7461B5490F94FB4E00A0C422 /* GPBExtensionRegistry.m in Sources */,
- F4E6759D1B21D0000054530B /* FieldMask.pbobjc.m in Sources */,
7461B54C0F94FB4E00A0C422 /* GPBUnknownField.m in Sources */,
7461B5530F94FB4E00A0C422 /* GPBMessage.m in Sources */,
- F47476E51D21A524007C7B1A /* Duration.pbobjc.m in Sources */,
7461B5610F94FB4E00A0C422 /* GPBUnknownFieldSet.m in Sources */,
+ F47CF93423D9006000C7B24C /* GPBFieldMask.pbobjc.m in Sources */,
7461B5630F94FB4E00A0C422 /* GPBUtilities.m in Sources */,
7461B5640F94FB4E00A0C422 /* GPBWireFormat.m in Sources */,
- F4E675991B21D0000054530B /* Api.pbobjc.m in Sources */,
- F4E6759F1B21D0000054530B /* SourceContext.pbobjc.m in Sources */,
F4353D231ABB1537005A6198 /* GPBDictionary.m in Sources */,
8B79657B14992E3F002FFBFC /* GPBRootObject.m in Sources */,
+ F47CF93523D9006000C7B24C /* GPBTimestamp.pbobjc.m in Sources */,
8B96157414C8C38C00A2AC0B /* GPBDescriptor.m in Sources */,
- F4E675971B21D0000054530B /* Any.pbobjc.m in Sources */,
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */,
+ F47CF92B23D9006000C7B24C /* GPBStruct.pbobjc.m in Sources */,
+ F47CF94323D902D500C7B24C /* GPBAny.pbobjc.m in Sources */,
8B4248D21A927E1500BC1EC6 /* GPBWellKnownTypes.m in Sources */,
- F4E675A31B21D0000054530B /* Type.pbobjc.m in Sources */,
- F4E675A11B21D0000054530B /* Struct.pbobjc.m in Sources */,
- F4E675A51B21D0000054530B /* Wrappers.pbobjc.m in Sources */,
- F47476E61D21A524007C7B1A /* Timestamp.pbobjc.m in Sources */,
+ F47CF94223D902D500C7B24C /* GPBApi.pbobjc.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -770,6 +774,7 @@
8B4248BB1A8C256A00BC1EC6 /* GPBSwiftTests.swift in Sources */,
F40EE50C206C06640071091A /* GPBCompileTest25.m in Sources */,
F4584D821ECCB52A00803AB6 /* GPBExtensionRegistryTest.m in Sources */,
+ 8BFF9D1A23AD582300E63E32 /* GPBMessageTests+ClassNames.m in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
F4487C751AADF7F500531423 /* GPBMessageTests+Runtime.m in Sources */,
F40EE4AC206BF8B90071091A /* GPBCompileTest02.m in Sources */,
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
index 9f1d825..12d0ffd 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
@@ -36,6 +36,7 @@
8BBEA4BB147C729200C4ADB7 /* libProtocolBuffers.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7461B52E0F94FAF800A0C422 /* libProtocolBuffers.a */; };
8BD3981F14BE59D70081D629 /* GPBUnittestProtos.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */; };
8BF8193514A0DDA600A2C982 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
+ 8BFF9D1C23AD593C00E63E32 /* GPBMessageTests+ClassNames.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BFF9D1B23AD593B00E63E32 /* GPBMessageTests+ClassNames.m */; };
F401DC351A8E5C6F00FCC765 /* GPBArrayTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */; };
F40EE4F0206BF91E0071091A /* GPBCompileTest01.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CD206BF9170071091A /* GPBCompileTest01.m */; };
F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C6206BF9170071091A /* GPBCompileTest02.m */; };
@@ -81,18 +82,18 @@
F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F4584D801ECCB39E00803AB6 /* GPBExtensionRegistryTest.m */; };
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */; };
F45E57C91AE6DC98000B7D99 /* text_format_map_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F45E57C81AE6DC98000B7D99 /* text_format_map_unittest_data.txt */; };
- F47476E91D21A537007C7B1A /* Duration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248DE1A929C7D00BC1EC6 /* Duration.pbobjc.m */; };
- F47476EA1D21A537007C7B1A /* Timestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248E01A929C7D00BC1EC6 /* Timestamp.pbobjc.m */; };
+ F47CF95F23D903C600C7B24C /* GPBDuration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF94B23D903C600C7B24C /* GPBDuration.pbobjc.m */; };
+ F47CF96023D903C600C7B24C /* GPBWrappers.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF94C23D903C600C7B24C /* GPBWrappers.pbobjc.m */; };
+ F47CF96223D903C600C7B24C /* GPBFieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF94E23D903C600C7B24C /* GPBFieldMask.pbobjc.m */; };
+ F47CF96423D903C600C7B24C /* GPBStruct.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF95023D903C600C7B24C /* GPBStruct.pbobjc.m */; };
+ F47CF96523D903C600C7B24C /* GPBApi.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF95123D903C600C7B24C /* GPBApi.pbobjc.m */; };
+ F47CF96623D903C600C7B24C /* GPBSourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF95223D903C600C7B24C /* GPBSourceContext.pbobjc.m */; };
+ F47CF96723D903C600C7B24C /* GPBEmpty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF95323D903C600C7B24C /* GPBEmpty.pbobjc.m */; };
+ F47CF96923D903C600C7B24C /* GPBTimestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF95523D903C600C7B24C /* GPBTimestamp.pbobjc.m */; };
+ F47CF96C23D903C600C7B24C /* GPBType.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF95823D903C600C7B24C /* GPBType.pbobjc.m */; };
+ F47CF96D23D903C600C7B24C /* GPBAny.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF95923D903C600C7B24C /* GPBAny.pbobjc.m */; };
F4B51B1C1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4B51B1B1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm */; };
F4C4B9E71E1D97BF00D3B61D /* GPBDictionaryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */; };
- F4E675D01B21D1620054530B /* Any.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675B71B21D1440054530B /* Any.pbobjc.m */; };
- F4E675D11B21D1620054530B /* Api.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675B91B21D1440054530B /* Api.pbobjc.m */; };
- F4E675D21B21D1620054530B /* Empty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675BC1B21D1440054530B /* Empty.pbobjc.m */; };
- F4E675D31B21D1620054530B /* FieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675BE1B21D1440054530B /* FieldMask.pbobjc.m */; };
- F4E675D41B21D1620054530B /* SourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675C01B21D1440054530B /* SourceContext.pbobjc.m */; };
- 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 */; };
F4F53F8C219CC5DF001EABF4 /* text_format_extensions_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F4F53F8B219CC5DF001EABF4 /* text_format_extensions_unittest_data.txt */; };
F4F8D8861D78A193002CE128 /* GPBUnittestProtos2.m in Sources */ = {isa = PBXBuildFile; fileRef = F4F8D8841D78A186002CE128 /* GPBUnittestProtos2.m */; };
/* End PBXBuildFile section */
@@ -154,9 +155,6 @@
8B35468621A61EB2000BD30D /* unittest_objc_options.proto */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.protobuf; path = unittest_objc_options.proto; sourceTree = "<group>"; };
8B4248B21A8BD96D00BC1EC6 /* UnitTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "UnitTests-Bridging-Header.h"; sourceTree = "<group>"; };
8B4248B31A8BD96E00BC1EC6 /* GPBSwiftTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GPBSwiftTests.swift; sourceTree = "<group>"; };
- 8B4248DD1A929C7D00BC1EC6 /* Duration.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Duration.pbobjc.h; path = google/protobuf/Duration.pbobjc.h; sourceTree = "<group>"; };
- 8B4248DE1A929C7D00BC1EC6 /* Duration.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Duration.pbobjc.m; path = google/protobuf/Duration.pbobjc.m; sourceTree = "<group>"; };
- 8B4248E01A929C7D00BC1EC6 /* Timestamp.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Timestamp.pbobjc.m; path = google/protobuf/Timestamp.pbobjc.m; sourceTree = "<group>"; };
8B4248E11A929C8900BC1EC6 /* GPBWellKnownTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBWellKnownTypes.h; sourceTree = "<group>"; };
8B4248E21A929C8900BC1EC6 /* GPBWellKnownTypes.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWellKnownTypes.m; sourceTree = "<group>"; };
8B4248E51A929C9900BC1EC6 /* GPBWellKnownTypesTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWellKnownTypesTest.m; sourceTree = "<group>"; };
@@ -183,6 +181,7 @@
8BD3981D14BE54220081D629 /* unittest_enormous_descriptor.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = unittest_enormous_descriptor.proto; path = ../../src/google/protobuf/unittest_enormous_descriptor.proto; sourceTree = "<group>"; };
8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBUnittestProtos.m; sourceTree = "<group>"; };
8BEB5AE01498033E0078BF9D /* GPBRuntimeTypes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRuntimeTypes.h; sourceTree = "<group>"; };
+ 8BFF9D1B23AD593B00E63E32 /* GPBMessageTests+ClassNames.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GPBMessageTests+ClassNames.m"; sourceTree = "<group>"; };
F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArrayTests.m; sourceTree = "<group>"; };
F40EE4C2206BF9160071091A /* GPBCompileTest08.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest08.m; sourceTree = "<group>"; };
F40EE4C3206BF9160071091A /* GPBCompileTest04.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest04.m; sourceTree = "<group>"; };
@@ -237,6 +236,26 @@
F4584D801ECCB39E00803AB6 /* GPBExtensionRegistryTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GPBExtensionRegistryTest.m; path = Tests/GPBExtensionRegistryTest.m; sourceTree = SOURCE_ROOT; };
F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBExtensionInternals.m; sourceTree = "<group>"; };
F45E57C81AE6DC98000B7D99 /* text_format_map_unittest_data.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = text_format_map_unittest_data.txt; sourceTree = "<group>"; };
+ F47CF94723D903C500C7B24C /* GPBFieldMask.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBFieldMask.pbobjc.h; sourceTree = "<group>"; };
+ F47CF94823D903C500C7B24C /* GPBDuration.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBDuration.pbobjc.h; sourceTree = "<group>"; };
+ F47CF94923D903C500C7B24C /* GPBApi.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBApi.pbobjc.h; sourceTree = "<group>"; };
+ F47CF94A23D903C500C7B24C /* GPBEmpty.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBEmpty.pbobjc.h; sourceTree = "<group>"; };
+ F47CF94B23D903C600C7B24C /* GPBDuration.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDuration.pbobjc.m; sourceTree = "<group>"; };
+ F47CF94C23D903C600C7B24C /* GPBWrappers.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWrappers.pbobjc.m; sourceTree = "<group>"; };
+ F47CF94D23D903C600C7B24C /* GPBWrappers.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBWrappers.pbobjc.h; sourceTree = "<group>"; };
+ F47CF94E23D903C600C7B24C /* GPBFieldMask.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBFieldMask.pbobjc.m; sourceTree = "<group>"; };
+ F47CF94F23D903C600C7B24C /* GPBStruct.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBStruct.pbobjc.h; sourceTree = "<group>"; };
+ F47CF95023D903C600C7B24C /* GPBStruct.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBStruct.pbobjc.m; sourceTree = "<group>"; };
+ F47CF95123D903C600C7B24C /* GPBApi.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBApi.pbobjc.m; sourceTree = "<group>"; };
+ F47CF95223D903C600C7B24C /* GPBSourceContext.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBSourceContext.pbobjc.m; sourceTree = "<group>"; };
+ F47CF95323D903C600C7B24C /* GPBEmpty.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBEmpty.pbobjc.m; sourceTree = "<group>"; };
+ F47CF95423D903C600C7B24C /* GPBAny.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBAny.pbobjc.h; sourceTree = "<group>"; };
+ F47CF95523D903C600C7B24C /* GPBTimestamp.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBTimestamp.pbobjc.m; sourceTree = "<group>"; };
+ F47CF95623D903C600C7B24C /* GPBType.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBType.pbobjc.h; sourceTree = "<group>"; };
+ F47CF95723D903C600C7B24C /* GPBTimestamp.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBTimestamp.pbobjc.h; sourceTree = "<group>"; };
+ F47CF95823D903C600C7B24C /* GPBType.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBType.pbobjc.m; sourceTree = "<group>"; };
+ F47CF95923D903C600C7B24C /* GPBAny.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBAny.pbobjc.m; sourceTree = "<group>"; };
+ F47CF95A23D903C600C7B24C /* GPBSourceContext.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBSourceContext.pbobjc.h; sourceTree = "<group>"; };
F4AC9E1C1A8BEB1000BD6E83 /* unittest_cycle.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_cycle.proto; sourceTree = "<group>"; };
F4B51B1B1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = GPBObjectiveCPlusPlusTest.mm; sourceTree = "<group>"; };
F4B6B8B01A9CC99500892426 /* GPBUnknownField_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBUnknownField_PackagePrivate.h; sourceTree = "<group>"; };
@@ -245,23 +264,6 @@
F4B6B8B51A9CD1C600892426 /* GPBRootObject_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRootObject_PackagePrivate.h; sourceTree = "<group>"; };
F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDictionaryTests.m; sourceTree = "<group>"; };
F4CF31711B162EF500BD9B06 /* unittest_objc_startup.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_objc_startup.proto; sourceTree = "<group>"; };
- F4E675B61B21D1440054530B /* Any.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Any.pbobjc.h; path = google/protobuf/Any.pbobjc.h; sourceTree = "<group>"; };
- F4E675B71B21D1440054530B /* Any.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Any.pbobjc.m; path = google/protobuf/Any.pbobjc.m; sourceTree = "<group>"; };
- F4E675B81B21D1440054530B /* Api.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Api.pbobjc.h; path = google/protobuf/Api.pbobjc.h; sourceTree = "<group>"; };
- F4E675B91B21D1440054530B /* Api.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Api.pbobjc.m; path = google/protobuf/Api.pbobjc.m; sourceTree = "<group>"; };
- F4E675BB1B21D1440054530B /* Empty.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Empty.pbobjc.h; path = google/protobuf/Empty.pbobjc.h; sourceTree = "<group>"; };
- F4E675BC1B21D1440054530B /* Empty.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Empty.pbobjc.m; path = google/protobuf/Empty.pbobjc.m; sourceTree = "<group>"; };
- F4E675BD1B21D1440054530B /* FieldMask.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = FieldMask.pbobjc.h; path = google/protobuf/FieldMask.pbobjc.h; sourceTree = "<group>"; };
- F4E675BE1B21D1440054530B /* FieldMask.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = FieldMask.pbobjc.m; path = google/protobuf/FieldMask.pbobjc.m; sourceTree = "<group>"; };
- F4E675BF1B21D1440054530B /* SourceContext.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SourceContext.pbobjc.h; path = google/protobuf/SourceContext.pbobjc.h; sourceTree = "<group>"; };
- F4E675C01B21D1440054530B /* SourceContext.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = SourceContext.pbobjc.m; path = google/protobuf/SourceContext.pbobjc.m; sourceTree = "<group>"; };
- F4E675C11B21D1440054530B /* Struct.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Struct.pbobjc.h; path = google/protobuf/Struct.pbobjc.h; sourceTree = "<group>"; };
- F4E675C21B21D1440054530B /* Struct.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Struct.pbobjc.m; path = google/protobuf/Struct.pbobjc.m; sourceTree = "<group>"; };
- F4E675C31B21D1440054530B /* Timestamp.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Timestamp.pbobjc.h; path = google/protobuf/Timestamp.pbobjc.h; sourceTree = "<group>"; };
- F4E675C41B21D1440054530B /* Type.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Type.pbobjc.h; path = google/protobuf/Type.pbobjc.h; sourceTree = "<group>"; };
- F4E675C51B21D1440054530B /* Type.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Type.pbobjc.m; path = google/protobuf/Type.pbobjc.m; sourceTree = "<group>"; };
- F4E675C61B21D1440054530B /* Wrappers.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Wrappers.pbobjc.h; path = google/protobuf/Wrappers.pbobjc.h; sourceTree = "<group>"; };
- F4E675C71B21D1440054530B /* Wrappers.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Wrappers.pbobjc.m; path = google/protobuf/Wrappers.pbobjc.m; sourceTree = "<group>"; };
F4E675D81B21D1DE0054530B /* any.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = any.proto; path = ../src/google/protobuf/any.proto; sourceTree = "<group>"; };
F4E675D91B21D1DE0054530B /* api.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = api.proto; path = ../src/google/protobuf/api.proto; sourceTree = "<group>"; };
F4E675DA1B21D1DE0054530B /* empty.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = empty.proto; path = ../src/google/protobuf/empty.proto; sourceTree = "<group>"; };
@@ -344,35 +346,35 @@
29B97315FDCFA39411CA2CEA /* Generated */ = {
isa = PBXGroup;
children = (
- F4E675B61B21D1440054530B /* Any.pbobjc.h */,
- F4E675B71B21D1440054530B /* Any.pbobjc.m */,
+ F47CF95423D903C600C7B24C /* GPBAny.pbobjc.h */,
+ F47CF95923D903C600C7B24C /* GPBAny.pbobjc.m */,
+ F47CF94923D903C500C7B24C /* GPBApi.pbobjc.h */,
+ F47CF95123D903C600C7B24C /* GPBApi.pbobjc.m */,
+ F47CF94823D903C500C7B24C /* GPBDuration.pbobjc.h */,
+ F47CF94B23D903C600C7B24C /* GPBDuration.pbobjc.m */,
+ F47CF94A23D903C500C7B24C /* GPBEmpty.pbobjc.h */,
+ F47CF95323D903C600C7B24C /* GPBEmpty.pbobjc.m */,
+ F47CF94723D903C500C7B24C /* GPBFieldMask.pbobjc.h */,
+ F47CF94E23D903C600C7B24C /* GPBFieldMask.pbobjc.m */,
+ F47CF95A23D903C600C7B24C /* GPBSourceContext.pbobjc.h */,
+ F47CF95223D903C600C7B24C /* GPBSourceContext.pbobjc.m */,
+ F47CF94F23D903C600C7B24C /* GPBStruct.pbobjc.h */,
+ F47CF95023D903C600C7B24C /* GPBStruct.pbobjc.m */,
+ F47CF95723D903C600C7B24C /* GPBTimestamp.pbobjc.h */,
+ F47CF95523D903C600C7B24C /* GPBTimestamp.pbobjc.m */,
+ F47CF95623D903C600C7B24C /* GPBType.pbobjc.h */,
+ F47CF95823D903C600C7B24C /* GPBType.pbobjc.m */,
+ F47CF94D23D903C600C7B24C /* GPBWrappers.pbobjc.h */,
+ F47CF94C23D903C600C7B24C /* GPBWrappers.pbobjc.m */,
F4E675D81B21D1DE0054530B /* any.proto */,
- F4E675B81B21D1440054530B /* Api.pbobjc.h */,
- F4E675B91B21D1440054530B /* Api.pbobjc.m */,
F4E675D91B21D1DE0054530B /* api.proto */,
- 8B4248DD1A929C7D00BC1EC6 /* Duration.pbobjc.h */,
- 8B4248DE1A929C7D00BC1EC6 /* Duration.pbobjc.m */,
8B42494A1A92A0BA00BC1EC6 /* duration.proto */,
- F4E675BB1B21D1440054530B /* Empty.pbobjc.h */,
- F4E675BC1B21D1440054530B /* Empty.pbobjc.m */,
F4E675DA1B21D1DE0054530B /* empty.proto */,
F4E675DB1B21D1DE0054530B /* field_mask.proto */,
- F4E675BD1B21D1440054530B /* FieldMask.pbobjc.h */,
- F4E675BE1B21D1440054530B /* FieldMask.pbobjc.m */,
F4E675DC1B21D1DE0054530B /* source_context.proto */,
- F4E675BF1B21D1440054530B /* SourceContext.pbobjc.h */,
- F4E675C01B21D1440054530B /* SourceContext.pbobjc.m */,
- F4E675C11B21D1440054530B /* Struct.pbobjc.h */,
- F4E675C21B21D1440054530B /* Struct.pbobjc.m */,
F4E675DD1B21D1DE0054530B /* struct.proto */,
- F4E675C31B21D1440054530B /* Timestamp.pbobjc.h */,
- 8B4248E01A929C7D00BC1EC6 /* Timestamp.pbobjc.m */,
8B4249481A92A02300BC1EC6 /* timestamp.proto */,
- F4E675C41B21D1440054530B /* Type.pbobjc.h */,
- F4E675C51B21D1440054530B /* Type.pbobjc.m */,
F4E675DE1B21D1DE0054530B /* type.proto */,
- F4E675C61B21D1440054530B /* Wrappers.pbobjc.h */,
- F4E675C71B21D1440054530B /* Wrappers.pbobjc.m */,
F4E675DF1B21D1DE0054530B /* wrappers.proto */,
);
name = Generated;
@@ -491,6 +493,7 @@
7461B6A30F94FDF800A0C422 /* GPBMessageTests.m */,
F4487C841AAF6AC500531423 /* GPBMessageTests+Merge.m */,
F4487C761AADF84900531423 /* GPBMessageTests+Runtime.m */,
+ 8BFF9D1B23AD593B00E63E32 /* GPBMessageTests+ClassNames.m */,
F4487C801AAF62FC00531423 /* GPBMessageTests+Serialization.m */,
F4B51B1B1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm */,
F41C175C1833D3310064ED4D /* GPBPerfTests.m */,
@@ -663,6 +666,7 @@
developmentRegion = English;
hasScannedForEncodings = 1;
knownRegions = (
+ English,
en,
);
mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */;
@@ -716,29 +720,29 @@
buildActionMask = 2147483647;
files = (
7461B53C0F94FB4E00A0C422 /* GPBCodedInputStream.m in Sources */,
- F4E675D21B21D1620054530B /* Empty.pbobjc.m in Sources */,
+ F47CF96D23D903C600C7B24C /* GPBAny.pbobjc.m in Sources */,
+ F47CF96623D903C600C7B24C /* GPBSourceContext.pbobjc.m in Sources */,
+ F47CF96C23D903C600C7B24C /* GPBType.pbobjc.m in Sources */,
+ F47CF96423D903C600C7B24C /* GPBStruct.pbobjc.m in Sources */,
+ F47CF96723D903C600C7B24C /* GPBEmpty.pbobjc.m in Sources */,
F4487C731A9F906200531423 /* GPBArray.m in Sources */,
7461B53D0F94FB4E00A0C422 /* GPBCodedOutputStream.m in Sources */,
7461B5490F94FB4E00A0C422 /* GPBExtensionRegistry.m in Sources */,
- F4E675D31B21D1620054530B /* FieldMask.pbobjc.m in Sources */,
+ F47CF95F23D903C600C7B24C /* GPBDuration.pbobjc.m in Sources */,
7461B54C0F94FB4E00A0C422 /* GPBUnknownField.m in Sources */,
7461B5530F94FB4E00A0C422 /* GPBMessage.m in Sources */,
- F47476E91D21A537007C7B1A /* Duration.pbobjc.m in Sources */,
7461B5610F94FB4E00A0C422 /* GPBUnknownFieldSet.m in Sources */,
7461B5630F94FB4E00A0C422 /* GPBUtilities.m in Sources */,
7461B5640F94FB4E00A0C422 /* GPBWireFormat.m in Sources */,
- F4E675D11B21D1620054530B /* Api.pbobjc.m in Sources */,
- F4E675D41B21D1620054530B /* SourceContext.pbobjc.m in Sources */,
+ F47CF96023D903C600C7B24C /* GPBWrappers.pbobjc.m in Sources */,
+ F47CF96523D903C600C7B24C /* GPBApi.pbobjc.m in Sources */,
F4353D271ABB156F005A6198 /* GPBDictionary.m in Sources */,
8B79657B14992E3F002FFBFC /* GPBRootObject.m in Sources */,
+ F47CF96223D903C600C7B24C /* GPBFieldMask.pbobjc.m in Sources */,
8B96157414C8C38C00A2AC0B /* GPBDescriptor.m in Sources */,
- F4E675D01B21D1620054530B /* Any.pbobjc.m in Sources */,
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */,
8B4248E41A929C8900BC1EC6 /* GPBWellKnownTypes.m in Sources */,
- F4E675D61B21D1620054530B /* Type.pbobjc.m in Sources */,
- F4E675D51B21D1620054530B /* Struct.pbobjc.m in Sources */,
- F4E675D71B21D1620054530B /* Wrappers.pbobjc.m in Sources */,
- F47476EA1D21A537007C7B1A /* Timestamp.pbobjc.m in Sources */,
+ F47CF96923D903C600C7B24C /* GPBTimestamp.pbobjc.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -777,6 +781,7 @@
8B4248B41A8BD96E00BC1EC6 /* GPBSwiftTests.swift in Sources */,
F40EE512206C068D0071091A /* GPBCompileTest25.m in Sources */,
F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */,
+ 8BFF9D1C23AD593C00E63E32 /* GPBMessageTests+ClassNames.m in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
F4487C771AADF84900531423 /* GPBMessageTests+Runtime.m in Sources */,
F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */,
@@ -851,6 +856,7 @@
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
+ ENABLE_BITCODE = YES;
FRAMEWORK_SEARCH_PATHS = (
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
@@ -883,6 +889,7 @@
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
+ ENABLE_BITCODE = YES;
FRAMEWORK_SEARCH_PATHS = (
"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
"$(inherited)",
diff --git a/objectivec/ProtocolBuffers_tvOS.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_tvOS.xcodeproj/project.pbxproj
index c40c2aa..c7a8d85 100644
--- a/objectivec/ProtocolBuffers_tvOS.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_tvOS.xcodeproj/project.pbxproj
@@ -36,6 +36,7 @@
8BBEA4BB147C729200C4ADB7 /* libProtocolBuffers.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7461B52E0F94FAF800A0C422 /* libProtocolBuffers.a */; };
8BD3981F14BE59D70081D629 /* GPBUnittestProtos.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */; };
8BF8193514A0DDA600A2C982 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
+ 8BFF9D1E23AD599400E63E32 /* GPBMessageTests+ClassNames.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BFF9D1D23AD599400E63E32 /* GPBMessageTests+ClassNames.m */; };
F401DC351A8E5C6F00FCC765 /* GPBArrayTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */; };
F40EE4F0206BF91E0071091A /* GPBCompileTest01.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4CD206BF9170071091A /* GPBCompileTest01.m */; };
F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */ = {isa = PBXBuildFile; fileRef = F40EE4C6206BF9170071091A /* GPBCompileTest02.m */; };
@@ -81,18 +82,18 @@
F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F4584D801ECCB39E00803AB6 /* GPBExtensionRegistryTest.m */; };
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */; };
F45E57C91AE6DC98000B7D99 /* text_format_map_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F45E57C81AE6DC98000B7D99 /* text_format_map_unittest_data.txt */; };
- F47476E91D21A537007C7B1A /* Duration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248DE1A929C7D00BC1EC6 /* Duration.pbobjc.m */; };
- F47476EA1D21A537007C7B1A /* Timestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B4248E01A929C7D00BC1EC6 /* Timestamp.pbobjc.m */; };
+ F47CF98523D904E600C7B24C /* GPBApi.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97123D904E500C7B24C /* GPBApi.pbobjc.m */; };
+ F47CF98623D904E600C7B24C /* GPBEmpty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97223D904E500C7B24C /* GPBEmpty.pbobjc.m */; };
+ F47CF98923D904E600C7B24C /* GPBStruct.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97523D904E500C7B24C /* GPBStruct.pbobjc.m */; };
+ F47CF98A23D904E600C7B24C /* GPBFieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97623D904E500C7B24C /* GPBFieldMask.pbobjc.m */; };
+ F47CF98B23D904E600C7B24C /* GPBDuration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97723D904E500C7B24C /* GPBDuration.pbobjc.m */; };
+ F47CF98E23D904E600C7B24C /* GPBType.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97A23D904E600C7B24C /* GPBType.pbobjc.m */; };
+ F47CF98F23D904E600C7B24C /* GPBTimestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97B23D904E600C7B24C /* GPBTimestamp.pbobjc.m */; };
+ F47CF99323D904E600C7B24C /* GPBWrappers.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF97F23D904E600C7B24C /* GPBWrappers.pbobjc.m */; };
+ F47CF99423D904E600C7B24C /* GPBAny.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF98023D904E600C7B24C /* GPBAny.pbobjc.m */; };
+ F47CF99623D904E600C7B24C /* GPBSourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F47CF98223D904E600C7B24C /* GPBSourceContext.pbobjc.m */; };
F4B51B1C1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4B51B1B1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm */; };
F4C4B9E71E1D97BF00D3B61D /* GPBDictionaryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */; };
- F4E675D01B21D1620054530B /* Any.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675B71B21D1440054530B /* Any.pbobjc.m */; };
- F4E675D11B21D1620054530B /* Api.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675B91B21D1440054530B /* Api.pbobjc.m */; };
- F4E675D21B21D1620054530B /* Empty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675BC1B21D1440054530B /* Empty.pbobjc.m */; };
- F4E675D31B21D1620054530B /* FieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675BE1B21D1440054530B /* FieldMask.pbobjc.m */; };
- F4E675D41B21D1620054530B /* SourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675C01B21D1440054530B /* SourceContext.pbobjc.m */; };
- 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 */; };
F4F53F8C219CC5DF001EABF4 /* text_format_extensions_unittest_data.txt in Resources */ = {isa = PBXBuildFile; fileRef = F4F53F8B219CC5DF001EABF4 /* text_format_extensions_unittest_data.txt */; };
F4F8D8861D78A193002CE128 /* GPBUnittestProtos2.m in Sources */ = {isa = PBXBuildFile; fileRef = F4F8D8841D78A186002CE128 /* GPBUnittestProtos2.m */; };
/* End PBXBuildFile section */
@@ -154,9 +155,6 @@
8B35468621A61EB2000BD30D /* unittest_objc_options.proto */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.protobuf; path = unittest_objc_options.proto; sourceTree = "<group>"; };
8B4248B21A8BD96D00BC1EC6 /* UnitTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "UnitTests-Bridging-Header.h"; sourceTree = "<group>"; };
8B4248B31A8BD96E00BC1EC6 /* GPBSwiftTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GPBSwiftTests.swift; sourceTree = "<group>"; };
- 8B4248DD1A929C7D00BC1EC6 /* Duration.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Duration.pbobjc.h; path = google/protobuf/Duration.pbobjc.h; sourceTree = "<group>"; };
- 8B4248DE1A929C7D00BC1EC6 /* Duration.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Duration.pbobjc.m; path = google/protobuf/Duration.pbobjc.m; sourceTree = "<group>"; };
- 8B4248E01A929C7D00BC1EC6 /* Timestamp.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Timestamp.pbobjc.m; path = google/protobuf/Timestamp.pbobjc.m; sourceTree = "<group>"; };
8B4248E11A929C8900BC1EC6 /* GPBWellKnownTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBWellKnownTypes.h; sourceTree = "<group>"; };
8B4248E21A929C8900BC1EC6 /* GPBWellKnownTypes.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWellKnownTypes.m; sourceTree = "<group>"; };
8B4248E51A929C9900BC1EC6 /* GPBWellKnownTypesTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWellKnownTypesTest.m; sourceTree = "<group>"; };
@@ -183,6 +181,7 @@
8BD3981D14BE54220081D629 /* unittest_enormous_descriptor.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = unittest_enormous_descriptor.proto; path = ../../src/google/protobuf/unittest_enormous_descriptor.proto; sourceTree = "<group>"; };
8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBUnittestProtos.m; sourceTree = "<group>"; };
8BEB5AE01498033E0078BF9D /* GPBRuntimeTypes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRuntimeTypes.h; sourceTree = "<group>"; };
+ 8BFF9D1D23AD599400E63E32 /* GPBMessageTests+ClassNames.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GPBMessageTests+ClassNames.m"; sourceTree = "<group>"; };
F401DC341A8E5C6F00FCC765 /* GPBArrayTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBArrayTests.m; sourceTree = "<group>"; };
F40EE4C2206BF9160071091A /* GPBCompileTest08.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest08.m; sourceTree = "<group>"; };
F40EE4C3206BF9160071091A /* GPBCompileTest04.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBCompileTest04.m; sourceTree = "<group>"; };
@@ -237,6 +236,26 @@
F4584D801ECCB39E00803AB6 /* GPBExtensionRegistryTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GPBExtensionRegistryTest.m; path = Tests/GPBExtensionRegistryTest.m; sourceTree = SOURCE_ROOT; };
F45C69CB16DFD08D0081955B /* GPBExtensionInternals.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBExtensionInternals.m; sourceTree = "<group>"; };
F45E57C81AE6DC98000B7D99 /* text_format_map_unittest_data.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = text_format_map_unittest_data.txt; sourceTree = "<group>"; };
+ F47CF96F23D904E500C7B24C /* GPBWrappers.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBWrappers.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97023D904E500C7B24C /* GPBFieldMask.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBFieldMask.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97123D904E500C7B24C /* GPBApi.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBApi.pbobjc.m; sourceTree = "<group>"; };
+ F47CF97223D904E500C7B24C /* GPBEmpty.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBEmpty.pbobjc.m; sourceTree = "<group>"; };
+ F47CF97323D904E500C7B24C /* GPBSourceContext.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBSourceContext.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97423D904E500C7B24C /* GPBDuration.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBDuration.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97523D904E500C7B24C /* GPBStruct.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBStruct.pbobjc.m; sourceTree = "<group>"; };
+ F47CF97623D904E500C7B24C /* GPBFieldMask.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBFieldMask.pbobjc.m; sourceTree = "<group>"; };
+ F47CF97723D904E500C7B24C /* GPBDuration.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDuration.pbobjc.m; sourceTree = "<group>"; };
+ F47CF97823D904E600C7B24C /* GPBTimestamp.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBTimestamp.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97923D904E600C7B24C /* GPBType.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBType.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97A23D904E600C7B24C /* GPBType.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBType.pbobjc.m; sourceTree = "<group>"; };
+ F47CF97B23D904E600C7B24C /* GPBTimestamp.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBTimestamp.pbobjc.m; sourceTree = "<group>"; };
+ F47CF97C23D904E600C7B24C /* GPBApi.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBApi.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97D23D904E600C7B24C /* GPBAny.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBAny.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97E23D904E600C7B24C /* GPBEmpty.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBEmpty.pbobjc.h; sourceTree = "<group>"; };
+ F47CF97F23D904E600C7B24C /* GPBWrappers.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBWrappers.pbobjc.m; sourceTree = "<group>"; };
+ F47CF98023D904E600C7B24C /* GPBAny.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBAny.pbobjc.m; sourceTree = "<group>"; };
+ F47CF98123D904E600C7B24C /* GPBStruct.pbobjc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GPBStruct.pbobjc.h; sourceTree = "<group>"; };
+ F47CF98223D904E600C7B24C /* GPBSourceContext.pbobjc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBSourceContext.pbobjc.m; sourceTree = "<group>"; };
F4AC9E1C1A8BEB1000BD6E83 /* unittest_cycle.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_cycle.proto; sourceTree = "<group>"; };
F4B51B1B1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = GPBObjectiveCPlusPlusTest.mm; sourceTree = "<group>"; };
F4B6B8B01A9CC99500892426 /* GPBUnknownField_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBUnknownField_PackagePrivate.h; sourceTree = "<group>"; };
@@ -245,23 +264,6 @@
F4B6B8B51A9CD1C600892426 /* GPBRootObject_PackagePrivate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GPBRootObject_PackagePrivate.h; sourceTree = "<group>"; };
F4C4B9E51E1D97BB00D3B61D /* GPBDictionaryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBDictionaryTests.m; sourceTree = "<group>"; };
F4CF31711B162EF500BD9B06 /* unittest_objc_startup.proto */ = {isa = PBXFileReference; lastKnownFileType = text; path = unittest_objc_startup.proto; sourceTree = "<group>"; };
- F4E675B61B21D1440054530B /* Any.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Any.pbobjc.h; path = google/protobuf/Any.pbobjc.h; sourceTree = "<group>"; };
- F4E675B71B21D1440054530B /* Any.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Any.pbobjc.m; path = google/protobuf/Any.pbobjc.m; sourceTree = "<group>"; };
- F4E675B81B21D1440054530B /* Api.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Api.pbobjc.h; path = google/protobuf/Api.pbobjc.h; sourceTree = "<group>"; };
- F4E675B91B21D1440054530B /* Api.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Api.pbobjc.m; path = google/protobuf/Api.pbobjc.m; sourceTree = "<group>"; };
- F4E675BB1B21D1440054530B /* Empty.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Empty.pbobjc.h; path = google/protobuf/Empty.pbobjc.h; sourceTree = "<group>"; };
- F4E675BC1B21D1440054530B /* Empty.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Empty.pbobjc.m; path = google/protobuf/Empty.pbobjc.m; sourceTree = "<group>"; };
- F4E675BD1B21D1440054530B /* FieldMask.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = FieldMask.pbobjc.h; path = google/protobuf/FieldMask.pbobjc.h; sourceTree = "<group>"; };
- F4E675BE1B21D1440054530B /* FieldMask.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = FieldMask.pbobjc.m; path = google/protobuf/FieldMask.pbobjc.m; sourceTree = "<group>"; };
- F4E675BF1B21D1440054530B /* SourceContext.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SourceContext.pbobjc.h; path = google/protobuf/SourceContext.pbobjc.h; sourceTree = "<group>"; };
- F4E675C01B21D1440054530B /* SourceContext.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = SourceContext.pbobjc.m; path = google/protobuf/SourceContext.pbobjc.m; sourceTree = "<group>"; };
- F4E675C11B21D1440054530B /* Struct.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Struct.pbobjc.h; path = google/protobuf/Struct.pbobjc.h; sourceTree = "<group>"; };
- F4E675C21B21D1440054530B /* Struct.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Struct.pbobjc.m; path = google/protobuf/Struct.pbobjc.m; sourceTree = "<group>"; };
- F4E675C31B21D1440054530B /* Timestamp.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Timestamp.pbobjc.h; path = google/protobuf/Timestamp.pbobjc.h; sourceTree = "<group>"; };
- F4E675C41B21D1440054530B /* Type.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Type.pbobjc.h; path = google/protobuf/Type.pbobjc.h; sourceTree = "<group>"; };
- F4E675C51B21D1440054530B /* Type.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Type.pbobjc.m; path = google/protobuf/Type.pbobjc.m; sourceTree = "<group>"; };
- F4E675C61B21D1440054530B /* Wrappers.pbobjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = Wrappers.pbobjc.h; path = google/protobuf/Wrappers.pbobjc.h; sourceTree = "<group>"; };
- F4E675C71B21D1440054530B /* Wrappers.pbobjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = Wrappers.pbobjc.m; path = google/protobuf/Wrappers.pbobjc.m; sourceTree = "<group>"; };
F4E675D81B21D1DE0054530B /* any.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = any.proto; path = ../src/google/protobuf/any.proto; sourceTree = "<group>"; };
F4E675D91B21D1DE0054530B /* api.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = api.proto; path = ../src/google/protobuf/api.proto; sourceTree = "<group>"; };
F4E675DA1B21D1DE0054530B /* empty.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = empty.proto; path = ../src/google/protobuf/empty.proto; sourceTree = "<group>"; };
@@ -344,35 +346,35 @@
29B97315FDCFA39411CA2CEA /* Generated */ = {
isa = PBXGroup;
children = (
- F4E675B61B21D1440054530B /* Any.pbobjc.h */,
- F4E675B71B21D1440054530B /* Any.pbobjc.m */,
+ F47CF97D23D904E600C7B24C /* GPBAny.pbobjc.h */,
+ F47CF98023D904E600C7B24C /* GPBAny.pbobjc.m */,
+ F47CF97C23D904E600C7B24C /* GPBApi.pbobjc.h */,
+ F47CF97123D904E500C7B24C /* GPBApi.pbobjc.m */,
+ F47CF97423D904E500C7B24C /* GPBDuration.pbobjc.h */,
+ F47CF97723D904E500C7B24C /* GPBDuration.pbobjc.m */,
+ F47CF97E23D904E600C7B24C /* GPBEmpty.pbobjc.h */,
+ F47CF97223D904E500C7B24C /* GPBEmpty.pbobjc.m */,
+ F47CF97023D904E500C7B24C /* GPBFieldMask.pbobjc.h */,
+ F47CF97623D904E500C7B24C /* GPBFieldMask.pbobjc.m */,
+ F47CF97323D904E500C7B24C /* GPBSourceContext.pbobjc.h */,
+ F47CF98223D904E600C7B24C /* GPBSourceContext.pbobjc.m */,
+ F47CF98123D904E600C7B24C /* GPBStruct.pbobjc.h */,
+ F47CF97523D904E500C7B24C /* GPBStruct.pbobjc.m */,
+ F47CF97823D904E600C7B24C /* GPBTimestamp.pbobjc.h */,
+ F47CF97B23D904E600C7B24C /* GPBTimestamp.pbobjc.m */,
+ F47CF97923D904E600C7B24C /* GPBType.pbobjc.h */,
+ F47CF97A23D904E600C7B24C /* GPBType.pbobjc.m */,
+ F47CF96F23D904E500C7B24C /* GPBWrappers.pbobjc.h */,
+ F47CF97F23D904E600C7B24C /* GPBWrappers.pbobjc.m */,
F4E675D81B21D1DE0054530B /* any.proto */,
- F4E675B81B21D1440054530B /* Api.pbobjc.h */,
- F4E675B91B21D1440054530B /* Api.pbobjc.m */,
F4E675D91B21D1DE0054530B /* api.proto */,
- 8B4248DD1A929C7D00BC1EC6 /* Duration.pbobjc.h */,
- 8B4248DE1A929C7D00BC1EC6 /* Duration.pbobjc.m */,
8B42494A1A92A0BA00BC1EC6 /* duration.proto */,
- F4E675BB1B21D1440054530B /* Empty.pbobjc.h */,
- F4E675BC1B21D1440054530B /* Empty.pbobjc.m */,
F4E675DA1B21D1DE0054530B /* empty.proto */,
F4E675DB1B21D1DE0054530B /* field_mask.proto */,
- F4E675BD1B21D1440054530B /* FieldMask.pbobjc.h */,
- F4E675BE1B21D1440054530B /* FieldMask.pbobjc.m */,
F4E675DC1B21D1DE0054530B /* source_context.proto */,
- F4E675BF1B21D1440054530B /* SourceContext.pbobjc.h */,
- F4E675C01B21D1440054530B /* SourceContext.pbobjc.m */,
- F4E675C11B21D1440054530B /* Struct.pbobjc.h */,
- F4E675C21B21D1440054530B /* Struct.pbobjc.m */,
F4E675DD1B21D1DE0054530B /* struct.proto */,
- F4E675C31B21D1440054530B /* Timestamp.pbobjc.h */,
- 8B4248E01A929C7D00BC1EC6 /* Timestamp.pbobjc.m */,
8B4249481A92A02300BC1EC6 /* timestamp.proto */,
- F4E675C41B21D1440054530B /* Type.pbobjc.h */,
- F4E675C51B21D1440054530B /* Type.pbobjc.m */,
F4E675DE1B21D1DE0054530B /* type.proto */,
- F4E675C61B21D1440054530B /* Wrappers.pbobjc.h */,
- F4E675C71B21D1440054530B /* Wrappers.pbobjc.m */,
F4E675DF1B21D1DE0054530B /* wrappers.proto */,
);
name = Generated;
@@ -491,6 +493,7 @@
7461B6A30F94FDF800A0C422 /* GPBMessageTests.m */,
F4487C841AAF6AC500531423 /* GPBMessageTests+Merge.m */,
F4487C761AADF84900531423 /* GPBMessageTests+Runtime.m */,
+ 8BFF9D1D23AD599400E63E32 /* GPBMessageTests+ClassNames.m */,
F4487C801AAF62FC00531423 /* GPBMessageTests+Serialization.m */,
F4B51B1B1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm */,
F41C175C1833D3310064ED4D /* GPBPerfTests.m */,
@@ -663,6 +666,7 @@
developmentRegion = English;
hasScannedForEncodings = 1;
knownRegions = (
+ English,
en,
);
mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */;
@@ -716,29 +720,29 @@
buildActionMask = 2147483647;
files = (
7461B53C0F94FB4E00A0C422 /* GPBCodedInputStream.m in Sources */,
- F4E675D21B21D1620054530B /* Empty.pbobjc.m in Sources */,
F4487C731A9F906200531423 /* GPBArray.m in Sources */,
+ F47CF98923D904E600C7B24C /* GPBStruct.pbobjc.m in Sources */,
+ F47CF98623D904E600C7B24C /* GPBEmpty.pbobjc.m in Sources */,
7461B53D0F94FB4E00A0C422 /* GPBCodedOutputStream.m in Sources */,
+ F47CF98523D904E600C7B24C /* GPBApi.pbobjc.m in Sources */,
7461B5490F94FB4E00A0C422 /* GPBExtensionRegistry.m in Sources */,
- F4E675D31B21D1620054530B /* FieldMask.pbobjc.m in Sources */,
7461B54C0F94FB4E00A0C422 /* GPBUnknownField.m in Sources */,
+ F47CF98E23D904E600C7B24C /* GPBType.pbobjc.m in Sources */,
+ F47CF99623D904E600C7B24C /* GPBSourceContext.pbobjc.m in Sources */,
7461B5530F94FB4E00A0C422 /* GPBMessage.m in Sources */,
- F47476E91D21A537007C7B1A /* Duration.pbobjc.m in Sources */,
+ F47CF99323D904E600C7B24C /* GPBWrappers.pbobjc.m in Sources */,
+ F47CF98F23D904E600C7B24C /* GPBTimestamp.pbobjc.m in Sources */,
7461B5610F94FB4E00A0C422 /* GPBUnknownFieldSet.m in Sources */,
7461B5630F94FB4E00A0C422 /* GPBUtilities.m in Sources */,
7461B5640F94FB4E00A0C422 /* GPBWireFormat.m in Sources */,
- F4E675D11B21D1620054530B /* Api.pbobjc.m in Sources */,
- F4E675D41B21D1620054530B /* SourceContext.pbobjc.m in Sources */,
F4353D271ABB156F005A6198 /* GPBDictionary.m in Sources */,
+ F47CF98B23D904E600C7B24C /* GPBDuration.pbobjc.m in Sources */,
8B79657B14992E3F002FFBFC /* GPBRootObject.m in Sources */,
8B96157414C8C38C00A2AC0B /* GPBDescriptor.m in Sources */,
- F4E675D01B21D1620054530B /* Any.pbobjc.m in Sources */,
+ F47CF98A23D904E600C7B24C /* GPBFieldMask.pbobjc.m in Sources */,
+ F47CF99423D904E600C7B24C /* GPBAny.pbobjc.m in Sources */,
F45C69CC16DFD08D0081955B /* GPBExtensionInternals.m in Sources */,
8B4248E41A929C8900BC1EC6 /* GPBWellKnownTypes.m in Sources */,
- F4E675D61B21D1620054530B /* Type.pbobjc.m in Sources */,
- F4E675D51B21D1620054530B /* Struct.pbobjc.m in Sources */,
- F4E675D71B21D1620054530B /* Wrappers.pbobjc.m in Sources */,
- F47476EA1D21A537007C7B1A /* Timestamp.pbobjc.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -777,6 +781,7 @@
8B4248B41A8BD96E00BC1EC6 /* GPBSwiftTests.swift in Sources */,
F40EE512206C068D0071091A /* GPBCompileTest25.m in Sources */,
F4584D831ECCB53600803AB6 /* GPBExtensionRegistryTest.m in Sources */,
+ 8BFF9D1E23AD599400E63E32 /* GPBMessageTests+ClassNames.m in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
F4487C771AADF84900531423 /* GPBMessageTests+Runtime.m in Sources */,
F40EE4F1206BF91E0071091A /* GPBCompileTest02.m in Sources */,
diff --git a/objectivec/README.md b/objectivec/README.md
index 528f547..69fe631 100644
--- a/objectivec/README.md
+++ b/objectivec/README.md
@@ -13,7 +13,7 @@
The Objective C implementation requires:
- Objective C 2.0 Runtime (32bit & 64bit iOS, 64bit OS X).
-- Xcode 8.0 (or later).
+- Xcode 10.3 (or later).
- The library code does *not* use ARC (for performance reasons), but it all can
be called from ARC code.
diff --git a/objectivec/Tests/GPBArrayTests.m b/objectivec/Tests/GPBArrayTests.m
index e414d90..9b004bc 100644
--- a/objectivec/Tests/GPBArrayTests.m
+++ b/objectivec/Tests/GPBArrayTests.m
@@ -433,6 +433,7 @@
//%
//%PDDM-EXPAND ARRAY_TESTS(Int32, int32_t, 1, 2, 3, 4)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int32
@@ -775,8 +776,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_TESTS(UInt32, uint32_t, 11U, 12U, 13U, 14U)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - UInt32
@@ -1119,8 +1122,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_TESTS(Int64, int64_t, 31LL, 32LL, 33LL, 34LL)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Int64
@@ -1463,8 +1468,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_TESTS(UInt64, uint64_t, 41ULL, 42ULL, 43ULL, 44ULL)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - UInt64
@@ -1807,8 +1814,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_TESTS(Float, float, 51.f, 52.f, 53.f, 54.f)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Float
@@ -2151,8 +2160,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_TESTS(Double, double, 61., 62., 63., 64.)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Double
@@ -2495,8 +2506,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_TESTS(Bool, BOOL, TRUE, TRUE, FALSE, FALSE)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool
@@ -2839,8 +2852,10 @@
@end
+// clang-format on
//%PDDM-EXPAND ARRAY_TESTS2(Enum, int32_t, 71, 72, 73, 74, Raw)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Enum
@@ -3183,6 +3198,7 @@
@end
+// clang-format on
//%PDDM-EXPAND-END (8 expansions)
#pragma mark - Non macro-based Enum tests
diff --git a/objectivec/Tests/GPBCompileTest14.m b/objectivec/Tests/GPBCompileTest14.m
index ae04349..1e64b71 100644
--- a/objectivec/Tests/GPBCompileTest14.m
+++ b/objectivec/Tests/GPBCompileTest14.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Any.pbobjc.h"
+#import "GPBAny.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest15.m b/objectivec/Tests/GPBCompileTest15.m
index 889243a..2eaedb2 100644
--- a/objectivec/Tests/GPBCompileTest15.m
+++ b/objectivec/Tests/GPBCompileTest15.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Api.pbobjc.h"
+#import "GPBApi.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest16.m b/objectivec/Tests/GPBCompileTest16.m
index c5aaf14..25af89e 100644
--- a/objectivec/Tests/GPBCompileTest16.m
+++ b/objectivec/Tests/GPBCompileTest16.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Duration.pbobjc.h"
+#import "GPBDuration.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest17.m b/objectivec/Tests/GPBCompileTest17.m
index feb64d6..c719ad3 100644
--- a/objectivec/Tests/GPBCompileTest17.m
+++ b/objectivec/Tests/GPBCompileTest17.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Empty.pbobjc.h"
+#import "GPBEmpty.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest18.m b/objectivec/Tests/GPBCompileTest18.m
index 66784c4..a02b259 100644
--- a/objectivec/Tests/GPBCompileTest18.m
+++ b/objectivec/Tests/GPBCompileTest18.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/FieldMask.pbobjc.h"
+#import "GPBFieldMask.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest19.m b/objectivec/Tests/GPBCompileTest19.m
index 435dea0..b447284 100644
--- a/objectivec/Tests/GPBCompileTest19.m
+++ b/objectivec/Tests/GPBCompileTest19.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/SourceContext.pbobjc.h"
+#import "GPBSourceContext.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest20.m b/objectivec/Tests/GPBCompileTest20.m
index c2da806..120ef55 100644
--- a/objectivec/Tests/GPBCompileTest20.m
+++ b/objectivec/Tests/GPBCompileTest20.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Struct.pbobjc.h"
+#import "GPBStruct.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest21.m b/objectivec/Tests/GPBCompileTest21.m
index d7110b9..766d890 100644
--- a/objectivec/Tests/GPBCompileTest21.m
+++ b/objectivec/Tests/GPBCompileTest21.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Timestamp.pbobjc.h"
+#import "GPBTimestamp.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest22.m b/objectivec/Tests/GPBCompileTest22.m
index 1738061..6d0955b 100644
--- a/objectivec/Tests/GPBCompileTest22.m
+++ b/objectivec/Tests/GPBCompileTest22.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Type.pbobjc.h"
+#import "GPBType.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBCompileTest23.m b/objectivec/Tests/GPBCompileTest23.m
index f22f9bd..22f2db6 100644
--- a/objectivec/Tests/GPBCompileTest23.m
+++ b/objectivec/Tests/GPBCompileTest23.m
@@ -32,7 +32,7 @@
// This is a test including a single public header to ensure things build.
// It helps test that imports are complete/ordered correctly.
-#import "google/protobuf/Wrappers.pbobjc.h"
+#import "GPBWrappers.pbobjc.h"
// Something in the body of this file so the compiler/linker won't complain
diff --git a/objectivec/Tests/GPBDescriptorTests.m b/objectivec/Tests/GPBDescriptorTests.m
index 46c1729..6fa7202 100644
--- a/objectivec/Tests/GPBDescriptorTests.m
+++ b/objectivec/Tests/GPBDescriptorTests.m
@@ -355,7 +355,7 @@
XCTAssertNil([oneofBar fieldWithNumber:TestOneof2_FieldNumber_FooString]);
// Check pointers back to the enclosing oneofs.
- // (pointer comparisions)
+ // (pointer comparisons)
XCTAssertEqual(fooStringField.containingOneof, oneofFoo);
XCTAssertEqual(barStringField.containingOneof, oneofBar);
GPBFieldDescriptor *bazString =
diff --git a/objectivec/Tests/GPBDictionaryTests+Bool.m b/objectivec/Tests/GPBDictionaryTests+Bool.m
index 0af0c81..4c02144 100644
--- a/objectivec/Tests/GPBDictionaryTests+Bool.m
+++ b/objectivec/Tests/GPBDictionaryTests+Bool.m
@@ -42,6 +42,7 @@
//%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(UInt32, uint32_t, 100U, 101U)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> UInt32
@@ -345,8 +346,10 @@
@end
+// clang-format on
//%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Int32, int32_t, 200, 201)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Int32
@@ -650,8 +653,10 @@
@end
+// clang-format on
//%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(UInt64, uint64_t, 300U, 301U)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> UInt64
@@ -955,8 +960,10 @@
@end
+// clang-format on
//%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Int64, int64_t, 400, 401)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Int64
@@ -1260,8 +1267,10 @@
@end
+// clang-format on
//%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Bool, BOOL, NO, YES)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Bool
@@ -1565,8 +1574,10 @@
@end
+// clang-format on
//%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Float, float, 500.f, 501.f)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Float
@@ -1870,8 +1881,10 @@
@end
+// clang-format on
//%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Double, double, 600., 601.)
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Double
@@ -2175,8 +2188,10 @@
@end
+// clang-format on
//%PDDM-EXPAND TESTS_FOR_BOOL_KEY_OBJECT_VALUE(Object, NSString*, @"abc", @"def")
// This block of code is generated, do not edit it directly.
+// clang-format off
#pragma mark - Bool -> Object
@@ -2445,6 +2460,7 @@
@end
+// clang-format on
//%PDDM-EXPAND-END (8 expansions)
diff --git a/objectivec/Tests/GPBDictionaryTests+Int32.m b/objectivec/Tests/GPBDictionaryTests+Int32.m
index 4ba3020..8dafaac 100644
--- a/objectivec/Tests/GPBDictionaryTests+Int32.m
+++ b/objectivec/Tests/GPBDictionaryTests+Int32.m
@@ -42,6 +42,7 @@
//%PDDM-EXPAND TEST_FOR_POD_KEY(Int32, int32_t, 11, 12, 13, 14)
// This block of code is generated, do not edit it directly.
+// clang-format off
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBInt32EnumDictionary (TestingTweak)
@@ -3672,5 +3673,6 @@
@end
+// clang-format on
//%PDDM-EXPAND-END TEST_FOR_POD_KEY(Int32, int32_t, 11, 12, 13, 14)
diff --git a/objectivec/Tests/GPBDictionaryTests+Int64.m b/objectivec/Tests/GPBDictionaryTests+Int64.m
index 966024b..a603356 100644
--- a/objectivec/Tests/GPBDictionaryTests+Int64.m
+++ b/objectivec/Tests/GPBDictionaryTests+Int64.m
@@ -42,6 +42,7 @@
//%PDDM-EXPAND TEST_FOR_POD_KEY(Int64, int64_t, 21LL, 22LL, 23LL, 24LL)
// This block of code is generated, do not edit it directly.
+// clang-format off
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBInt64EnumDictionary (TestingTweak)
@@ -3672,5 +3673,6 @@
@end
+// clang-format on
//%PDDM-EXPAND-END TEST_FOR_POD_KEY(Int64, int64_t, 21LL, 22LL, 23LL, 24LL)
diff --git a/objectivec/Tests/GPBDictionaryTests+String.m b/objectivec/Tests/GPBDictionaryTests+String.m
index 82d7952..8ad1cea 100644
--- a/objectivec/Tests/GPBDictionaryTests+String.m
+++ b/objectivec/Tests/GPBDictionaryTests+String.m
@@ -42,6 +42,7 @@
//%PDDM-EXPAND TESTS_FOR_POD_VALUES(String, NSString, *, Objects, @"foo", @"bar", @"baz", @"mumble")
// This block of code is generated, do not edit it directly.
+// clang-format off
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBStringEnumDictionary (TestingTweak)
@@ -3380,5 +3381,6 @@
@end
+// clang-format on
//%PDDM-EXPAND-END TESTS_FOR_POD_VALUES(String, NSString, *, Objects, @"foo", @"bar", @"baz", @"mumble")
diff --git a/objectivec/Tests/GPBDictionaryTests+UInt32.m b/objectivec/Tests/GPBDictionaryTests+UInt32.m
index 5314c58..f607538 100644
--- a/objectivec/Tests/GPBDictionaryTests+UInt32.m
+++ b/objectivec/Tests/GPBDictionaryTests+UInt32.m
@@ -42,6 +42,7 @@
//%PDDM-EXPAND TEST_FOR_POD_KEY(UInt32, uint32_t, 1U, 2U, 3U, 4U)
// This block of code is generated, do not edit it directly.
+// clang-format off
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBUInt32EnumDictionary (TestingTweak)
@@ -3672,5 +3673,6 @@
@end
+// clang-format on
//%PDDM-EXPAND-END TEST_FOR_POD_KEY(UInt32, uint32_t, 1U, 2U, 3U, 4U)
diff --git a/objectivec/Tests/GPBDictionaryTests+UInt64.m b/objectivec/Tests/GPBDictionaryTests+UInt64.m
index ccd063f..b5dd91e 100644
--- a/objectivec/Tests/GPBDictionaryTests+UInt64.m
+++ b/objectivec/Tests/GPBDictionaryTests+UInt64.m
@@ -42,6 +42,7 @@
//%PDDM-EXPAND TEST_FOR_POD_KEY(UInt64, uint64_t, 31ULL, 32ULL, 33ULL, 34ULL)
// This block of code is generated, do not edit it directly.
+// clang-format off
// To let the testing macros work, add some extra methods to simplify things.
@interface GPBUInt64EnumDictionary (TestingTweak)
@@ -3672,4 +3673,5 @@
@end
+// clang-format on
//%PDDM-EXPAND-END TEST_FOR_POD_KEY(UInt64, uint64_t, 31ULL, 32ULL, 33ULL, 34ULL)
diff --git a/objectivec/Tests/GPBMessageTests+ClassNames.m b/objectivec/Tests/GPBMessageTests+ClassNames.m
new file mode 100644
index 0000000..b5a5c51
--- /dev/null
+++ b/objectivec/Tests/GPBMessageTests+ClassNames.m
@@ -0,0 +1,164 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2015 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#import "GPBTestUtilities.h"
+
+#import <objc/runtime.h>
+
+#import "GPBDescriptor_PackagePrivate.h"
+#import "GPBExtensionRegistry.h"
+#import "GPBMessage.h"
+#import "GPBRootObject_PackagePrivate.h"
+
+// Support classes for tests using old class name (vs classrefs) interfaces.
+GPB_FINAL @interface MessageLackingClazzRoot : GPBRootObject
+@end
+
+@interface MessageLackingClazzRoot (DynamicMethods)
++ (GPBExtensionDescriptor *)ext1;
+@end
+
+GPB_FINAL @interface MessageLackingClazz : GPBMessage
+@property(copy, nonatomic) NSString *foo;
+@end
+
+@implementation MessageLackingClazz
+
+@dynamic foo;
+
+typedef struct MessageLackingClazz_storage_ {
+ uint32_t _has_storage_[1];
+ NSString *foo;
+} MessageLackingClazz_storage_;
+
++ (GPBDescriptor *)descriptor {
+ static GPBDescriptor *descriptor = nil;
+ if (!descriptor) {
+ static GPBMessageFieldDescription fields[] = {
+ {
+ .name = "foo",
+ .dataTypeSpecific.className = "NSString",
+ .number = 1,
+ .hasIndex = 0,
+ .offset = (uint32_t)offsetof(MessageLackingClazz_storage_, foo),
+ .flags = (GPBFieldFlags)(GPBFieldOptional),
+ .dataType = GPBDataTypeMessage,
+ },
+ };
+ GPBFileDescriptor *desc =
+ [[[GPBFileDescriptor alloc] initWithPackage:@"test"
+ objcPrefix:@"TEST"
+ syntax:GPBFileSyntaxProto3] autorelease];
+
+ // GPBDescriptorInitializationFlag_UsesClassRefs intentionally not set here
+ descriptor =
+ [GPBDescriptor allocDescriptorForClass:[MessageLackingClazz class]
+ rootClass:[MessageLackingClazzRoot class]
+ file:desc
+ fields:fields
+ fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
+ storageSize:sizeof(MessageLackingClazz_storage_)
+ flags:GPBDescriptorInitializationFlag_None];
+ [descriptor setupContainingMessageClassName:"MessageLackingClazz"];
+ }
+ return descriptor;
+}
+@end
+
+@implementation MessageLackingClazzRoot
+
++ (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) {
+ registry = [[GPBExtensionRegistry alloc] init];
+ static GPBExtensionDescription descriptions[] = {
+ {
+ .defaultValue.valueMessage = NULL,
+ .singletonName = "MessageLackingClazzRoot_ext1",
+ .extendedClass.name = "MessageLackingClazz",
+ .messageOrGroupClass.name = "MessageLackingClazz",
+ .enumDescriptorFunc = NULL,
+ .fieldNumber = 1,
+ .dataType = GPBDataTypeMessage,
+ // GPBExtensionUsesClazz Intentionally not set
+ .options = 0,
+ },
+ };
+ for (size_t i = 0; i < sizeof(descriptions) / sizeof(descriptions[0]); ++i) {
+ // Intentionall using `-initWithExtensionDescription:` and not `
+ // -initWithExtensionDescription:usesClassRefs:` to test backwards
+ // compatibility
+ GPBExtensionDescriptor *extension =
+ [[GPBExtensionDescriptor alloc] initWithExtensionDescription:&descriptions[i]];
+ [registry addExtension:extension];
+ [self globallyRegisterExtension:extension];
+ [extension release];
+ }
+ // None of the imports (direct or indirect) defined extensions, so no need to add
+ // them to this registry.
+ }
+ return registry;
+}
+@end
+
+@interface MessageClassNameTests : GPBTestCase
+@end
+
+@implementation MessageClassNameTests
+
+- (void)testClassNameSupported {
+ // This tests backwards compatibility to make sure we support older sources
+ // that use class names instead of references.
+ GPBDescriptor *desc = [MessageLackingClazz descriptor];
+ GPBFieldDescriptor *fieldDesc = [desc fieldWithName:@"foo"];
+ XCTAssertEqualObjects(fieldDesc.msgClass, [NSString class]);
+}
+
+- (void)testSetupContainingMessageClassNameSupported {
+ // This tests backwards compatibility to make sure we support older sources
+ // that use class names instead of references.
+ GPBDescriptor *desc = [MessageLackingClazz descriptor];
+ GPBDescriptor *container = [desc containingType];
+ XCTAssertEqualObjects(container.messageClass, [MessageLackingClazz class]);
+}
+
+- (void)testExtensionsNameSupported {
+ // This tests backwards compatibility to make sure we support older sources
+ // that use class names instead of references.
+ GPBExtensionDescriptor *desc = [MessageLackingClazzRoot ext1];
+ Class containerClass = [desc containingMessageClass];
+ XCTAssertEqualObjects(containerClass, [MessageLackingClazz class]);
+ Class msgClass = [desc msgClass];
+ XCTAssertEqualObjects(msgClass, [MessageLackingClazz class]);
+}
+
+@end
diff --git a/objectivec/Tests/GPBMessageTests+Merge.m b/objectivec/Tests/GPBMessageTests+Merge.m
index c0bd589..f895542 100644
--- a/objectivec/Tests/GPBMessageTests+Merge.m
+++ b/objectivec/Tests/GPBMessageTests+Merge.m
@@ -267,6 +267,7 @@
//%
//%PDDM-EXPAND MERGE2_TEST(Int32, 10, Enum, Message2_Enum_Baz)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofInt32 = 10;
[dst mergeFrom:src];
@@ -274,8 +275,10 @@
XCTAssertEqual(dst.oneofInt32, 10);
XCTAssertEqual(dst.oneofEnum, Message2_Enum_Baz);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Int64, 11, Int32, 100)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofInt64 = 11;
[dst mergeFrom:src];
@@ -283,8 +286,10 @@
XCTAssertEqual(dst.oneofInt64, 11);
XCTAssertEqual(dst.oneofInt32, 100);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Uint32, 12U, Int64, 101)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofUint32 = 12U;
[dst mergeFrom:src];
@@ -292,8 +297,10 @@
XCTAssertEqual(dst.oneofUint32, 12U);
XCTAssertEqual(dst.oneofInt64, 101);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Uint64, 13U, Uint32, 102U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofUint64 = 13U;
[dst mergeFrom:src];
@@ -301,8 +308,10 @@
XCTAssertEqual(dst.oneofUint64, 13U);
XCTAssertEqual(dst.oneofUint32, 102U);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Sint32, 14, Uint64, 103U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSint32 = 14;
[dst mergeFrom:src];
@@ -310,8 +319,10 @@
XCTAssertEqual(dst.oneofSint32, 14);
XCTAssertEqual(dst.oneofUint64, 103U);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Sint64, 15, Sint32, 104)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSint64 = 15;
[dst mergeFrom:src];
@@ -319,8 +330,10 @@
XCTAssertEqual(dst.oneofSint64, 15);
XCTAssertEqual(dst.oneofSint32, 104);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Fixed32, 16U, Sint64, 105)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofFixed32 = 16U;
[dst mergeFrom:src];
@@ -328,8 +341,10 @@
XCTAssertEqual(dst.oneofFixed32, 16U);
XCTAssertEqual(dst.oneofSint64, 105);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Fixed64, 17U, Fixed32, 106U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofFixed64 = 17U;
[dst mergeFrom:src];
@@ -337,8 +352,10 @@
XCTAssertEqual(dst.oneofFixed64, 17U);
XCTAssertEqual(dst.oneofFixed32, 106U);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Sfixed32, 18, Fixed64, 107U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSfixed32 = 18;
[dst mergeFrom:src];
@@ -346,8 +363,10 @@
XCTAssertEqual(dst.oneofSfixed32, 18);
XCTAssertEqual(dst.oneofFixed64, 107U);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Sfixed64, 19, Sfixed32, 108)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSfixed64 = 19;
[dst mergeFrom:src];
@@ -355,8 +374,10 @@
XCTAssertEqual(dst.oneofSfixed64, 19);
XCTAssertEqual(dst.oneofSfixed32, 108);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Float, 20.0f, Sfixed64, 109)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofFloat = 20.0f;
[dst mergeFrom:src];
@@ -364,8 +385,10 @@
XCTAssertEqual(dst.oneofFloat, 20.0f);
XCTAssertEqual(dst.oneofSfixed64, 109);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Double, 21.0, Float, 110.0f)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofDouble = 21.0;
[dst mergeFrom:src];
@@ -373,8 +396,10 @@
XCTAssertEqual(dst.oneofDouble, 21.0);
XCTAssertEqual(dst.oneofFloat, 110.0f);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Bool, NO, Double, 111.0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofBool = NO;
[dst mergeFrom:src];
@@ -382,8 +407,10 @@
XCTAssertEqual(dst.oneofBool, NO);
XCTAssertEqual(dst.oneofDouble, 111.0);
+// clang-format on
//%PDDM-EXPAND MERGE2_TEST(Enum, Message2_Enum_Bar, Bool, YES)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofEnum = Message2_Enum_Bar;
[dst mergeFrom:src];
@@ -391,6 +418,7 @@
XCTAssertEqual(dst.oneofEnum, Message2_Enum_Bar);
XCTAssertEqual(dst.oneofBool, YES);
+// clang-format on
//%PDDM-EXPAND-END (14 expansions)
NSString *oneofStringDefault = @"string";
@@ -416,7 +444,7 @@
XCTAssertEqual(dst.oOneOfCase, Message2_O_OneOfCase_OneofGroup);
Message2_OneofGroup *mergedGroup = [[dst.oneofGroup retain] autorelease];
XCTAssertNotNil(mergedGroup);
- XCTAssertNotEqual(mergedGroup, group); // Pointer comparision.
+ XCTAssertNotEqual(mergedGroup, group); // Pointer comparison.
XCTAssertEqualObjects(mergedGroup, group);
XCTAssertEqualObjects(dst.oneofBytes, oneofBytesDefault);
@@ -427,10 +455,10 @@
XCTAssertEqual(dst.oOneOfCase, Message2_O_OneOfCase_OneofMessage);
Message2 *mergedSubMessage = [[dst.oneofMessage retain] autorelease];
XCTAssertNotNil(mergedSubMessage);
- XCTAssertNotEqual(mergedSubMessage, subMessage); // Pointer comparision.
+ XCTAssertNotEqual(mergedSubMessage, subMessage); // Pointer comparison.
XCTAssertEqualObjects(mergedSubMessage, subMessage);
XCTAssertNotNil(dst.oneofGroup);
- XCTAssertNotEqual(dst.oneofGroup, mergedGroup); // Pointer comparision.
+ XCTAssertNotEqual(dst.oneofGroup, mergedGroup); // Pointer comparison.
// Back to something else to make sure message clears out ok.
@@ -439,7 +467,7 @@
XCTAssertEqual(dst.oOneOfCase, Message2_O_OneOfCase_OneofInt32);
XCTAssertNotNil(dst.oneofMessage);
XCTAssertNotEqual(dst.oneofMessage,
- mergedSubMessage); // Pointer comparision.
+ mergedSubMessage); // Pointer comparison.
//
// Test merging in to message/group when they already had something.
@@ -452,9 +480,9 @@
[dst mergeFrom:src];
XCTAssertEqual(dst.oOneOfCase, Message2_O_OneOfCase_OneofGroup);
// Shouldn't have been a new object.
- XCTAssertEqual(dst.oneofGroup, mergedGroup); // Pointer comparision.
- XCTAssertEqual(dst.oneofGroup.a, 666); // Pointer comparision.
- XCTAssertEqual(dst.oneofGroup.b, 888); // Pointer comparision.
+ XCTAssertEqual(dst.oneofGroup, mergedGroup); // Pointer comparison.
+ XCTAssertEqual(dst.oneofGroup.a, 666); // Pointer comparison.
+ XCTAssertEqual(dst.oneofGroup.b, 888); // Pointer comparison.
src.oneofMessage = subMessage;
mergedSubMessage = [Message2 message];
@@ -463,9 +491,9 @@
[dst mergeFrom:src];
XCTAssertEqual(dst.oOneOfCase, Message2_O_OneOfCase_OneofMessage);
// Shouldn't have been a new object.
- XCTAssertEqual(dst.oneofMessage, mergedSubMessage); // Pointer comparision.
- XCTAssertEqual(dst.oneofMessage.optionalInt32, 777); // Pointer comparision.
- XCTAssertEqual(dst.oneofMessage.optionalInt64, 999); // Pointer comparision.
+ XCTAssertEqual(dst.oneofMessage, mergedSubMessage); // Pointer comparison.
+ XCTAssertEqual(dst.oneofMessage.optionalInt32, 777); // Pointer comparison.
+ XCTAssertEqual(dst.oneofMessage.optionalInt64, 999); // Pointer comparison.
}
- (void)testProto3MergeOneof {
@@ -487,6 +515,7 @@
//%
//%PDDM-EXPAND MERGE3_TEST(Int32, 10, Enum, Message3_Enum_Foo)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofInt32 = 10;
[dst mergeFrom:src];
@@ -494,8 +523,10 @@
XCTAssertEqual(dst.oneofInt32, 10);
XCTAssertEqual(dst.oneofEnum, Message3_Enum_Foo);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Int64, 11, Int32, 0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofInt64 = 11;
[dst mergeFrom:src];
@@ -503,8 +534,10 @@
XCTAssertEqual(dst.oneofInt64, 11);
XCTAssertEqual(dst.oneofInt32, 0);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Uint32, 12U, Int64, 0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofUint32 = 12U;
[dst mergeFrom:src];
@@ -512,8 +545,10 @@
XCTAssertEqual(dst.oneofUint32, 12U);
XCTAssertEqual(dst.oneofInt64, 0);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Uint64, 13U, Uint32, 0U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofUint64 = 13U;
[dst mergeFrom:src];
@@ -521,8 +556,10 @@
XCTAssertEqual(dst.oneofUint64, 13U);
XCTAssertEqual(dst.oneofUint32, 0U);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Sint32, 14, Uint64, 0U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSint32 = 14;
[dst mergeFrom:src];
@@ -530,8 +567,10 @@
XCTAssertEqual(dst.oneofSint32, 14);
XCTAssertEqual(dst.oneofUint64, 0U);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Sint64, 15, Sint32, 0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSint64 = 15;
[dst mergeFrom:src];
@@ -539,8 +578,10 @@
XCTAssertEqual(dst.oneofSint64, 15);
XCTAssertEqual(dst.oneofSint32, 0);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Fixed32, 16U, Sint64, 0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofFixed32 = 16U;
[dst mergeFrom:src];
@@ -548,8 +589,10 @@
XCTAssertEqual(dst.oneofFixed32, 16U);
XCTAssertEqual(dst.oneofSint64, 0);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Fixed64, 17U, Fixed32, 0U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofFixed64 = 17U;
[dst mergeFrom:src];
@@ -557,8 +600,10 @@
XCTAssertEqual(dst.oneofFixed64, 17U);
XCTAssertEqual(dst.oneofFixed32, 0U);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Sfixed32, 18, Fixed64, 0U)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSfixed32 = 18;
[dst mergeFrom:src];
@@ -566,8 +611,10 @@
XCTAssertEqual(dst.oneofSfixed32, 18);
XCTAssertEqual(dst.oneofFixed64, 0U);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Sfixed64, 19, Sfixed32, 0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofSfixed64 = 19;
[dst mergeFrom:src];
@@ -575,8 +622,10 @@
XCTAssertEqual(dst.oneofSfixed64, 19);
XCTAssertEqual(dst.oneofSfixed32, 0);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Float, 20.0f, Sfixed64, 0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofFloat = 20.0f;
[dst mergeFrom:src];
@@ -584,8 +633,10 @@
XCTAssertEqual(dst.oneofFloat, 20.0f);
XCTAssertEqual(dst.oneofSfixed64, 0);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Double, 21.0, Float, 0.0f)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofDouble = 21.0;
[dst mergeFrom:src];
@@ -593,8 +644,10 @@
XCTAssertEqual(dst.oneofDouble, 21.0);
XCTAssertEqual(dst.oneofFloat, 0.0f);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Bool, YES, Double, 0.0)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofBool = YES;
[dst mergeFrom:src];
@@ -602,8 +655,10 @@
XCTAssertEqual(dst.oneofBool, YES);
XCTAssertEqual(dst.oneofDouble, 0.0);
+// clang-format on
//%PDDM-EXPAND MERGE3_TEST(Enum, Message3_Enum_Bar, Bool, NO)
// This block of code is generated, do not edit it directly.
+// clang-format off
src.oneofEnum = Message3_Enum_Bar;
[dst mergeFrom:src];
@@ -611,6 +666,7 @@
XCTAssertEqual(dst.oneofEnum, Message3_Enum_Bar);
XCTAssertEqual(dst.oneofBool, NO);
+// clang-format on
//%PDDM-EXPAND-END (14 expansions)
NSString *oneofStringDefault = @"";
@@ -637,7 +693,7 @@
XCTAssertEqual(dst.oOneOfCase, Message3_O_OneOfCase_OneofMessage);
Message3 *mergedSubMessage = [[dst.oneofMessage retain] autorelease];
XCTAssertNotNil(mergedSubMessage);
- XCTAssertNotEqual(mergedSubMessage, subMessage); // Pointer comparision.
+ XCTAssertNotEqual(mergedSubMessage, subMessage); // Pointer comparison.
XCTAssertEqualObjects(mergedSubMessage, subMessage);
XCTAssertEqualObjects(dst.oneofBytes, oneofBytesDefault);
@@ -648,7 +704,7 @@
XCTAssertEqual(dst.oOneOfCase, Message3_O_OneOfCase_OneofInt32);
XCTAssertNotNil(dst.oneofMessage);
XCTAssertNotEqual(dst.oneofMessage,
- mergedSubMessage); // Pointer comparision.
+ mergedSubMessage); // Pointer comparison.
//
// Test merging in to message when they already had something.
@@ -661,9 +717,9 @@
[dst mergeFrom:src];
XCTAssertEqual(dst.oOneOfCase, Message3_O_OneOfCase_OneofMessage);
// Shouldn't have been a new object.
- XCTAssertEqual(dst.oneofMessage, mergedSubMessage); // Pointer comparision.
- XCTAssertEqual(dst.oneofMessage.optionalInt32, 777); // Pointer comparision.
- XCTAssertEqual(dst.oneofMessage.optionalInt64, 999); // Pointer comparision.
+ XCTAssertEqual(dst.oneofMessage, mergedSubMessage); // Pointer comparison.
+ XCTAssertEqual(dst.oneofMessage.optionalInt32, 777); // Pointer comparison.
+ XCTAssertEqual(dst.oneofMessage.optionalInt64, 999); // Pointer comparison.
}
#pragma mark - Subset from from map_tests.cc
diff --git a/objectivec/Tests/GPBMessageTests+Runtime.m b/objectivec/Tests/GPBMessageTests+Runtime.m
index 9d98f91..1dac797 100644
--- a/objectivec/Tests/GPBMessageTests+Runtime.m
+++ b/objectivec/Tests/GPBMessageTests+Runtime.m
@@ -212,7 +212,7 @@
// Proto3 gets:
// Single fields
- // - has*/setHas* invalid for primative types.
+ // - has*/setHas* invalid for primitive types.
// - has*/setHas* valid for Message.
for (NSString *name in names) {
@@ -252,7 +252,7 @@
// build the selector, i.e. - repeatedInt32Array_Count
SEL countSel = NSSelectorFromString(
[NSString stringWithFormat:@"repeated%@Array_Count", name]);
- XCTAssertTrue([Message2 instancesRespondToSelector:countSel], @"field: %@",
+ XCTAssertTrue([Message3 instancesRespondToSelector:countSel], @"field: %@",
name);
}
@@ -264,12 +264,29 @@
NSSelectorFromString([NSString stringWithFormat:@"hasOneof%@", name]);
SEL setHasSel = NSSelectorFromString(
[NSString stringWithFormat:@"setHasOneof%@:", name]);
- XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@",
+ XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@",
name);
- XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel],
+ XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel],
@"field: %@", name);
}
+ // Single Optional fields
+ // - has*/setHas* thanks to the optional keyword in proto3, they exist
+ // for primitive types.
+ // - has*/setHas* valid for Message.
+
+ for (NSString *name in names) {
+ // build the selector, i.e. - hasOptionalInt32/setHasOptionalInt32:
+ SEL hasSel = NSSelectorFromString(
+ [NSString stringWithFormat:@"hasOptional%@", name]);
+ SEL setHasSel = NSSelectorFromString(
+ [NSString stringWithFormat:@"setHasOptional%@:", name]);
+ XCTAssertTrue([Message3Optional instancesRespondToSelector:hasSel], @"field: %@",
+ name);
+ XCTAssertTrue([Message3Optional instancesRespondToSelector:setHasSel],
+ @"field: %@", name);
+ }
+
// map<> fields
// - no has*/setHas*
// - *Count
@@ -302,14 +319,14 @@
[NSString stringWithFormat:@"hasMap%@", name]);
SEL setHasSel = NSSelectorFromString(
[NSString stringWithFormat:@"setHasMap%@:", name]);
- XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@",
+ XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@",
name);
- XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel],
+ XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel],
@"field: %@", name);
// build the selector, i.e. - mapInt32Int32Count
SEL countSel = NSSelectorFromString(
[NSString stringWithFormat:@"map%@_Count", name]);
- XCTAssertTrue([Message2 instancesRespondToSelector:countSel], @"field: %@",
+ XCTAssertTrue([Message3 instancesRespondToSelector:countSel], @"field: %@",
name);
}
}
@@ -382,6 +399,7 @@
//%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.
+// clang-format off
{ // optionalInt32 :: 1
Message2 *msg = [[Message2 alloc] init];
@@ -735,6 +753,7 @@
[msg release];
}
+// clang-format on
//%PDDM-EXPAND-END PROTO2_TEST_HAS_FIELDS()
}
@@ -796,6 +815,7 @@
//%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.
+// clang-format off
{ // optionalInt32
Message3 *msg = [[Message3 alloc] init];
@@ -995,9 +1015,253 @@
[msg release];
}
+// clang-format on
//%PDDM-EXPAND-END PROTO3_TEST_HAS_FIELDS()
}
+- (void)testProto3SingleOptionalFieldHasBehavior {
+ //
+ // Setting to any value including the default (0) should result in true.
+ //
+
+//%PDDM-DEFINE PROTO3_TEST_OPTIONAL_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE)
+//% { // optional##FIELD
+//% Message3Optional *msg = [[Message3Optional alloc] init];
+//% XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_Optional##FIELD));
+//% msg.optional##FIELD = NON_ZERO_VALUE;
+//% XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_Optional##FIELD));
+//% msg.hasOptional##FIELD = NO;
+//% XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_Optional##FIELD));
+//% msg.optional##FIELD = ZERO_VALUE;
+//% XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_Optional##FIELD));
+//% [msg release];
+//% }
+//%
+//%PDDM-DEFINE PROTO3_TEST_OPTIONAL_HAS_FIELDS()
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Int32, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Int64, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Uint32, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Uint64, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Sint32, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Sint64, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Fixed32, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Fixed64, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Sfixed32, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Sfixed64, 1, 0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Float, 1.0f, 0.0f)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Double, 1.0, 0.0)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Bool, YES, NO)
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(String, @"foo", @"")
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Bytes, [@"foo" dataUsingEncoding:NSUTF8StringEncoding], [NSData data])
+//% //
+//% // Test doesn't apply to optionalMessage (no groups in proto3).
+//% //
+//%
+//%PROTO3_TEST_OPTIONAL_HAS_FIELD(Enum, Message3Optional_Enum_Bar, Message3Optional_Enum_Foo)
+//%PDDM-EXPAND PROTO3_TEST_OPTIONAL_HAS_FIELDS()
+// This block of code is generated, do not edit it directly.
+// clang-format off
+
+ { // optionalInt32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt32));
+ msg.optionalInt32 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt32));
+ msg.hasOptionalInt32 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt32));
+ msg.optionalInt32 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt32));
+ [msg release];
+ }
+
+ { // optionalInt64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt64));
+ msg.optionalInt64 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt64));
+ msg.hasOptionalInt64 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt64));
+ msg.optionalInt64 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalInt64));
+ [msg release];
+ }
+
+ { // optionalUint32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint32));
+ msg.optionalUint32 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint32));
+ msg.hasOptionalUint32 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint32));
+ msg.optionalUint32 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint32));
+ [msg release];
+ }
+
+ { // optionalUint64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint64));
+ msg.optionalUint64 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint64));
+ msg.hasOptionalUint64 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint64));
+ msg.optionalUint64 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalUint64));
+ [msg release];
+ }
+
+ { // optionalSint32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint32));
+ msg.optionalSint32 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint32));
+ msg.hasOptionalSint32 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint32));
+ msg.optionalSint32 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint32));
+ [msg release];
+ }
+
+ { // optionalSint64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint64));
+ msg.optionalSint64 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint64));
+ msg.hasOptionalSint64 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint64));
+ msg.optionalSint64 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSint64));
+ [msg release];
+ }
+
+ { // optionalFixed32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed32));
+ msg.optionalFixed32 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed32));
+ msg.hasOptionalFixed32 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed32));
+ msg.optionalFixed32 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed32));
+ [msg release];
+ }
+
+ { // optionalFixed64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed64));
+ msg.optionalFixed64 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed64));
+ msg.hasOptionalFixed64 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed64));
+ msg.optionalFixed64 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFixed64));
+ [msg release];
+ }
+
+ { // optionalSfixed32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed32));
+ msg.optionalSfixed32 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed32));
+ msg.hasOptionalSfixed32 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed32));
+ msg.optionalSfixed32 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed32));
+ [msg release];
+ }
+
+ { // optionalSfixed64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed64));
+ msg.optionalSfixed64 = 1;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed64));
+ msg.hasOptionalSfixed64 = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed64));
+ msg.optionalSfixed64 = 0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalSfixed64));
+ [msg release];
+ }
+
+ { // optionalFloat
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFloat));
+ msg.optionalFloat = 1.0f;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFloat));
+ msg.hasOptionalFloat = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFloat));
+ msg.optionalFloat = 0.0f;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalFloat));
+ [msg release];
+ }
+
+ { // optionalDouble
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalDouble));
+ msg.optionalDouble = 1.0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalDouble));
+ msg.hasOptionalDouble = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalDouble));
+ msg.optionalDouble = 0.0;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalDouble));
+ [msg release];
+ }
+
+ { // optionalBool
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBool));
+ msg.optionalBool = YES;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBool));
+ msg.hasOptionalBool = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBool));
+ msg.optionalBool = NO;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBool));
+ [msg release];
+ }
+
+ { // optionalString
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalString));
+ msg.optionalString = @"foo";
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalString));
+ msg.hasOptionalString = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalString));
+ msg.optionalString = @"";
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalString));
+ [msg release];
+ }
+
+ { // optionalBytes
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBytes));
+ msg.optionalBytes = [@"foo" dataUsingEncoding:NSUTF8StringEncoding];
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBytes));
+ msg.hasOptionalBytes = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBytes));
+ msg.optionalBytes = [NSData data];
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalBytes));
+ [msg release];
+ }
+
+ //
+ // Test doesn't apply to optionalMessage (no groups in proto3).
+ //
+
+ { // optionalEnum
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalEnum));
+ msg.optionalEnum = Message3Optional_Enum_Bar;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalEnum));
+ msg.hasOptionalEnum = NO;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalEnum));
+ msg.optionalEnum = Message3Optional_Enum_Foo;
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3Optional_FieldNumber_OptionalEnum));
+ [msg release];
+ }
+
+// clang-format on
+//%PDDM-EXPAND-END PROTO3_TEST_OPTIONAL_HAS_FIELDS()
+}
+
- (void)testAccessingProto2UnknownEnumValues {
Message2 *msg = [[Message2 alloc] init];
@@ -2234,7 +2498,7 @@
- (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
+ // reset/cleared. But in a oneof, it still gets recorded so it can go out
// over the wire and the other side can see what was set in the oneof.
NSString *oneofStringDefault = @"";
@@ -2367,7 +2631,7 @@
XCTAssertNotEqual(msg1, msg2); // Ptr compare, new object.
XCTAssertEqualObjects(msg1, msg2); // Equal values.
- // Pointer comparisions, different objects.
+ // Pointer comparisons, different objects.
XCTAssertNotEqual(msg1.optionalGroup, msg2.optionalGroup);
XCTAssertNotEqual(msg1.optionalNestedMessage, msg2.optionalNestedMessage);
@@ -2423,7 +2687,7 @@
XCTAssertNotEqual(msg1, msg2); // Ptr compare, new object.
XCTAssertEqualObjects(msg1, msg2); // Equal values.
- // Pointer comparisions, different objects.
+ // Pointer comparisons, different objects.
XCTAssertNotEqual(msg1.mapInt32Int32, msg2.mapInt32Int32);
XCTAssertNotEqual(msg1.mapInt64Int64, msg2.mapInt64Int64);
XCTAssertNotEqual(msg1.mapUint32Uint32, msg2.mapUint32Uint32);
@@ -2492,7 +2756,7 @@
}
- (void)test_StringFieldsCopy {
- // ObjC conventions call for NSString properites to be copy, ensure
+ // ObjC conventions call for NSString properties to be copy, ensure
// that is done correctly and the string isn't simply retained.
Message2 *msg1 = [Message2 message];
@@ -2507,25 +2771,25 @@
XCTAssertEqualObjects(msg1.optionalString, mutableStr);
XCTAssertEqualObjects(msg1.optionalString, @"foo");
- XCTAssertTrue(msg1.optionalString != mutableStr); // Ptr comparision.
+ XCTAssertTrue(msg1.optionalString != mutableStr); // Ptr comparison.
XCTAssertEqualObjects(msg2.optionalString, mutableStr);
XCTAssertEqualObjects(msg2.optionalString, @"foo");
- XCTAssertTrue(msg2.optionalString != mutableStr); // Ptr comparision.
+ XCTAssertTrue(msg2.optionalString != mutableStr); // Ptr comparison.
[mutableStr appendString:@"bar"];
XCTAssertNotEqualObjects(msg1.optionalString, mutableStr);
XCTAssertEqualObjects(msg1.optionalString, @"foo");
- XCTAssertTrue(msg1.optionalString != mutableStr); // Ptr comparision.
+ XCTAssertTrue(msg1.optionalString != mutableStr); // Ptr comparison.
XCTAssertNotEqualObjects(msg2.optionalString, mutableStr);
XCTAssertEqualObjects(msg2.optionalString, @"foo");
- XCTAssertTrue(msg2.optionalString != mutableStr); // Ptr comparision.
+ XCTAssertTrue(msg2.optionalString != mutableStr); // Ptr comparison.
}
- (void)test_BytesFieldsCopy {
- // ObjC conventions call for NSData properites to be copy, ensure
+ // ObjC conventions call for NSData properties to be copy, ensure
// that is done correctly and the data isn't simply retained.
Message2 *msg1 = [Message2 message];
@@ -2540,21 +2804,21 @@
XCTAssertEqualObjects(msg1.optionalBytes, mutableData);
XCTAssertEqualObjects(msg1.optionalBytes, DataFromCStr("abc"));
- XCTAssertTrue(msg1.optionalBytes != mutableData); // Ptr comparision.
+ XCTAssertTrue(msg1.optionalBytes != mutableData); // Ptr comparison.
XCTAssertEqualObjects(msg2.optionalBytes, mutableData);
XCTAssertEqualObjects(msg2.optionalBytes, DataFromCStr("abc"));
- XCTAssertTrue(msg2.optionalBytes != mutableData); // Ptr comparision.
+ XCTAssertTrue(msg2.optionalBytes != mutableData); // Ptr comparison.
[mutableData appendData:DataFromCStr("123")];
XCTAssertNotEqualObjects(msg1.optionalBytes, mutableData);
XCTAssertEqualObjects(msg1.optionalBytes, DataFromCStr("abc"));
- XCTAssertTrue(msg1.optionalBytes != mutableData); // Ptr comparision.
+ XCTAssertTrue(msg1.optionalBytes != mutableData); // Ptr comparison.
XCTAssertNotEqualObjects(msg2.optionalBytes, mutableData);
XCTAssertEqualObjects(msg2.optionalBytes, DataFromCStr("abc"));
- XCTAssertTrue(msg2.optionalBytes != mutableData); // Ptr comparision.
+ XCTAssertTrue(msg2.optionalBytes != mutableData); // Ptr comparison.
}
#pragma mark - Subset from from map_tests.cc
diff --git a/objectivec/Tests/GPBMessageTests+Serialization.m b/objectivec/Tests/GPBMessageTests+Serialization.m
index 921feab..6f20797 100644
--- a/objectivec/Tests/GPBMessageTests+Serialization.m
+++ b/objectivec/Tests/GPBMessageTests+Serialization.m
@@ -109,6 +109,317 @@
[msg release];
}
+- (void)testProto3SerializationHandlingOptionals {
+ //
+ // Proto3 optionals should be just like proto2, zero values also get serialized.
+ //
+
+//%PDDM-DEFINE PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(FIELD, ZERO_VALUE, EXPECTED_LEN)
+//% { // optional##FIELD
+//% Message3Optional *msg = [[Message3Optional alloc] init];
+//% NSData *data = [msg data];
+//% XCTAssertEqual([data length], 0U);
+//% msg.optional##FIELD = ZERO_VALUE;
+//% data = [msg data];
+//% XCTAssertEqual(data.length, EXPECTED_LEN);
+//% NSError *err = nil;
+//% Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+//% XCTAssertNotNil(msg2);
+//% XCTAssertNil(err);
+//% XCTAssertTrue(msg2.hasOptional##FIELD);
+//% XCTAssertEqualObjects(msg, msg2);
+//% [msg release];
+//% }
+//%
+//%PDDM-DEFINE PROTO3_TEST_SERIALIZE_OPTIONAL_FIELDS()
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Int32, 0, 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Int64, 0, 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Uint32, 0, 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Uint64, 0, 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Sint32, 0, 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Sint64, 0, 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Fixed32, 0, 5)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Fixed64, 0, 9)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Sfixed32, 0, 5)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Sfixed64, 0, 9)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Float, 0.0f, 5)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Double, 0.0, 9)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Bool, NO, 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(String, @"", 2)
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Bytes, [NSData data], 2)
+//% //
+//% // Test doesn't apply to optionalMessage (no groups in proto3).
+//% //
+//%
+//%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Enum, Message3Optional_Enum_Foo, 3)
+//%PDDM-EXPAND PROTO3_TEST_SERIALIZE_OPTIONAL_FIELDS()
+// This block of code is generated, do not edit it directly.
+// clang-format off
+
+ { // optionalInt32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalInt32 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalInt32);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalInt64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalInt64 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalInt64);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalUint32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalUint32 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalUint32);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalUint64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalUint64 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalUint64);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalSint32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalSint32 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalSint32);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalSint64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalSint64 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalSint64);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalFixed32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalFixed32 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 5);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalFixed32);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalFixed64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalFixed64 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 9);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalFixed64);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalSfixed32
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalSfixed32 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 5);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalSfixed32);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalSfixed64
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalSfixed64 = 0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 9);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalSfixed64);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalFloat
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalFloat = 0.0f;
+ data = [msg data];
+ XCTAssertEqual(data.length, 5);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalFloat);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalDouble
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalDouble = 0.0;
+ data = [msg data];
+ XCTAssertEqual(data.length, 9);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalDouble);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalBool
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalBool = NO;
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalBool);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalString
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalString = @"";
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalString);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ { // optionalBytes
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalBytes = [NSData data];
+ data = [msg data];
+ XCTAssertEqual(data.length, 2);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalBytes);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+ //
+ // Test doesn't apply to optionalMessage (no groups in proto3).
+ //
+
+ { // optionalEnum
+ Message3Optional *msg = [[Message3Optional alloc] init];
+ NSData *data = [msg data];
+ XCTAssertEqual([data length], 0U);
+ msg.optionalEnum = Message3Optional_Enum_Foo;
+ data = [msg data];
+ XCTAssertEqual(data.length, 3);
+ NSError *err = nil;
+ Message3Optional *msg2 = [Message3Optional parseFromData:data error:&err];
+ XCTAssertNotNil(msg2);
+ XCTAssertNil(err);
+ XCTAssertTrue(msg2.hasOptionalEnum);
+ XCTAssertEqualObjects(msg, msg2);
+ [msg release];
+ }
+
+// clang-format on
+//%PDDM-EXPAND-END PROTO3_TEST_SERIALIZE_OPTIONAL_FIELDS()
+}
+
- (void)testProto2UnknownEnumToUnknownField {
Message3 *orig = [[Message3 alloc] init];
@@ -273,6 +584,7 @@
//%
//%PDDM-EXPAND TEST_ROUNDTRIP_ONEOFS(2, NO)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)testProto2RoundTripOneof {
@@ -503,8 +815,10 @@
[subMessage release];
}
+// clang-format on
//%PDDM-EXPAND TEST_ROUNDTRIP_ONEOFS(3, YES)
// This block of code is generated, do not edit it directly.
+// clang-format off
- (void)testProto3RoundTripOneof {
@@ -721,6 +1035,7 @@
[subMessage release];
}
+// clang-format on
//%PDDM-EXPAND-END (2 expansions)
- (void)testPackedUnpackedMessageParsing {
diff --git a/objectivec/Tests/GPBMessageTests.m b/objectivec/Tests/GPBMessageTests.m
index dec6cd7..ea224fa 100644
--- a/objectivec/Tests/GPBMessageTests.m
+++ b/objectivec/Tests/GPBMessageTests.m
@@ -1131,10 +1131,10 @@
XCTAssertNotNil(message.a.iArray);
XCTAssertFalse([message hasA]);
GPBInt32Array *iArray = [message.a.iArray retain];
- XCTAssertEqual(iArray->_autocreator, message.a); // Pointer comparision
+ XCTAssertEqual(iArray->_autocreator, message.a); // Pointer comparison
message.a.iArray = [GPBInt32Array arrayWithValue:1];
XCTAssertTrue([message hasA]);
- XCTAssertNotEqual(message.a.iArray, iArray); // Pointer comparision
+ XCTAssertNotEqual(message.a.iArray, iArray); // Pointer comparison
XCTAssertNil(iArray->_autocreator);
[iArray release];
}
@@ -1148,10 +1148,10 @@
GPBAutocreatedArray *strArray =
(GPBAutocreatedArray *)[message.a.strArray retain];
XCTAssertTrue([strArray isKindOfClass:[GPBAutocreatedArray class]]);
- XCTAssertEqual(strArray->_autocreator, message.a); // Pointer comparision
+ XCTAssertEqual(strArray->_autocreator, message.a); // Pointer comparison
message.a.strArray = [NSMutableArray arrayWithObject:@"foo"];
XCTAssertTrue([message hasA]);
- XCTAssertNotEqual(message.a.strArray, strArray); // Pointer comparision
+ XCTAssertNotEqual(message.a.strArray, strArray); // Pointer comparison
XCTAssertNil(strArray->_autocreator);
[strArray release];
}
@@ -1348,11 +1348,11 @@
XCTAssertNotNil(message.a.iToI);
XCTAssertFalse([message hasA]);
GPBInt32Int32Dictionary *iToI = [message.a.iToI retain];
- XCTAssertEqual(iToI->_autocreator, message.a); // Pointer comparision
+ XCTAssertEqual(iToI->_autocreator, message.a); // Pointer comparison
message.a.iToI = [[[GPBInt32Int32Dictionary alloc] init] autorelease];
[message.a.iToI setInt32:6 forKey:7];
XCTAssertTrue([message hasA]);
- XCTAssertNotEqual(message.a.iToI, iToI); // Pointer comparision
+ XCTAssertNotEqual(message.a.iToI, iToI); // Pointer comparison
XCTAssertNil(iToI->_autocreator);
[iToI release];
}
@@ -1366,11 +1366,11 @@
GPBAutocreatedDictionary *strToStr =
(GPBAutocreatedDictionary *)[message.a.strToStr retain];
XCTAssertTrue([strToStr isKindOfClass:[GPBAutocreatedDictionary class]]);
- XCTAssertEqual(strToStr->_autocreator, message.a); // Pointer comparision
+ XCTAssertEqual(strToStr->_autocreator, message.a); // Pointer comparison
message.a.strToStr =
[NSMutableDictionary dictionaryWithObject:@"abc" forKey:@"def"];
XCTAssertTrue([message hasA]);
- XCTAssertNotEqual(message.a.strToStr, strToStr); // Pointer comparision
+ XCTAssertNotEqual(message.a.strToStr, strToStr); // Pointer comparison
XCTAssertNil(strToStr->_autocreator);
[strToStr release];
}
@@ -1918,7 +1918,7 @@
aTime = Time_SomethingElse;
Time_IsValidValue(aTime);
- // This block confirms the names in the decriptors is what we wanted.
+ // This block confirms the names in the descriptors is what we wanted.
GPBEnumDescriptor *descriptor;
NSString *valueName;
diff --git a/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm b/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm
index 9ba8fd0..fb67495 100644
--- a/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm
+++ b/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm
@@ -35,7 +35,7 @@
//
// This is just a compile test (here to make sure things never regress).
//
-// Objective C++ can run into issues with how the NS_ENUM/CF_ENUM declartion
+// Objective C++ can run into issues with how the NS_ENUM/CF_ENUM declaration
// works because of the C++ spec being used for that compilation unit. So
// the fact that these imports all work without errors/warning means things
// are still good.
diff --git a/objectivec/Tests/GPBSwiftTests.swift b/objectivec/Tests/GPBSwiftTests.swift
index 9d8a0fa..03d7510 100644
--- a/objectivec/Tests/GPBSwiftTests.swift
+++ b/objectivec/Tests/GPBSwiftTests.swift
@@ -276,7 +276,7 @@
msg5.optionalInt32 = 123
msg.optional = msg5
XCTAssertTrue(msg.hasOptionalMessage)
- // Modifing the autocreated doesn't replaced the explicit set one.
+ // Modifying the autocreated doesn't replaced the explicit set one.
autoCreated?.optionalInt32 = 456
XCTAssertTrue(msg.hasOptionalMessage)
XCTAssertTrue(msg.optional === msg5)
@@ -355,7 +355,7 @@
msg.oneof = nil
XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default
XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
-}
+ }
func testProto3OneOfSupport() {
let msg = Message3()
diff --git a/objectivec/Tests/GPBUnknownFieldSetTest.m b/objectivec/Tests/GPBUnknownFieldSetTest.m
index 8e03a42..5fa60b2 100644
--- a/objectivec/Tests/GPBUnknownFieldSetTest.m
+++ b/objectivec/Tests/GPBUnknownFieldSetTest.m
@@ -156,25 +156,34 @@
GPBUnknownFieldSet* bizarroFields =
[[[GPBUnknownFieldSet alloc] init] autorelease];
NSUInteger count = [unknownFields_ countOfFields];
- int32_t tags[count];
- [unknownFields_ getTags:tags];
- for (NSUInteger i = 0; i < count; ++i) {
- int32_t tag = tags[i];
- GPBUnknownField* field = [unknownFields_ getField:tag];
- if (field.varintList.count == 0) {
- // Original field is not a varint, so use a varint.
- GPBUnknownField* varintField =
- [[[GPBUnknownField alloc] initWithNumber:tag] autorelease];
- [varintField addVarint:1];
- [bizarroFields addField:varintField];
- } else {
- // Original field *is* a varint, so use something else.
- GPBUnknownField* fixed32Field =
- [[[GPBUnknownField alloc] initWithNumber:tag] autorelease];
- [fixed32Field addFixed32:1];
- [bizarroFields addField:fixed32Field];
+ int32_t *tags = malloc(count * sizeof(int32_t));
+ if (!tags) {
+ XCTFail(@"Failed to make scratch buffer for testing");
+ return [NSData data];
+ }
+ @try {
+ [unknownFields_ getTags:tags];
+ for (NSUInteger i = 0; i < count; ++i) {
+ int32_t tag = tags[i];
+ GPBUnknownField* field = [unknownFields_ getField:tag];
+ if (field.varintList.count == 0) {
+ // Original field is not a varint, so use a varint.
+ GPBUnknownField* varintField =
+ [[[GPBUnknownField alloc] initWithNumber:tag] autorelease];
+ [varintField addVarint:1];
+ [bizarroFields addField:varintField];
+ } else {
+ // Original field *is* a varint, so use something else.
+ GPBUnknownField* fixed32Field =
+ [[[GPBUnknownField alloc] initWithNumber:tag] autorelease];
+ [fixed32Field addFixed32:1];
+ [bizarroFields addField:fixed32Field];
+ }
}
}
+ @finally {
+ free(tags);
+ }
return [bizarroFields data];
}
diff --git a/objectivec/Tests/unittest_extension_chain_f.proto b/objectivec/Tests/unittest_extension_chain_f.proto
index b9bed72..096598d 100644
--- a/objectivec/Tests/unittest_extension_chain_f.proto
+++ b/objectivec/Tests/unittest_extension_chain_f.proto
@@ -34,7 +34,7 @@
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).
+// Root (because G doesn'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.
diff --git a/objectivec/Tests/unittest_runtime_proto3.proto b/objectivec/Tests/unittest_runtime_proto3.proto
index ad2e362..c2ee5fb 100644
--- a/objectivec/Tests/unittest_runtime_proto3.proto
+++ b/objectivec/Tests/unittest_runtime_proto3.proto
@@ -119,3 +119,31 @@
map<int32 , Enum > map_int32_enum = 87;
map<int32 , Message3> map_int32_message = 88;
}
+
+message Message3Optional {
+ enum Enum {
+ FOO = 0;
+ BAR = 1;
+ BAZ = 2;
+ EXTRA_3 = 30;
+ }
+
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional sint32 optional_sint32 = 5;
+ optional sint64 optional_sint64 = 6;
+ optional fixed32 optional_fixed32 = 7;
+ optional fixed64 optional_fixed64 = 8;
+ optional sfixed32 optional_sfixed32 = 9;
+ optional sfixed64 optional_sfixed64 = 10;
+ optional float optional_float = 11;
+ optional double optional_double = 12;
+ optional bool optional_bool = 13;
+ optional string optional_string = 14;
+ optional bytes optional_bytes = 15;
+ // No 'group' in proto3.
+ optional Message3 optional_message = 18;
+ optional Enum optional_enum = 19;
+}
diff --git a/objectivec/generate_well_known_types.sh b/objectivec/generate_well_known_types.sh
index 36c3460..1b9de6e 100755
--- a/objectivec/generate_well_known_types.sh
+++ b/objectivec/generate_well_known_types.sh
@@ -10,7 +10,8 @@
set -eu
readonly ScriptDir=$(dirname "$(echo $0 | sed -e "s,^\([^/]\),$(pwd)/\1,")")
-readonly ProtoRootDir="${ScriptDir}/.."
+readonly ObjCDir="${ScriptDir}"
+readonly ProtoRootDir="${ObjCDir}/.."
# Flag for continuous integration to check that everything is current.
CHECK_ONLY=0
@@ -19,9 +20,9 @@
shift
fi
-pushd "${ProtoRootDir}" > /dev/null
+cd "${ProtoRootDir}"
-if test ! -e src/google/protobuf/stubs/common.h; then
+if [[ ! -e src/google/protobuf/stubs/common.h ]]; then
cat >&2 << __EOF__
Could not find source code. Make sure you are running this script from the
root of the distribution tree.
@@ -29,7 +30,7 @@
exit 1
fi
-if test ! -e src/Makefile; then
+if [[ ! -e src/Makefile ]]; then
cat >&2 << __EOF__
Could not find src/Makefile. You must run ./configure (and perhaps
./autogen.sh) first.
@@ -53,24 +54,36 @@
google/protobuf/type.proto \
google/protobuf/wrappers.proto)
+declare -a OBJC_EXTENSIONS=( .pbobjc.h .pbobjc.m )
+
# Generate to a temp directory to see if they match.
TMP_DIR=$(mktemp -d)
trap "rm -rf ${TMP_DIR}" EXIT
./protoc --objc_out="${TMP_DIR}" ${RUNTIME_PROTO_FILES[@]}
-set +e
-diff -r "${TMP_DIR}/google" "${ProtoRootDir}/objectivec/google" > /dev/null
-if [[ $? -eq 0 ]] ; then
- echo "Generated source for WellKnownTypes is current."
+
+DID_COPY=0
+for PROTO_FILE in "${RUNTIME_PROTO_FILES[@]}"; do
+ DIR=${PROTO_FILE%/*}
+ BASE_NAME=${PROTO_FILE##*/}
+ # Drop the extension
+ BASE_NAME=${BASE_NAME%.*}
+ OBJC_NAME=$(echo "${BASE_NAME}" | awk -F _ '{for(i=1; i<=NF; i++) printf "%s", toupper(substr($i,1,1)) substr($i,2);}')
+
+ for EXT in "${OBJC_EXTENSIONS[@]}"; do
+ if ! diff "${ObjCDir}/GPB${OBJC_NAME}${EXT}" "${TMP_DIR}/${DIR}/${OBJC_NAME}${EXT}" > /dev/null 2>&1 ; then
+ if [[ "${CHECK_ONLY}" == 1 ]] ; then
+ echo "ERROR: The WKTs need to be regenerated! Run $0"
+ exit 1
+ fi
+
+ echo "INFO: Updating GPB${OBJC_NAME}${EXT}"
+ cp "${TMP_DIR}/${DIR}/${OBJC_NAME}${EXT}" "${ObjCDir}/GPB${OBJC_NAME}${EXT}"
+ DID_COPY=1
+ fi
+ done
+done
+
+if [[ "${DID_COPY}" == 0 ]]; then
+ echo "INFO: Generated source for WellKnownTypes is current."
exit 0
fi
-set -e
-
-# If check only mode, error out.
-if [[ "${CHECK_ONLY}" == 1 ]] ; then
- echo "ERROR: The WKTs need to be regenerated! Run $0"
- exit 1
-fi
-
-# Copy them over.
-echo "Copying over updated WellKnownType sources."
-cp -r "${TMP_DIR}/google/." "${ProtoRootDir}/objectivec/google/"
diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h
index f22c8c5..e6d1b74 100644
--- a/objectivec/google/protobuf/Any.pbobjc.h
+++ b/objectivec/google/protobuf/Any.pbobjc.h
@@ -1,183 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/any.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-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.
- **/
-@interface GPBAnyRoot : GPBRootObject
-@end
-
-#pragma mark - GPBAny
-
-typedef GPB_ENUM(GPBAny_FieldNumber) {
- GPBAny_FieldNumber_TypeURL = 1,
- 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)
- * ...
- *
- * Example 4: Pack and unpack a message in Go
- *
- * foo := &pb.Foo{...}
- * any, err := ptypes.MarshalAny(foo)
- * ...
- * foo := &pb.Foo{}
- * if err := ptypes.UnmarshalAny(any, foo); err != nil {
- * ...
- * }
- *
- * The pack methods provided by protobuf library will by default use
- * 'type.googleapis.com/full.type.name' as the type URL and the unpack
- * methods only use the fully qualified type name after the last '/'
- * 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 that uniquely identifies the type of the serialized
- * protocol buffer message. This string must contain at least
- * one "/" character. The last segment of the URL's path must represent
- * the fully qualified name of the type (as in
- * `path/google.protobuf.Duration`). The name should be in a canonical form
- * (e.g., leading "." is not accepted).
- *
- * In practice, teams usually precompile into the binary all types that they
- * expect it to use in the context of Any. However, for URLs which use the
- * scheme `http`, `https`, or no scheme, one can optionally set up a type
- * server that maps type URLs to message definitions as follows:
- *
- * * If no scheme is provided, `https` is assumed.
- * * An HTTP GET on the URL must yield a [google.protobuf.Type][]
- * value in binary format, or produce an error.
- * * Applications are allowed to cache lookup results based on the
- * URL, or have them precompiled into a binary to avoid any
- * lookup. Therefore, binary compatibility needs to be preserved
- * on changes to types. (Use versioned type names to manage
- * breaking changes.)
- *
- * Note: this functionality is not currently available in the official
- * protobuf release, and it is not used for type URLs beginning with
- * type.googleapis.com.
- *
- * Schemes other than `http`, `https` (or the empty scheme) might be
- * used with implementation specific semantics.
- **/
-@property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL;
-
-/** Must be a valid serialized protocol buffer of the above specified type. */
-@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBAny.pbobjc.h"
diff --git a/objectivec/google/protobuf/Api.pbobjc.h b/objectivec/google/protobuf/Api.pbobjc.h
index 99acd04..e7957db 100644
--- a/objectivec/google/protobuf/Api.pbobjc.h
+++ b/objectivec/google/protobuf/Api.pbobjc.h
@@ -1,311 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/api.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-@class GPBMethod;
-@class GPBMixin;
-@class GPBOption;
-@class GPBSourceContext;
-GPB_ENUM_FWD_DECLARE(GPBSyntax);
-
-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.
- **/
-@interface GPBApiRoot : GPBRootObject
-@end
-
-#pragma mark - GPBApi
-
-typedef GPB_ENUM(GPBApi_FieldNumber) {
- GPBApi_FieldNumber_Name = 1,
- GPBApi_FieldNumber_MethodsArray = 2,
- GPBApi_FieldNumber_OptionsArray = 3,
- GPBApi_FieldNumber_Version = 4,
- GPBApi_FieldNumber_SourceContext = 5,
- GPBApi_FieldNumber_MixinsArray = 6,
- GPBApi_FieldNumber_Syntax = 7,
-};
-
-/**
- * Api is a light-weight descriptor for an API Interface.
- *
- * Interfaces are also described as "protocol buffer services" in some contexts,
- * such as by the "service" keyword in a .proto file, but they are different
- * from API Services, which represent a concrete implementation of an interface
- * as opposed to simply a description of methods and bindings. They are also
- * sometimes simply referred to as "APIs" in other contexts, such as the name of
- * this message itself. See https://cloud.google.com/apis/design/glossary for
- * detailed terminology.
- **/
-@interface GPBApi : GPBMessage
-
-/**
- * The fully qualified name of this interface, including package name
- * followed by the interface's simple name.
- **/
-@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-
-/** The methods of this interface, in unspecified order. */
-@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMethod*> *methodsArray;
-/** The number of items in @c methodsArray without causing the array to be created. */
-@property(nonatomic, readonly) NSUInteger methodsArray_Count;
-
-/** Any metadata attached to the interface. */
-@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
-/** The number of items in @c optionsArray without causing the array to be created. */
-@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-
-/**
- * A version string for this interface. If specified, must have the form
- * `major-version.minor-version`, as in `1.10`. If the minor version is
- * omitted, it defaults to zero. If the entire version field is empty, the
- * major version is derived from the package name, as outlined below. If the
- * field is not empty, the version in the package name will be verified to be
- * consistent with what is provided here.
- *
- * The versioning schema uses [semantic
- * versioning](http://semver.org) where the major version number
- * indicates a breaking change and the minor version an additive,
- * non-breaking change. Both version numbers are signals to users
- * what to expect from different versions, and should be carefully
- * chosen based on the product plan.
- *
- * The major version is also reflected in the package name of the
- * interface, which must end in `v<major-version>`, as in
- * `google.feature.v1`. For major versions 0 and 1, the suffix can
- * be omitted. Zero major versions must only be used for
- * experimental, non-GA interfaces.
- **/
-@property(nonatomic, readwrite, copy, null_resettable) NSString *version;
-
-/**
- * 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. */
-@property(nonatomic, readwrite) BOOL hasSourceContext;
-
-/** Included interfaces. See [Mixin][]. */
-@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMixin*> *mixinsArray;
-/** The number of items in @c mixinsArray without causing the array to be created. */
-@property(nonatomic, readonly) NSUInteger mixinsArray_Count;
-
-/** 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.
- **/
-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.
- **/
-void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value);
-
-#pragma mark - GPBMethod
-
-typedef GPB_ENUM(GPBMethod_FieldNumber) {
- GPBMethod_FieldNumber_Name = 1,
- GPBMethod_FieldNumber_RequestTypeURL = 2,
- GPBMethod_FieldNumber_RequestStreaming = 3,
- GPBMethod_FieldNumber_ResponseTypeURL = 4,
- GPBMethod_FieldNumber_ResponseStreaming = 5,
- GPBMethod_FieldNumber_OptionsArray = 6,
- GPBMethod_FieldNumber_Syntax = 7,
-};
-
-/**
- * Method represents a method of an API interface.
- **/
-@interface GPBMethod : GPBMessage
-
-/** The simple name of this method. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-
-/** A URL of the input message type. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *requestTypeURL;
-
-/** If true, the request is streamed. */
-@property(nonatomic, readwrite) BOOL requestStreaming;
-
-/** The URL of the output message type. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *responseTypeURL;
-
-/** If true, the response is streamed. */
-@property(nonatomic, readwrite) BOOL responseStreaming;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-
-/** 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.
- **/
-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.
- **/
-void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value);
-
-#pragma mark - GPBMixin
-
-typedef GPB_ENUM(GPBMixin_FieldNumber) {
- GPBMixin_FieldNumber_Name = 1,
- GPBMixin_FieldNumber_Root = 2,
-};
-
-/**
- * Declares an API Interface to be included in this interface. The including
- * interface must redeclare all the methods from the included interface, but
- * documentation and options are inherited as follows:
- *
- * - If after comment and whitespace stripping, the documentation
- * string of the redeclared method is empty, it will be inherited
- * from the original method.
- *
- * - Each annotation belonging to the service config (http,
- * visibility) which is not set in the redeclared method will be
- * inherited.
- *
- * - If an http annotation is inherited, the path pattern will be
- * modified as follows. Any version prefix will be replaced by the
- * version of the including interface plus the [root][] path if
- * specified.
- *
- * Example of a simple mixin:
- *
- * package google.acl.v1;
- * service AccessControl {
- * // Get the underlying ACL object.
- * rpc GetAcl(GetAclRequest) returns (Acl) {
- * option (google.api.http).get = "/v1/{resource=**}:getAcl";
- * }
- * }
- *
- * package google.storage.v2;
- * service Storage {
- * rpc GetAcl(GetAclRequest) returns (Acl);
- *
- * // Get a data record.
- * rpc GetData(GetDataRequest) returns (Data) {
- * option (google.api.http).get = "/v2/{resource=**}";
- * }
- * }
- *
- * Example of a mixin configuration:
- *
- * apis:
- * - name: google.storage.v2.Storage
- * mixins:
- * - name: google.acl.v1.AccessControl
- *
- * The mixin construct implies that all methods in `AccessControl` are
- * also declared with same name and request/response types in
- * `Storage`. A documentation generator or annotation processor will
- * see the effective `Storage.GetAcl` method after inherting
- * documentation and annotations as follows:
- *
- * service Storage {
- * // Get the underlying ACL object.
- * rpc GetAcl(GetAclRequest) returns (Acl) {
- * option (google.api.http).get = "/v2/{resource=**}:getAcl";
- * }
- * ...
- * }
- *
- * Note how the version in the path pattern changed from `v1` to `v2`.
- *
- * If the `root` field in the mixin is specified, it should be a
- * relative path under which inherited HTTP paths are placed. Example:
- *
- * apis:
- * - name: google.storage.v2.Storage
- * mixins:
- * - name: google.acl.v1.AccessControl
- * root: acls
- *
- * This implies the following inherited HTTP annotation:
- *
- * service Storage {
- * // Get the underlying ACL object.
- * rpc GetAcl(GetAclRequest) returns (Acl) {
- * option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
- * }
- * ...
- * }
- **/
-@interface GPBMixin : GPBMessage
-
-/** The fully qualified name of the interface which is included. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-
-/**
- * If non-empty specifies a path under which inherited HTTP paths
- * are rooted.
- **/
-@property(nonatomic, readwrite, copy, null_resettable) NSString *root;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBApi.pbobjc.h"
diff --git a/objectivec/google/protobuf/Duration.pbobjc.h b/objectivec/google/protobuf/Duration.pbobjc.h
index 111a910..fabf00f 100644
--- a/objectivec/google/protobuf/Duration.pbobjc.h
+++ b/objectivec/google/protobuf/Duration.pbobjc.h
@@ -1,145 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/duration.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-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.
- **/
-@interface GPBDurationRoot : GPBRootObject
-@end
-
-#pragma mark - GPBDuration
-
-typedef GPB_ENUM(GPBDuration_FieldNumber) {
- GPBDuration_FieldNumber_Seconds = 1,
- 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.
- *
- * # Examples
- *
- * Example 1: Compute Duration from two Timestamps in pseudo code.
- *
- * Timestamp start = ...;
- * Timestamp end = ...;
- * Duration duration = ...;
- *
- * duration.seconds = end.seconds - start.seconds;
- * duration.nanos = end.nanos - start.nanos;
- *
- * if (duration.seconds < 0 && duration.nanos > 0) {
- * duration.seconds += 1;
- * duration.nanos -= 1000000000;
- * } else if (duration.seconds > 0 && duration.nanos < 0) {
- * duration.seconds -= 1;
- * duration.nanos += 1000000000;
- * }
- *
- * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
- *
- * Timestamp start = ...;
- * Duration duration = ...;
- * Timestamp end = ...;
- *
- * end.seconds = start.seconds + duration.seconds;
- * end.nanos = start.nanos + duration.nanos;
- *
- * if (end.nanos < 0) {
- * end.seconds -= 1;
- * end.nanos += 1000000000;
- * } else if (end.nanos >= 1000000000) {
- * end.seconds += 1;
- * end.nanos -= 1000000000;
- * }
- *
- * Example 3: Compute Duration from datetime.timedelta in Python.
- *
- * td = datetime.timedelta(days=3, minutes=10)
- * duration = Duration()
- * duration.FromTimedelta(td)
- *
- * # JSON Mapping
- *
- * In JSON format, the Duration type is encoded as a string rather than an
- * object, where the string ends in the suffix "s" (indicating seconds) and
- * is preceded by the number of seconds, with nanoseconds expressed as
- * fractional seconds. For example, 3 seconds with 0 nanoseconds should be
- * encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
- * be expressed in JSON format as "3.000000001s", and 3 seconds and 1
- * microsecond should be expressed in JSON format as "3.000001s".
- **/
-@interface GPBDuration : GPBMessage
-
-/**
- * Signed seconds of the span of time. Must be from -315,576,000,000
- * to +315,576,000,000 inclusive. Note: these bounds are computed from:
- * 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
- **/
-@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.
- **/
-@property(nonatomic, readwrite) int32_t nanos;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBDuration.pbobjc.h"
diff --git a/objectivec/google/protobuf/Empty.pbobjc.h b/objectivec/google/protobuf/Empty.pbobjc.h
index 5b1e7b4..4de9108 100644
--- a/objectivec/google/protobuf/Empty.pbobjc.h
+++ b/objectivec/google/protobuf/Empty.pbobjc.h
@@ -1,74 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/empty.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-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.
- **/
-@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 `{}`.
- **/
-@interface GPBEmpty : GPBMessage
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBEmpty.pbobjc.h"
diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.h b/objectivec/google/protobuf/FieldMask.pbobjc.h
index 92d5042..2691320 100644
--- a/objectivec/google/protobuf/FieldMask.pbobjc.h
+++ b/objectivec/google/protobuf/FieldMask.pbobjc.h
@@ -1,273 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/field_mask.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-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.
- **/
-@interface GPBFieldMaskRoot : GPBRootObject
-@end
-
-#pragma mark - GPBFieldMask
-
-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
- * 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, new values will
- * be appended to the existing repeated field in the target resource. Note that
- * a repeated field is only allowed in the last position of a `paths` string.
- *
- * If a sub-message is specified in the last position of the field mask for an
- * update operation, then new value will be merged into the existing sub-message
- * in the target resource.
- *
- * For example, given the target message:
- *
- * f {
- * b {
- * d: 1
- * x: 2
- * }
- * c: [1]
- * }
- *
- * And an update message:
- *
- * f {
- * b {
- * d: 10
- * }
- * c: [2]
- * }
- *
- * then if the field mask is:
- *
- * paths: ["f.b", "f.c"]
- *
- * then the result will be:
- *
- * f {
- * b {
- * d: 10
- * x: 2
- * }
- * c: [1, 2]
- * }
- *
- * An implementation may provide options to override this default behavior for
- * repeated and message fields.
- *
- * In order to reset a field's value to the default, the field must
- * be in the mask and set to the default value in the provided resource.
- * 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.
- *
- * ## Field Mask Verification
- *
- * The implementation of any API method which has a FieldMask type field in the
- * request should verify the included field paths, and return an
- * `INVALID_ARGUMENT` error if any path is unmappable.
- **/
-@interface GPBFieldMask : GPBMessage
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger pathsArray_Count;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBFieldMask.pbobjc.h"
diff --git a/objectivec/google/protobuf/SourceContext.pbobjc.h b/objectivec/google/protobuf/SourceContext.pbobjc.h
index b2cdbba..321dfec 100644
--- a/objectivec/google/protobuf/SourceContext.pbobjc.h
+++ b/objectivec/google/protobuf/SourceContext.pbobjc.h
@@ -1,77 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/source_context.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-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.
- **/
-@interface GPBSourceContextRoot : GPBRootObject
-@end
-
-#pragma mark - GPBSourceContext
-
-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.
- **/
-@interface GPBSourceContext : GPBMessage
-
-/**
- * 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
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBSourceContext.pbobjc.h"
diff --git a/objectivec/google/protobuf/Struct.pbobjc.h b/objectivec/google/protobuf/Struct.pbobjc.h
index 8a06de4..1173d16 100644
--- a/objectivec/google/protobuf/Struct.pbobjc.h
+++ b/objectivec/google/protobuf/Struct.pbobjc.h
@@ -1,204 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/struct.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-@class GPBListValue;
-@class GPBStruct;
-@class GPBValue;
-
-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`.
- **/
-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.
- **/
- GPBNullValue_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /** 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.
- **/
-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.
- **/
-@interface GPBStructRoot : GPBRootObject
-@end
-
-#pragma mark - GPBStruct
-
-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.
- **/
-@interface GPBStruct : GPBMessage
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger fields_Count;
-
-@end
-
-#pragma mark - GPBValue
-
-typedef GPB_ENUM(GPBValue_FieldNumber) {
- GPBValue_FieldNumber_NullValue = 1,
- GPBValue_FieldNumber_NumberValue = 2,
- GPBValue_FieldNumber_StringValue = 3,
- GPBValue_FieldNumber_BoolValue = 4,
- GPBValue_FieldNumber_StructValue = 5,
- GPBValue_FieldNumber_ListValue = 6,
-};
-
-typedef GPB_ENUM(GPBValue_Kind_OneOfCase) {
- GPBValue_Kind_OneOfCase_GPBUnsetOneOfCase = 0,
- GPBValue_Kind_OneOfCase_NullValue = 1,
- GPBValue_Kind_OneOfCase_NumberValue = 2,
- GPBValue_Kind_OneOfCase_StringValue = 3,
- GPBValue_Kind_OneOfCase_BoolValue = 4,
- GPBValue_Kind_OneOfCase_StructValue = 5,
- 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.
- **/
-@interface GPBValue : GPBMessage
-
-/** The kind of value. */
-@property(nonatomic, readonly) GPBValue_Kind_OneOfCase kindOneOfCase;
-
-/** Represents a null value. */
-@property(nonatomic, readwrite) GPBNullValue nullValue;
-
-/** Represents a double value. */
-@property(nonatomic, readwrite) double numberValue;
-
-/** Represents a string value. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *stringValue;
-
-/** Represents a boolean value. */
-@property(nonatomic, readwrite) BOOL boolValue;
-
-/** Represents a structured value. */
-@property(nonatomic, readwrite, strong, null_resettable) GPBStruct *structValue;
-
-/** 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.
- **/
-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.
- **/
-void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value);
-
-/**
- * Clears whatever value was set for the oneof 'kind'.
- **/
-void GPBValue_ClearKindOneOfCase(GPBValue *message);
-
-#pragma mark - GPBListValue
-
-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.
- **/
-@interface GPBListValue : GPBMessage
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger valuesArray_Count;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBStruct.pbobjc.h"
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h
index d351f27..6a7cef8 100644
--- a/objectivec/google/protobuf/Timestamp.pbobjc.h
+++ b/objectivec/google/protobuf/Timestamp.pbobjc.h
@@ -1,167 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/timestamp.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-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.
- **/
-@interface GPBTimestampRoot : GPBRootObject
-@end
-
-#pragma mark - GPBTimestamp
-
-typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
- GPBTimestamp_FieldNumber_Seconds = 1,
- GPBTimestamp_FieldNumber_Nanos = 2,
-};
-
-/**
- * A Timestamp represents a point in time independent of any time zone or local
- * calendar, encoded as a count of seconds and fractions of seconds at
- * nanosecond resolution. The count is relative to an epoch at UTC midnight on
- * January 1, 1970, in the proleptic Gregorian calendar which extends the
- * Gregorian calendar backwards to year one.
- *
- * All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
- * second table is needed for interpretation, using a [24-hour linear
- * smear](https://developers.google.com/time/smear).
- *
- * The 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](https://www.ietf.org/rfc/rfc3339.txt) date strings.
- *
- * # Examples
- *
- * Example 1: Compute Timestamp from POSIX `time()`.
- *
- * Timestamp timestamp;
- * timestamp.set_seconds(time(NULL));
- * timestamp.set_nanos(0);
- *
- * Example 2: Compute Timestamp from POSIX `gettimeofday()`.
- *
- * struct timeval tv;
- * gettimeofday(&tv, NULL);
- *
- * Timestamp timestamp;
- * timestamp.set_seconds(tv.tv_sec);
- * timestamp.set_nanos(tv.tv_usec * 1000);
- *
- * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
- *
- * FILETIME ft;
- * GetSystemTimeAsFileTime(&ft);
- * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
- *
- * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
- * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
- * Timestamp timestamp;
- * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
- * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
- *
- * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
- *
- * long millis = System.currentTimeMillis();
- *
- * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
- * .setNanos((int) ((millis % 1000) * 1000000)).build();
- *
- *
- * Example 5: Compute Timestamp from current time in Python.
- *
- * timestamp = Timestamp()
- * timestamp.GetCurrentTime()
- *
- * # JSON Mapping
- *
- * In JSON format, the Timestamp type is encoded as a string in the
- * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
- * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
- * where {year} is always expressed using four digits while {month}, {day},
- * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
- * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
- * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
- * is required. A proto3 JSON serializer should always use UTC (as indicated by
- * "Z") when printing the Timestamp type and a proto3 JSON parser should be
- * able to accept both UTC and other timezones (as indicated by an offset).
- *
- * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
- * 01:30 UTC on January 15, 2017.
- *
- * In JavaScript, one can convert a Date object to this format using the
- * standard
- * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
- * method. In Python, a standard `datetime.datetime` object can be converted
- * to this format using
- * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
- * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
- * the Joda Time's [`ISODateTimeFormat.dateTime()`](
- * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
- * ) to obtain a formatter capable of generating timestamps in this format.
- **/
-@interface GPBTimestamp : GPBMessage
-
-/**
- * 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.
- **/
-@property(nonatomic, readwrite) int32_t nanos;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBTimestamp.pbobjc.h"
diff --git a/objectivec/google/protobuf/Type.pbobjc.h b/objectivec/google/protobuf/Type.pbobjc.h
index 5a54863..e14e7cd 100644
--- a/objectivec/google/protobuf/Type.pbobjc.h
+++ b/objectivec/google/protobuf/Type.pbobjc.h
@@ -1,444 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/type.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-@class GPBAny;
-@class GPBEnumValue;
-@class GPBField;
-@class GPBOption;
-@class GPBSourceContext;
-
-NS_ASSUME_NONNULL_BEGIN
-
-#pragma mark - Enum GPBSyntax
-
-/** 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.
- **/
- GPBSyntax_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /** Syntax `proto2`. */
- GPBSyntax_SyntaxProto2 = 0,
-
- /** 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.
- **/
-BOOL GPBSyntax_IsValidValue(int32_t value);
-
-#pragma mark - Enum GPBField_Kind
-
-/** 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.
- **/
- GPBField_Kind_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /** Field type unknown. */
- GPBField_Kind_TypeUnknown = 0,
-
- /** Field type double. */
- GPBField_Kind_TypeDouble = 1,
-
- /** Field type float. */
- GPBField_Kind_TypeFloat = 2,
-
- /** Field type int64. */
- GPBField_Kind_TypeInt64 = 3,
-
- /** Field type uint64. */
- GPBField_Kind_TypeUint64 = 4,
-
- /** Field type int32. */
- GPBField_Kind_TypeInt32 = 5,
-
- /** Field type fixed64. */
- GPBField_Kind_TypeFixed64 = 6,
-
- /** Field type fixed32. */
- GPBField_Kind_TypeFixed32 = 7,
-
- /** Field type bool. */
- GPBField_Kind_TypeBool = 8,
-
- /** Field type string. */
- GPBField_Kind_TypeString = 9,
-
- /** Field type group. Proto2 syntax only, and deprecated. */
- GPBField_Kind_TypeGroup = 10,
-
- /** Field type message. */
- GPBField_Kind_TypeMessage = 11,
-
- /** Field type bytes. */
- GPBField_Kind_TypeBytes = 12,
-
- /** Field type uint32. */
- GPBField_Kind_TypeUint32 = 13,
-
- /** Field type enum. */
- GPBField_Kind_TypeEnum = 14,
-
- /** Field type sfixed32. */
- GPBField_Kind_TypeSfixed32 = 15,
-
- /** Field type sfixed64. */
- GPBField_Kind_TypeSfixed64 = 16,
-
- /** Field type sint32. */
- GPBField_Kind_TypeSint32 = 17,
-
- /** 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.
- **/
-BOOL GPBField_Kind_IsValidValue(int32_t value);
-
-#pragma mark - Enum GPBField_Cardinality
-
-/** 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.
- **/
- GPBField_Cardinality_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /** For fields with unknown cardinality. */
- GPBField_Cardinality_CardinalityUnknown = 0,
-
- /** For optional fields. */
- GPBField_Cardinality_CardinalityOptional = 1,
-
- /** For required fields. Proto2 syntax only. */
- GPBField_Cardinality_CardinalityRequired = 2,
-
- /** 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.
- **/
-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.
- **/
-@interface GPBTypeRoot : GPBRootObject
-@end
-
-#pragma mark - GPBType
-
-typedef GPB_ENUM(GPBType_FieldNumber) {
- GPBType_FieldNumber_Name = 1,
- GPBType_FieldNumber_FieldsArray = 2,
- GPBType_FieldNumber_OneofsArray = 3,
- GPBType_FieldNumber_OptionsArray = 4,
- GPBType_FieldNumber_SourceContext = 5,
- GPBType_FieldNumber_Syntax = 6,
-};
-
-/**
- * A protocol buffer message type.
- **/
-@interface GPBType : GPBMessage
-
-/** The fully qualified message name. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger fieldsArray_Count;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger oneofsArray_Count;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-
-/** The source context. */
-@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext;
-/** Test to see if @c sourceContext has been set. */
-@property(nonatomic, readwrite) BOOL hasSourceContext;
-
-/** 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.
- **/
-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.
- **/
-void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value);
-
-#pragma mark - GPBField
-
-typedef GPB_ENUM(GPBField_FieldNumber) {
- GPBField_FieldNumber_Kind = 1,
- GPBField_FieldNumber_Cardinality = 2,
- GPBField_FieldNumber_Number = 3,
- GPBField_FieldNumber_Name = 4,
- GPBField_FieldNumber_TypeURL = 6,
- GPBField_FieldNumber_OneofIndex = 7,
- GPBField_FieldNumber_Packed = 8,
- GPBField_FieldNumber_OptionsArray = 9,
- GPBField_FieldNumber_JsonName = 10,
- GPBField_FieldNumber_DefaultValue = 11,
-};
-
-/**
- * A single field of a message type.
- **/
-@interface GPBField : GPBMessage
-
-/** The field type. */
-@property(nonatomic, readwrite) GPBField_Kind kind;
-
-/** The field cardinality. */
-@property(nonatomic, readwrite) GPBField_Cardinality cardinality;
-
-/** The field number. */
-@property(nonatomic, readwrite) int32_t number;
-
-/** 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"`.
- **/
-@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.
- **/
-@property(nonatomic, readwrite) int32_t oneofIndex;
-
-/** Whether to use alternative packed wire representation. */
-@property(nonatomic, readwrite) BOOL packed;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-
-/** 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. */
-@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.
- **/
-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.
- **/
-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.
- **/
-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.
- **/
-void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value);
-
-#pragma mark - GPBEnum
-
-typedef GPB_ENUM(GPBEnum_FieldNumber) {
- GPBEnum_FieldNumber_Name = 1,
- GPBEnum_FieldNumber_EnumvalueArray = 2,
- GPBEnum_FieldNumber_OptionsArray = 3,
- GPBEnum_FieldNumber_SourceContext = 4,
- GPBEnum_FieldNumber_Syntax = 5,
-};
-
-/**
- * Enum type definition.
- **/
-@interface GPBEnum : GPBMessage
-
-/** Enum type name. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger enumvalueArray_Count;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-
-/** The source context. */
-@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext;
-/** Test to see if @c sourceContext has been set. */
-@property(nonatomic, readwrite) BOOL hasSourceContext;
-
-/** 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.
- **/
-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.
- **/
-void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value);
-
-#pragma mark - GPBEnumValue
-
-typedef GPB_ENUM(GPBEnumValue_FieldNumber) {
- GPBEnumValue_FieldNumber_Name = 1,
- GPBEnumValue_FieldNumber_Number = 2,
- GPBEnumValue_FieldNumber_OptionsArray = 3,
-};
-
-/**
- * Enum value definition.
- **/
-@interface GPBEnumValue : GPBMessage
-
-/** Enum value name. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-
-/** Enum value number. */
-@property(nonatomic, readwrite) int32_t number;
-
-/** 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. */
-@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-
-@end
-
-#pragma mark - GPBOption
-
-typedef GPB_ENUM(GPBOption_FieldNumber) {
- GPBOption_FieldNumber_Name = 1,
- GPBOption_FieldNumber_Value = 2,
-};
-
-/**
- * A protocol buffer option, which can be attached to a message, field,
- * enumeration, etc.
- **/
-@interface GPBOption : GPBMessage
-
-/**
- * The option's name. For protobuf built-in options (options defined in
- * descriptor.proto), this is the short name. For example, `"map_entry"`.
- * For custom options, it should be the fully-qualified name. For example,
- * `"google.api.http"`.
- **/
-@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-
-/**
- * The option's value packed in an Any message. If the value is a primitive,
- * the corresponding wrapper type defined in google/protobuf/wrappers.proto
- * should be used. If the value is an enum, it should be stored as an int32
- * value using the google.protobuf.Int32Value type.
- **/
-@property(nonatomic, readwrite, strong, null_resettable) GPBAny *value;
-/** Test to see if @c value has been set. */
-@property(nonatomic, readwrite) BOOL hasValue;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBType.pbobjc.h"
diff --git a/objectivec/google/protobuf/Wrappers.pbobjc.h b/objectivec/google/protobuf/Wrappers.pbobjc.h
index a9d3646..8365afc 100644
--- a/objectivec/google/protobuf/Wrappers.pbobjc.h
+++ b/objectivec/google/protobuf/Wrappers.pbobjc.h
@@ -1,219 +1,2 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: google/protobuf/wrappers.proto
-
-// This CPP symbol can be defined to use imports that match up to the framework
-// imports needed when using CocoaPods.
-#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
- #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
-#endif
-
-#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
- #import <protobuf/GPBDescriptor.h>
- #import <protobuf/GPBMessage.h>
- #import <protobuf/GPBRootObject.h>
-#else
- #import "GPBDescriptor.h"
- #import "GPBMessage.h"
- #import "GPBRootObject.h"
-#endif
-
-#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)
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated-declarations"
-
-CF_EXTERN_C_BEGIN
-
-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.
- **/
-@interface GPBWrappersRoot : GPBRootObject
-@end
-
-#pragma mark - GPBDoubleValue
-
-typedef GPB_ENUM(GPBDoubleValue_FieldNumber) {
- GPBDoubleValue_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `double`.
- *
- * The JSON representation for `DoubleValue` is JSON number.
- **/
-@interface GPBDoubleValue : GPBMessage
-
-/** The double value. */
-@property(nonatomic, readwrite) double value;
-
-@end
-
-#pragma mark - GPBFloatValue
-
-typedef GPB_ENUM(GPBFloatValue_FieldNumber) {
- GPBFloatValue_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `float`.
- *
- * The JSON representation for `FloatValue` is JSON number.
- **/
-@interface GPBFloatValue : GPBMessage
-
-/** The float value. */
-@property(nonatomic, readwrite) float value;
-
-@end
-
-#pragma mark - GPBInt64Value
-
-typedef GPB_ENUM(GPBInt64Value_FieldNumber) {
- GPBInt64Value_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `int64`.
- *
- * The JSON representation for `Int64Value` is JSON string.
- **/
-@interface GPBInt64Value : GPBMessage
-
-/** The int64 value. */
-@property(nonatomic, readwrite) int64_t value;
-
-@end
-
-#pragma mark - GPBUInt64Value
-
-typedef GPB_ENUM(GPBUInt64Value_FieldNumber) {
- GPBUInt64Value_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `uint64`.
- *
- * The JSON representation for `UInt64Value` is JSON string.
- **/
-@interface GPBUInt64Value : GPBMessage
-
-/** The uint64 value. */
-@property(nonatomic, readwrite) uint64_t value;
-
-@end
-
-#pragma mark - GPBInt32Value
-
-typedef GPB_ENUM(GPBInt32Value_FieldNumber) {
- GPBInt32Value_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `int32`.
- *
- * The JSON representation for `Int32Value` is JSON number.
- **/
-@interface GPBInt32Value : GPBMessage
-
-/** The int32 value. */
-@property(nonatomic, readwrite) int32_t value;
-
-@end
-
-#pragma mark - GPBUInt32Value
-
-typedef GPB_ENUM(GPBUInt32Value_FieldNumber) {
- GPBUInt32Value_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `uint32`.
- *
- * The JSON representation for `UInt32Value` is JSON number.
- **/
-@interface GPBUInt32Value : GPBMessage
-
-/** The uint32 value. */
-@property(nonatomic, readwrite) uint32_t value;
-
-@end
-
-#pragma mark - GPBBoolValue
-
-typedef GPB_ENUM(GPBBoolValue_FieldNumber) {
- GPBBoolValue_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `bool`.
- *
- * The JSON representation for `BoolValue` is JSON `true` and `false`.
- **/
-@interface GPBBoolValue : GPBMessage
-
-/** The bool value. */
-@property(nonatomic, readwrite) BOOL value;
-
-@end
-
-#pragma mark - GPBStringValue
-
-typedef GPB_ENUM(GPBStringValue_FieldNumber) {
- GPBStringValue_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `string`.
- *
- * The JSON representation for `StringValue` is JSON string.
- **/
-@interface GPBStringValue : GPBMessage
-
-/** The string value. */
-@property(nonatomic, readwrite, copy, null_resettable) NSString *value;
-
-@end
-
-#pragma mark - GPBBytesValue
-
-typedef GPB_ENUM(GPBBytesValue_FieldNumber) {
- GPBBytesValue_FieldNumber_Value = 1,
-};
-
-/**
- * Wrapper message for `bytes`.
- *
- * The JSON representation for `BytesValue` is JSON string.
- **/
-@interface GPBBytesValue : GPBMessage
-
-/** The bytes value. */
-@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
-
-@end
-
-NS_ASSUME_NONNULL_END
-
-CF_EXTERN_C_END
-
-#pragma clang diagnostic pop
-
-// @@protoc_insertion_point(global_scope)
+// Moved to root of objectivec directory, shim to keep anyone's imports working.
+#import "GPBWrappers.pbobjc.h"
diff --git a/php/composer.json b/php/composer.json
index b47065b..b618ea1 100644
--- a/php/composer.json
+++ b/php/composer.json
@@ -23,6 +23,7 @@
}
},
"scripts": {
- "test": "(cd tests && rm -rf generated && mkdir -p generated && ../../src/protoc --php_out=generated -I../../src -I. proto/empty/echo.proto proto/test.proto proto/test_include.proto proto/test_no_namespace.proto proto/test_prefix.proto proto/test_php_namespace.proto proto/test_empty_php_namespace.proto proto/test_reserved_enum_lower.proto proto/test_reserved_enum_upper.proto proto/test_reserved_enum_value_lower.proto proto/test_reserved_enum_value_upper.proto proto/test_reserved_message_lower.proto proto/test_reserved_message_upper.proto proto/test_service.proto proto/test_service_namespace.proto proto/test_wrapper_type_setters.proto proto/test_descriptors.proto) && (cd ../src && ./protoc --php_out=../php/tests/generated -I../php/tests -I. ../php/tests/proto/test_import_descriptor_proto.proto) && vendor/bin/phpunit"
+ "test": "(cd tests && rm -rf generated && mkdir -p generated && ../../src/protoc --php_out=generated -I../../src -I. proto/empty/echo.proto proto/test.proto proto/test_include.proto proto/test_no_namespace.proto proto/test_prefix.proto proto/test_php_namespace.proto proto/test_empty_php_namespace.proto proto/test_reserved_enum_lower.proto proto/test_reserved_enum_upper.proto proto/test_reserved_enum_value_lower.proto proto/test_reserved_enum_value_upper.proto proto/test_reserved_message_lower.proto proto/test_reserved_message_upper.proto proto/test_service.proto proto/test_service_namespace.proto proto/test_wrapper_type_setters.proto proto/test_descriptors.proto) && (cd ../src && ./protoc --php_out=../php/tests/generated -I../php/tests -I. ../php/tests/proto/test_import_descriptor_proto.proto) && vendor/bin/phpunit",
+ "aggregate_metadata_test": "(cd tests && rm -rf generated && mkdir -p generated && ../../src/protoc --php_out=aggregate_metadata=foo#bar:generated -I../../src -I. proto/test.proto proto/test_include.proto && ../../src/protoc --php_out=generated -I../../src -I. proto/empty/echo.proto proto/test_no_namespace.proto proto/test_empty_php_namespace.proto proto/test_prefix.proto proto/test_php_namespace.proto proto/test_reserved_enum_lower.proto proto/test_reserved_enum_upper.proto proto/test_reserved_enum_value_lower.proto proto/test_reserved_enum_value_upper.proto proto/test_reserved_message_lower.proto proto/test_reserved_message_upper.proto proto/test_service.proto proto/test_service_namespace.proto proto/test_wrapper_type_setters.proto proto/test_descriptors.proto) && (cd ../src && ./protoc --php_out=aggregate_metadata=foo:../php/tests/generated -I../php/tests -I. ../php/tests/proto/test_import_descriptor_proto.proto) && vendor/bin/phpunit"
}
}
diff --git a/php/ext/google/protobuf/array.c b/php/ext/google/protobuf/array.c
index b52bdf6..5174f4a 100644
--- a/php/ext/google/protobuf/array.c
+++ b/php/ext/google/protobuf/array.c
@@ -73,7 +73,6 @@
uint size ZEND_FILE_LINE_DC);
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, CACHED_VALUE **table,
int *n TSRMLS_DC);
#if PHP_MAJOR_VERSION < 7
@@ -85,7 +84,7 @@
#endif
// -----------------------------------------------------------------------------
-// RepeatedField creation/desctruction
+// RepeatedField creation/destruction
// -----------------------------------------------------------------------------
zend_class_entry* repeated_field_type;
@@ -102,7 +101,7 @@
#endif
PHP_PROTO_OBJECT_FREE_END
-PHP_PROTO_OBJECT_DTOR_START(RepeatedField, repeated_field)
+PHP_PROTO_OBJECT_EMPTY_DTOR_START(RepeatedField, repeated_field)
PHP_PROTO_OBJECT_DTOR_END
// Define object create method.
@@ -484,14 +483,14 @@
}
// -----------------------------------------------------------------------------
-// RepeatedFieldIter creation/desctruction
+// RepeatedFieldIter creation/destruction
// -----------------------------------------------------------------------------
// Define object free method.
-PHP_PROTO_OBJECT_FREE_START(RepeatedFieldIter, repeated_field_iter)
+PHP_PROTO_OBJECT_EMPTY_FREE_START(RepeatedFieldIter, repeated_field_iter)
PHP_PROTO_OBJECT_FREE_END
-PHP_PROTO_OBJECT_DTOR_START(RepeatedFieldIter, repeated_field_iter)
+PHP_PROTO_OBJECT_EMPTY_DTOR_START(RepeatedFieldIter, repeated_field_iter)
PHP_PROTO_OBJECT_DTOR_END
// Define object create method.
@@ -519,7 +518,7 @@
RepeatedFieldIter *intern = UNBOX(RepeatedFieldIter, getThis());
RepeatedField *repeated_field = intern->repeated_field;
- long index;
+ long index = 0;
void *memory;
HashTable *table = PHP_PROTO_HASH_OF(repeated_field->array);
@@ -527,13 +526,13 @@
if (repeated_field->type == UPB_TYPE_MESSAGE) {
if (php_proto_zend_hash_index_find_zval(table, intern->position,
(void **)&memory) == FAILURE) {
- zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
+ zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
return;
}
} else {
if (php_proto_zend_hash_index_find_mem(table, intern->position,
(void **)&memory) == FAILURE) {
- zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
+ zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
return;
}
}
diff --git a/php/ext/google/protobuf/def.c b/php/ext/google/protobuf/def.c
index 7c575c3..5edcb03 100644
--- a/php/ext/google/protobuf/def.c
+++ b/php/ext/google/protobuf/def.c
@@ -69,31 +69,6 @@
}
}
-// 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");
-}
-
// -----------------------------------------------------------------------------
// GPBType
// -----------------------------------------------------------------------------
@@ -157,6 +132,7 @@
PHP_METHOD(Descriptor, getClass) {
Descriptor* desc = UNBOX(Descriptor, getThis());
DescriptorInternal* intern = desc->intern;
+ register_class(intern, false TSRMLS_CC);
#if PHP_MAJOR_VERSION < 7
const char* classname = intern->klass->name;
#else
@@ -682,29 +658,6 @@
static void descriptor_pool_free_c(DescriptorPool *pool TSRMLS_DC) {
}
-static void validate_enumdef(const upb_enumdef *enumdef) {
- // Verify that an entry exists with integer value 0. (This is the default
- // value.)
- 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'.");
- }
-}
-
-static void validate_msgdef(const upb_msgdef* msgdef) {
- // Verify that no required fields exist. proto3 does not support these.
- upb_msg_field_iter it;
- for (upb_msg_field_begin(&it, msgdef);
- !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* field = upb_msg_iter_field(&it);
- if (upb_fielddef_label(field) == UPB_LABEL_REQUIRED) {
- zend_error(E_ERROR, "Required fields are unsupported in proto3.");
- }
- }
-}
-
PHP_METHOD(DescriptorPool, getGeneratedPool) {
init_generated_pool_once(TSRMLS_C);
#if PHP_MAJOR_VERSION < 7
@@ -725,58 +678,6 @@
#endif
}
-static size_t classname_len_max(const char *fullname,
- const char *package,
- const char *php_namespace,
- const char *prefix) {
- size_t fullname_len = strlen(fullname);
- size_t package_len = 0;
- size_t prefix_len = 0;
- size_t namespace_len = 0;
- size_t length = fullname_len;
- int i, segment, classname_start = 0;
-
- if (package != NULL) {
- package_len = strlen(package);
- }
- if (prefix != NULL) {
- prefix_len = strlen(prefix);
- }
- if (php_namespace != NULL) {
- namespace_len = strlen(php_namespace);
- }
-
- // Process package
- if (package_len > 0) {
- segment = 1;
- for (i = 0; i < package_len; i++) {
- if (package[i] == '.') {
- segment++;
- }
- }
- // In case of reserved name in package.
- length += 3 * segment;
-
- classname_start = package_len + 1;
- }
-
- // Process class name
- segment = 1;
- for (i = classname_start; i < fullname_len; i++) {
- if (fullname[i] == '.') {
- segment++;
- }
- }
- if (prefix_len == 0) {
- length += 3 * segment;
- } else {
- length += prefix_len * segment;
- }
-
- // The additional 2, one is for preceding '.' and the other is for trailing 0.
- return length + namespace_len + 2;
-}
-
static bool is_reserved(const char *segment, int length) {
bool result;
char* lower = ALLOC_N(char, length + 1);
@@ -797,8 +698,6 @@
const char *prefix_given,
const char *package_name,
stringsink *classname) {
- size_t i;
-
if (prefix_given != NULL && strcmp(prefix_given, "") != 0) {
stringsink_string(classname, NULL, prefix_given,
strlen(prefix_given), NULL);
@@ -828,11 +727,13 @@
static void fill_namespace(const char *package, const char *php_namespace,
stringsink *classname) {
if (php_namespace != NULL) {
- stringsink_string(classname, NULL, php_namespace, strlen(php_namespace),
- NULL);
- stringsink_string(classname, NULL, "\\", 1, NULL);
+ if (strlen(php_namespace) != 0) {
+ stringsink_string(classname, NULL, php_namespace, strlen(php_namespace),
+ NULL);
+ stringsink_string(classname, NULL, "\\", 1, NULL);
+ }
} else if (package != NULL) {
- int i = 0, j, offset = 0;
+ int i = 0, j = 0;
size_t package_len = strlen(package);
while (i < package_len) {
j = i;
@@ -866,7 +767,7 @@
while (j < fullname_len && fullname[j] != '.') {
j++;
}
- if (use_nested_submsg || is_first_segment && j == fullname_len) {
+ if (use_nested_submsg || (is_first_segment && j == fullname_len)) {
fill_prefix(fullname + i, j - i, prefix, package, classname);
}
is_first_segment = false;
@@ -882,21 +783,29 @@
}
}
-static zend_class_entry *register_class(const upb_filedef *file,
- const char *fullname,
- PHP_PROTO_HASHTABLE_VALUE desc_php,
- bool use_nested_submsg,
- bool is_enum TSRMLS_DC) {
+static void fill_classname_for_desc(void *desc, bool is_enum) {
+ const upb_filedef *file;
+ const char *fullname;
+ bool use_nested_submsg;
+
+ if (is_enum) {
+ EnumDescriptorInternal* enumdesc = desc;
+ file = upb_enumdef_file(enumdesc->enumdef);
+ fullname = upb_enumdef_fullname(enumdesc->enumdef);
+ use_nested_submsg = enumdesc->use_nested_submsg;
+ } else {
+ DescriptorInternal* msgdesc = desc;
+ file = upb_msgdef_file(msgdesc->msgdef);
+ fullname = upb_msgdef_fullname(msgdesc->msgdef);
+ use_nested_submsg = msgdesc->use_nested_submsg;
+ }
+
// Prepend '.' to package name to make it absolute. In the 5 additional
// bytes allocated, one for '.', one for trailing 0, and 3 for 'GPB' if
// given message is google.protobuf.Empty.
const char *package = upb_filedef_package(file);
const char *php_namespace = upb_filedef_phpnamespace(file);
const char *prefix = upb_filedef_phpprefix(file);
- size_t classname_len =
- classname_len_max(fullname, package, php_namespace, prefix);
- char* after_package;
- zend_class_entry* ret;
stringsink namesink;
stringsink_init(&namesink);
@@ -904,28 +813,67 @@
fill_classname(fullname, package, prefix, &namesink, use_nested_submsg);
stringsink_string(&namesink, NULL, "\0", 1, NULL);
+ if (is_enum) {
+ EnumDescriptorInternal* enumdesc = desc;
+ enumdesc->classname = strdup(namesink.ptr);
+ } else {
+ DescriptorInternal* msgdesc = desc;
+ msgdesc->classname = strdup(namesink.ptr);
+ }
+
+ stringsink_uninit(&namesink);
+}
+
+void register_class(void *desc, bool is_enum TSRMLS_DC) {
+ const char *classname;
+ const char *fullname;
+ zend_class_entry* ret;
+
+ if (is_enum) {
+ EnumDescriptorInternal* enumdesc = desc;
+ if (enumdesc->klass) {
+ return;
+ }
+ classname = enumdesc->classname;
+ fullname = upb_enumdef_fullname(enumdesc->enumdef);
+ } else {
+ DescriptorInternal* msgdesc = desc;
+ if (msgdesc->klass) {
+ return;
+ }
+ if (!msgdesc->classname) {
+ return;
+ }
+ classname = msgdesc->classname;
+ fullname = upb_msgdef_fullname(msgdesc->msgdef);
+ }
+
PHP_PROTO_CE_DECLARE pce;
- if (php_proto_zend_lookup_class(namesink.ptr, namesink.len - 1, &pce) ==
+ if (php_proto_zend_lookup_class(classname, strlen(classname), &pce) ==
FAILURE) {
zend_error(
E_ERROR,
- "Generated message class %s hasn't been defined (%s, %s, %s, %s)",
- namesink.ptr, fullname, package, php_namespace, prefix);
- return NULL;
+ "Generated message class %s hasn't been defined (%s)",
+ classname, fullname);
+ return;
}
ret = PHP_PROTO_CE_UNREF(pce);
- add_ce_obj(ret, desc_php);
if (is_enum) {
- EnumDescriptor* desc = UNBOX_HASHTABLE_VALUE(EnumDescriptor, desc_php);
- add_ce_enumdesc(ret, desc->intern);
- add_proto_enumdesc(fullname, desc->intern);
+ EnumDescriptorInternal* enumdesc = desc;
+ add_ce_enumdesc(ret, desc);
+ enumdesc->klass = ret;
} else {
- Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, desc_php);
- add_ce_desc(ret, desc->intern);
- add_proto_desc(fullname, desc->intern);
+ DescriptorInternal* msgdesc = desc;
+ add_ce_desc(ret, desc);
+ msgdesc->klass = ret;
+ // Map entries don't have existing php class.
+ if (!upb_msgdef_mapentry(msgdesc->msgdef)) {
+ if (msgdesc->layout == NULL) {
+ MessageLayout* layout = create_layout(msgdesc->msgdef);
+ msgdesc->layout = layout;
+ }
+ }
}
- stringsink_uninit(&namesink);
- return ret;
}
bool depends_on_descriptor(const google_protobuf_FileDescriptorProto* file) {
@@ -943,74 +891,15 @@
return false;
}
-const upb_filedef *parse_and_add_descriptor(const char *data,
- PHP_PROTO_SIZE data_len,
- InternalDescriptorPoolImpl *pool,
- upb_arena *arena) {
- size_t n;
- google_protobuf_FileDescriptorSet *set;
- const google_protobuf_FileDescriptorProto* const* files;
- const upb_filedef* file;
- upb_status status;
-
- set = google_protobuf_FileDescriptorSet_parse(
- data, data_len, arena);
-
- if (!set) {
- zend_error(E_ERROR, "Failed to parse binary descriptor\n");
- return NULL;
- }
-
- files = google_protobuf_FileDescriptorSet_file(set, &n);
-
- if (n != 1) {
- zend_error(E_ERROR, "Serialized descriptors should have exactly one file");
- return NULL;
- }
-
- // Check whether file has already been added.
- upb_strview name = google_protobuf_FileDescriptorProto_name(files[0]);
- // TODO(teboring): Needs another look up method which takes data and length.
- file = upb_symtab_lookupfile2(pool->symtab, name.data, name.size);
- if (file != NULL) {
- return NULL;
- }
-
- // The PHP code generator currently special-cases descriptor.proto. It
- // doesn't add it as a dependency even if the proto file actually does
- // depend on it.
- if (depends_on_descriptor(files[0]) &&
- upb_symtab_lookupfile(pool->symtab, "google/protobuf/descriptor.proto") ==
- NULL) {
- if (!parse_and_add_descriptor((char *)descriptor_proto,
- descriptor_proto_len, pool, arena)) {
- return NULL;
- }
- }
-
- upb_status_clear(&status);
- file = upb_symtab_addfile(pool->symtab, files[0], &status);
- check_upb_status(&status, "Unable to load descriptor");
- return file;
-}
-
-void internal_add_generated_file(const char *data, PHP_PROTO_SIZE data_len,
- InternalDescriptorPoolImpl *pool,
- bool use_nested_submsg TSRMLS_DC) {
- int i;
- upb_arena *arena;
- const upb_filedef* file;
-
- arena = upb_arena_new();
- file = parse_and_add_descriptor(data, data_len, pool, arena);
- upb_arena_free(arena);
- if (!file) return;
-
+static void internal_add_single_generated_file(
+ const upb_filedef* file,
+ InternalDescriptorPoolImpl* pool,
+ bool use_nested_submsg TSRMLS_DC) {
+ size_t i;
// 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_msgcount(file); i++) {
const upb_msgdef *msgdef = upb_filedef_msg(file, i);
CREATE_HASHTABLE_VALUE(desc, desc_php, Descriptor, descriptor_type);
@@ -1019,6 +908,8 @@
desc->intern->pool = pool;
desc->intern->layout = NULL;
desc->intern->klass = NULL;
+ desc->intern->use_nested_submsg = use_nested_submsg;
+ desc->intern->classname = NULL;
add_def_obj(desc->intern->msgdef, desc_php);
add_msgdef_desc(desc->intern->msgdef, desc->intern);
@@ -1029,15 +920,9 @@
continue;
}
- desc->intern->klass =
- register_class(file, upb_msgdef_fullname(msgdef), desc_php,
- use_nested_submsg, false TSRMLS_CC);
-
- if (desc->intern->klass == NULL) {
- return;
- }
-
- build_class_from_descriptor(desc_php TSRMLS_CC);
+ fill_classname_for_desc(desc->intern, false);
+ add_class_desc(desc->intern->classname, desc->intern);
+ add_proto_desc(upb_msgdef_fullname(desc->intern->msgdef), desc->intern);
}
for (i = 0; i < upb_filedef_enumcount(file); i++) {
@@ -1046,25 +931,87 @@
desc->intern = SYS_MALLOC(EnumDescriptorInternal);
desc->intern->enumdef = enumdef;
desc->intern->klass = NULL;
+ desc->intern->use_nested_submsg = use_nested_submsg;
+ desc->intern->classname = NULL;
add_def_obj(desc->intern->enumdef, desc_php);
add_enumdef_enumdesc(desc->intern->enumdef, desc->intern);
- desc->intern->klass =
- register_class(file, upb_enumdef_fullname(enumdef), desc_php,
- use_nested_submsg, true TSRMLS_CC);
-
- if (desc->intern->klass == NULL) {
- return;
- }
+ fill_classname_for_desc(desc->intern, true);
+ add_class_enumdesc(desc->intern->classname, desc->intern);
}
}
+const bool parse_and_add_descriptor(const char *data,
+ PHP_PROTO_SIZE data_len,
+ InternalDescriptorPoolImpl *pool,
+ upb_arena *arena,
+ bool use_nested_submsg TSRMLS_DC) {
+ size_t i, n;
+ google_protobuf_FileDescriptorSet *set;
+ const google_protobuf_FileDescriptorProto* const* files;
+ const upb_filedef* file;
+ upb_status status;
+
+ set = google_protobuf_FileDescriptorSet_parse(
+ data, data_len, arena);
+
+ if (!set) {
+ zend_error(E_ERROR, "Failed to parse binary descriptor\n");
+ return false;
+ }
+
+ files = google_protobuf_FileDescriptorSet_file(set, &n);
+
+ for (i = 0; i < n; i++) {
+ // Check whether file has already been added.
+ upb_strview name = google_protobuf_FileDescriptorProto_name(files[i]);
+ // TODO(teboring): Needs another look up method which takes data and length.
+ file = upb_symtab_lookupfile2(pool->symtab, name.data, name.size);
+ if (file != NULL) {
+ continue;
+ }
+
+ // The PHP code generator currently special-cases descriptor.proto. It
+ // doesn't add it as a dependency even if the proto file actually does
+ // depend on it.
+ if (depends_on_descriptor(files[i]) &&
+ upb_symtab_lookupfile(
+ pool->symtab, "google/protobuf/descriptor.proto") ==
+ NULL) {
+ if (!parse_and_add_descriptor((char *)descriptor_proto,
+ descriptor_proto_len, pool, arena,
+ use_nested_submsg TSRMLS_CC)) {
+ return false;
+ }
+ }
+
+ upb_status_clear(&status);
+ file = upb_symtab_addfile(pool->symtab, files[i], &status);
+ check_upb_status(&status, "Unable to load descriptor");
+
+ internal_add_single_generated_file(file, pool, use_nested_submsg TSRMLS_CC);
+ }
+
+ return true;
+}
+
+void internal_add_generated_file(const char *data, PHP_PROTO_SIZE data_len,
+ InternalDescriptorPoolImpl *pool,
+ bool use_nested_submsg TSRMLS_DC) {
+ int i;
+ upb_arena *arena;
+
+ arena = upb_arena_new();
+ parse_and_add_descriptor(data, data_len, pool, arena,
+ use_nested_submsg TSRMLS_CC);
+ upb_arena_free(arena);
+ return;
+}
+
PHP_METHOD(InternalDescriptorPool, internalAddGeneratedFile) {
char *data = NULL;
PHP_PROTO_SIZE data_len;
- upb_filedef **files;
zend_bool use_nested_submsg = false;
- size_t i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b",
&data, &data_len, &use_nested_submsg) ==
@@ -1144,9 +1091,17 @@
RETURN_NULL();
}
- PHP_PROTO_HASHTABLE_VALUE desc_php = get_ce_obj(PHP_PROTO_CE_UNREF(pce));
+ zend_class_entry* ce = PHP_PROTO_CE_UNREF(pce);
+
+ PHP_PROTO_HASHTABLE_VALUE desc_php = get_ce_obj(ce);
if (desc_php == NULL) {
- EnumDescriptorInternal* intern = get_ce_enumdesc(PHP_PROTO_CE_UNREF(pce));
+#if PHP_MAJOR_VERSION < 7
+ EnumDescriptorInternal* intern = get_class_enumdesc(ce->name);
+#else
+ EnumDescriptorInternal* intern = get_class_enumdesc(ZSTR_VAL(ce->name));
+#endif
+ register_class(intern, true TSRMLS_CC);
+
if (intern == NULL) {
RETURN_NULL();
}
@@ -1164,7 +1119,7 @@
EnumDescriptor* desc = UNBOX_HASHTABLE_VALUE(EnumDescriptor, desc_php);
desc->intern = intern;
add_def_obj(intern->enumdef, desc_php);
- add_ce_obj(PHP_PROTO_CE_UNREF(pce), desc_php);
+ add_ce_obj(ce, desc_php);
}
zend_class_entry* instance_ce = HASHTABLE_VALUE_CE(desc_php);
diff --git a/php/ext/google/protobuf/encode_decode.c b/php/ext/google/protobuf/encode_decode.c
index 14808eb..8eaa5d2 100644
--- a/php/ext/google/protobuf/encode_decode.c
+++ b/php/ext/google/protobuf/encode_decode.c
@@ -334,25 +334,6 @@
#undef DEFINE_SINGULAR_HANDLER
#if PHP_MAJOR_VERSION < 7
-static void *empty_php_string(zval** value_ptr) {
- SEPARATE_ZVAL_IF_NOT_REF(value_ptr);
- if (Z_TYPE_PP(value_ptr) == IS_STRING &&
- !IS_INTERNED(Z_STRVAL_PP(value_ptr))) {
- FREE(Z_STRVAL_PP(value_ptr));
- }
- ZVAL_EMPTY_STRING(*value_ptr);
- return (void*)(*value_ptr);
-}
-#else
-static void *empty_php_string(zval* value_ptr) {
- if (Z_TYPE_P(value_ptr) == IS_STRING) {
- zend_string_release(Z_STR_P(value_ptr));
- }
- ZVAL_EMPTY_STRING(value_ptr);
- return value_ptr;
-}
-#endif
-#if PHP_MAJOR_VERSION < 7
static void new_php_string(zval** value_ptr, const char* str, size_t len) {
SEPARATE_ZVAL_IF_NOT_REF(value_ptr);
if (Z_TYPE_PP(value_ptr) == IS_STRING &&
@@ -429,6 +410,7 @@
const submsg_handlerdata_t *submsgdata = hd;
DescriptorInternal* subdesc = get_msgdef_desc(submsgdata->md);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
MessageHeader* submsg;
@@ -456,6 +438,7 @@
const submsg_handlerdata_t *submsgdata = hd;
DescriptorInternal* subdesc = get_msgdef_desc(submsgdata->md);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
MessageHeader* submsg;
wrapperfields_parseframe_t* frame =
@@ -487,6 +470,7 @@
const submsg_handlerdata_t* submsgdata = hd;
TSRMLS_FETCH();
DescriptorInternal* subdesc = get_msgdef_desc(submsgdata->md);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
zval* submsg_php;
MessageHeader* submsg;
@@ -520,6 +504,7 @@
const submsg_handlerdata_t* submsgdata = hd;
TSRMLS_FETCH();
DescriptorInternal* subdesc = get_msgdef_desc(submsgdata->md);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
zval* submsg_php;
MessageHeader* submsg;
@@ -554,6 +539,7 @@
const submsg_handlerdata_t* submsgdata = hd;
TSRMLS_FETCH();
DescriptorInternal* subdesc = get_msgdef_desc(submsgdata->md);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
zval* submsg_php;
MessageHeader* submsg;
@@ -641,6 +627,7 @@
}
case UPB_TYPE_MESSAGE: {
DescriptorInternal* subdesc = get_msgdef_desc(value_msg);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
MessageHeader* submsg;
#if PHP_MAJOR_VERSION < 7
@@ -824,7 +811,6 @@
static bool oneof##type##_handler(void* closure, const void* hd, \
ctype val) { \
const oneof_handlerdata_t* oneofdata = hd; \
- MessageHeader* msg = (MessageHeader*)closure; \
DEREF(message_data(closure), oneofdata->case_ofs, uint32_t) = \
oneofdata->oneof_case_num; \
DEREF(message_data(closure), oneofdata->ofs, ctype) = val; \
@@ -880,22 +866,6 @@
}
// Handlers for string/bytes in a oneof.
-static void *oneofbytes_handler(void *closure,
- const void *hd,
- size_t size_hint) {
- MessageHeader* msg = closure;
- const oneof_handlerdata_t *oneofdata = hd;
-
- oneof_cleanup(msg, oneofdata);
-
- DEREF(message_data(msg), oneofdata->case_ofs, uint32_t) =
- oneofdata->oneof_case_num;
- DEREF(message_data(msg), oneofdata->ofs, CACHED_VALUE*) =
- OBJ_PROP(&msg->std, oneofdata->property_ofs);
-
- return empty_php_string(DEREF(
- message_data(msg), oneofdata->ofs, CACHED_VALUE*));
-}
static bool oneofstr_end_handler(void *closure, const void *hd) {
stringfields_parseframe_t* frame = closure;
MessageHeader* msg = (MessageHeader*)frame->closure;
@@ -938,6 +908,7 @@
uint32_t oldcase = DEREF(message_data(msg), oneofdata->case_ofs, uint32_t);
TSRMLS_FETCH();
DescriptorInternal* subdesc = get_msgdef_desc(oneofdata->md);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
zval* submsg_php;
MessageHeader* submsg;
@@ -976,7 +947,7 @@
const submsg_handlerdata_t* submsgdata = hd;
TSRMLS_FETCH();
DescriptorInternal* subdesc = get_msgdef_desc(submsgdata->md);
- zend_class_entry* subklass = subdesc->klass;
+ register_class(subdesc, false TSRMLS_CC);
zval* submsg_php;
MessageHeader* submsg;
wrapperfields_parseframe_t* frame =
@@ -991,6 +962,12 @@
frame->submsg = submsg;
frame->is_msg = true;
} else {
+ if (Z_TYPE_P(CACHED_PTR_TO_ZVAL_PTR(cached)) == IS_NULL) {
+ // Needs to initiate the wrapper message
+ const upb_msgdef* msgdef = subdesc->msgdef;
+ const upb_fielddef* f = upb_msgdef_itof(msgdef, 1);
+ native_slot_get_default(upb_fielddef_type(f), cached TSRMLS_CC);
+ }
// In this case, wrapper message hasn't been created and value will be
// stored in cache directly.
frame->submsg = cached;
@@ -1007,7 +984,7 @@
uint32_t oldcase = DEREF(message_data(msg), oneofdata->case_ofs, uint32_t);
TSRMLS_FETCH();
DescriptorInternal* subdesc = get_msgdef_desc(oneofdata->md);
- zend_class_entry* subklass = subdesc->klass;
+ register_class(subdesc, false TSRMLS_CC);
wrapperfields_parseframe_t* frame =
(wrapperfields_parseframe_t*)malloc(sizeof(wrapperfields_parseframe_t));
CACHED_VALUE* cached = OBJ_PROP(&msg->std, oneofdata->property_ofs);
@@ -1015,6 +992,12 @@
if (oldcase != oneofdata->oneof_case_num) {
oneof_cleanup(msg, oneofdata);
+ if (Z_TYPE_P(CACHED_PTR_TO_ZVAL_PTR(cached)) == IS_NULL) {
+ // Needs to initiate the wrapper message
+ const upb_msgdef* msgdef = subdesc->msgdef;
+ const upb_fielddef* f = upb_msgdef_itof(msgdef, 1);
+ native_slot_get_default(upb_fielddef_type(f), cached TSRMLS_CC);
+ }
frame->submsg = cached;
frame->is_msg = false;
} else if (Z_TYPE_P(CACHED_PTR_TO_ZVAL_PTR(cached)) == IS_OBJECT) {
@@ -1347,6 +1330,7 @@
const upb_msgdef* msgdef = upb_handlers_msgdef(h);
TSRMLS_FETCH();
DescriptorInternal* desc = get_msgdef_desc(msgdef);
+ register_class(desc, false TSRMLS_CC);
upb_msg_field_iter i;
// If this is a mapentry message type, set up a special set of handlers and
@@ -1356,15 +1340,6 @@
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);
- }
-
-
// If this is a wrapper message type, set up a special set of handlers and
// bail out of the normal (user-defined) message type handling.
if (is_wrapper_msg(msgdef)) {
@@ -1635,6 +1610,7 @@
if (value_len > 0) {
DescriptorInternal* payload_desc = get_msgdef_desc(payload_type);
+ register_class(payload_desc, false TSRMLS_CC);
zend_class_entry* payload_klass = payload_desc->klass;
zval val;
upb_sink subsink;
@@ -1674,11 +1650,10 @@
upb_status status;
upb_sink subsink;
const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
- uint32_t offset = desc->layout->fields[upb_fielddef_index(f)].offset;
zval* array;
RepeatedField* intern;
HashTable *ht;
- int size, i;
+ int size;
upb_sink_startmsg(sink);
@@ -1708,7 +1683,6 @@
upb_status status;
upb_sink subsink;
const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
- uint32_t offset = desc->layout->fields[upb_fielddef_index(f)].offset;
zval* map;
Map* intern;
int size;
@@ -2233,8 +2207,6 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
upb_fielddef* f = upb_msg_iter_field(&it);
- uint32_t offset = desc->layout->fields[upb_fielddef_index(f)].offset;
- bool containing_oneof = false;
if (upb_fielddef_containingoneof(f)) {
uint32_t oneof_case_offset =
@@ -2247,12 +2219,11 @@
}
// Otherwise, fall through to the appropriate singular-field handler
// below.
- containing_oneof = true;
}
if (is_map_field(f)) {
MapIter map_it;
- int len, size;
+ int len;
const upb_fielddef* value_field;
value_field = map_field_value(f);
@@ -2261,7 +2232,6 @@
zval* map_php = CACHED_PTR_TO_ZVAL_PTR(find_zval_property(msg, f));
if (ZVAL_IS_NULL(map_php)) continue;
- Map* intern = UNBOX(Map, map_php);
for (map_begin(map_php, &map_it TSRMLS_CC);
!map_done(&map_it); map_next(&map_it)) {
upb_value value = map_iter_value(&map_it, &len);
diff --git a/php/ext/google/protobuf/map.c b/php/ext/google/protobuf/map.c
index 2764788..2dded92 100644
--- a/php/ext/google/protobuf/map.c
+++ b/php/ext/google/protobuf/map.c
@@ -153,7 +153,7 @@
zval *value TSRMLS_DC);
// -----------------------------------------------------------------------------
-// MapField creation/desctruction
+// MapField creation/destruction
// -----------------------------------------------------------------------------
zend_class_entry* map_field_type;
@@ -222,7 +222,7 @@
upb_strtable_uninit(&intern->table);
PHP_PROTO_OBJECT_FREE_END
-PHP_PROTO_OBJECT_DTOR_START(Map, map_field)
+PHP_PROTO_OBJECT_EMPTY_DTOR_START(Map, map_field)
PHP_PROTO_OBJECT_DTOR_END
// Define object create method.
@@ -383,7 +383,6 @@
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;
}
@@ -454,7 +453,7 @@
}
PHP_METHOD(MapField, offsetGet) {
- zval *index, *value;
+ zval *index;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) ==
FAILURE) {
return;
@@ -495,7 +494,6 @@
CREATE_OBJ_ON_ALLOCATED_ZVAL_PTR(return_value,
map_field_iter_type);
- Map *intern = UNBOX(Map, getThis());
MapIter *iter = UNBOX(MapIter, return_value);
map_begin(getThis(), iter TSRMLS_CC);
}
@@ -518,8 +516,8 @@
}
const char *map_iter_key(MapIter *iter, int *len) {
- *len = upb_strtable_iter_keylength(&iter->it);
- return upb_strtable_iter_key(&iter->it);
+ *len = upb_strtable_iter_key(&iter->it).size;
+ return upb_strtable_iter_key(&iter->it).data;
}
upb_value map_iter_value(MapIter *iter, int *len) {
@@ -540,14 +538,14 @@
};
// -----------------------------------------------------------------------------
-// MapFieldIter creation/desctruction
+// MapFieldIter creation/destruction
// -----------------------------------------------------------------------------
// Define object free method.
-PHP_PROTO_OBJECT_FREE_START(MapIter, map_field_iter)
+PHP_PROTO_OBJECT_EMPTY_FREE_START(MapIter, map_field_iter)
PHP_PROTO_OBJECT_FREE_END
-PHP_PROTO_OBJECT_DTOR_START(MapIter, map_field_iter)
+PHP_PROTO_OBJECT_EMPTY_DTOR_START(MapIter, map_field_iter)
PHP_PROTO_OBJECT_DTOR_END
// Define object create method.
diff --git a/php/ext/google/protobuf/message.c b/php/ext/google/protobuf/message.c
index e80ec4e..e8d4c6f 100644
--- a/php/ext/google/protobuf/message.c
+++ b/php/ext/google/protobuf/message.c
@@ -75,8 +75,13 @@
php_proto_zend_literal key TSRMLS_DC);
static HashTable* message_get_gc(zval* object, zval*** table, int* n TSRMLS_DC);
#else
+#if PHP_VERSION_ID < 70400
static void message_set_property(zval* object, zval* member, zval* value,
void** cache_slot);
+#else
+static zval* message_set_property(zval* object, zval* member, zval* value,
+ void** cache_slot);
+#endif
static zval* message_get_property(zval* object, zval* member, int type,
void** cache_slot, zval* rv);
static zval* message_get_property_ptr_ptr(zval* object, zval* member, int type,
@@ -100,14 +105,14 @@
}
PHP_PROTO_OBJECT_FREE_END
-PHP_PROTO_OBJECT_DTOR_START(MessageHeader, message)
+PHP_PROTO_OBJECT_EMPTY_DTOR_START(MessageHeader, message)
PHP_PROTO_OBJECT_DTOR_END
// Define object create method.
PHP_PROTO_OBJECT_CREATE_START(MessageHeader, message)
// Because php call this create func before calling the sub-message's
-// constructor defined in PHP, it's possible that the decriptor of this class
-// hasn't been added to descritpor pool (when the class is first
+// constructor defined in PHP, it's possible that the descriptor of this class
+// hasn't been added to descriptor pool (when the class is first
// instantiated). In that case, we will defer the initialization of the custom
// data to the parent Message's constructor, which will be called by
// sub-message's constructors after the descriptor has been added.
@@ -140,13 +145,20 @@
#if PHP_MAJOR_VERSION < 7
static void message_set_property(zval* object, zval* member, zval* value,
php_proto_zend_literal key TSRMLS_DC) {
-#else
+#elif PHP_VERSION_ID < 70400
static void message_set_property(zval* object, zval* member, zval* value,
void** cache_slot) {
+#else
+static zval* message_set_property(zval* object, zval* member, zval* value,
+ void** cache_slot) {
#endif
if (Z_TYPE_P(member) != IS_STRING) {
zend_error(E_USER_ERROR, "Unexpected type for field name");
+#if PHP_VERSION_ID < 70400
return;
+#else
+ return value;
+#endif
}
#if PHP_MAJOR_VERSION < 7 || (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0)
@@ -156,10 +168,17 @@
#endif
// User cannot set property directly (e.g., $m->a = 1)
zend_error(E_USER_ERROR, "Cannot access private property.");
+#if PHP_VERSION_ID < 70400
return;
+#else
+ return value;
+#endif
}
message_set_property_internal(object, member, value TSRMLS_CC);
+#if PHP_VERSION_ID >= 70400
+ return value;
+#endif
}
static zval* message_get_property_internal(zval* object,
@@ -274,25 +293,6 @@
Message_construct(getThis(), array_wrapper); \
}
-void build_class_from_descriptor(
- PHP_PROTO_HASHTABLE_VALUE php_descriptor TSRMLS_DC) {
- Descriptor* desc = UNBOX_HASHTABLE_VALUE(Descriptor, php_descriptor);
-
- // Map entries don't have existing php class.
- if (upb_msgdef_mapentry(desc->intern->msgdef)) {
- return;
- }
-
- zend_class_entry* registered_ce = desc->intern->klass;
-
- if (desc->intern->layout == NULL) {
- MessageLayout* layout = create_layout(desc->intern->msgdef);
- desc->intern->layout = layout;
- }
-
- registered_ce->create_object = message_create;
-}
-
// -----------------------------------------------------------------------------
// PHP Methods
// -----------------------------------------------------------------------------
@@ -346,11 +346,19 @@
TSRMLS_FETCH();
zend_class_entry* ce = Z_OBJCE_P(msg);
MessageHeader* intern = NULL;
- if (EXPECTED(class_added(ce))) {
- intern = UNBOX(MessageHeader, msg);
- custom_data_init(ce, intern PHP_PROTO_TSRMLS_CC);
+
+ if (!class_added(ce)) {
+#if PHP_MAJOR_VERSION < 7
+ DescriptorInternal* desc = get_class_desc(ce->name);
+#else
+ DescriptorInternal* desc = get_class_desc(ZSTR_VAL(ce->name));
+#endif
+ register_class(desc, false TSRMLS_CC);
}
+ intern = UNBOX(MessageHeader, msg);
+ custom_data_init(ce, intern PHP_PROTO_TSRMLS_CC);
+
if (array_wrapper == NULL) {
return;
}
@@ -391,11 +399,11 @@
if (upb_fielddef_issubmsg(value_field)) {
const upb_msgdef* submsgdef = upb_fielddef_msgsubdef(value_field);
- upb_wellknowntype_t type = upb_msgdef_wellknowntype(submsgdef);
is_wrapper = is_wrapper_msg(submsgdef);
if (is_wrapper) {
DescriptorInternal* subdesc = get_msgdef_desc(submsgdef);
+ register_class(subdesc, false TSRMLS_CC);
subklass = subdesc->klass;
}
}
@@ -430,11 +438,11 @@
if (upb_fielddef_issubmsg(field)) {
const upb_msgdef* submsgdef = upb_fielddef_msgsubdef(field);
- upb_wellknowntype_t type = upb_msgdef_wellknowntype(submsgdef);
is_wrapper = is_wrapper_msg(submsgdef);
if (is_wrapper) {
DescriptorInternal* subdesc = get_msgdef_desc(submsgdef);
+ register_class(subdesc, false TSRMLS_CC);
subklass = subdesc->klass;
}
}
@@ -458,6 +466,7 @@
} else if (upb_fielddef_issubmsg(field)) {
const upb_msgdef* submsgdef = upb_fielddef_msgsubdef(field);
DescriptorInternal* desc = get_msgdef_desc(submsgdef);
+ register_class(desc, false TSRMLS_CC);
CACHED_VALUE* cached = NULL;
if (upb_fielddef_containingoneof(field)) {
@@ -528,6 +537,7 @@
PHP_METHOD(Message, clear) {
MessageHeader* msg = UNBOX(MessageHeader, getThis());
DescriptorInternal* desc = msg->descriptor;
+ register_class(desc, false TSRMLS_CC);
zend_class_entry* ce = desc->klass;
zend_object_std_dtor(&msg->std TSRMLS_CC);
@@ -653,6 +663,9 @@
CASE_TYPE(BOOL, bool, int8_t)
#undef CASE_TYPE
+ case UPB_TYPE_MESSAGE:
+ zend_error(E_ERROR, "No wrapper for message.");
+ break;
}
}
@@ -673,7 +686,6 @@
const upb_msgdef* submsgdef = upb_fielddef_msgsubdef(field);
const upb_fielddef* value_field = upb_msgdef_itof(submsgdef, 1);
MessageHeader* submsg = UNBOX(MessageHeader, cached_zval);
- CACHED_VALUE* cached_value = find_zval_property(submsg, value_field);
layout_set(submsg->descriptor->layout, submsg,
value_field, value TSRMLS_CC);
} else {
@@ -1163,7 +1175,11 @@
zend_throw_exception_ex(
NULL, 0 TSRMLS_CC,
"Enum Google\\Protobuf\\Field_Cardinality has no name "
+#if PHP_MAJOR_VERSION < 7
"defined for value %d.",
+#else
+ "defined for value " ZEND_LONG_FMT ".",
+#endif
value);
}
}
@@ -1298,7 +1314,11 @@
default:
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Enum Google\\Protobuf\\Field_Kind has no name "
+#if PHP_MAJOR_VERSION < 7
"defined for value %d.",
+#else
+ "defined for value " ZEND_LONG_FMT ".",
+#endif
value);
}
}
@@ -1369,7 +1389,11 @@
default:
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Enum Google\\Protobuf\\NullValue has no name "
+#if PHP_MAJOR_VERSION < 7
"defined for value %d.",
+#else
+ "defined for value " ZEND_LONG_FMT ".",
+#endif
value);
}
}
@@ -1426,7 +1450,11 @@
default:
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Enum Google\\Protobuf\\Syntax has no name "
+#if PHP_MAJOR_VERSION < 7
"defined for value %d.",
+#else
+ "defined for value " ZEND_LONG_FMT ".",
+#endif
value);
}
}
@@ -1502,7 +1530,6 @@
PHP_METHOD(Any, __construct) {
init_file_any(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -1540,6 +1567,7 @@
0 TSRMLS_CC);
return;
}
+ register_class(desc, false TSRMLS_CC);
zend_class_entry* klass = desc->klass;
ZVAL_OBJ(return_value, klass->create_object(klass TSRMLS_CC));
MessageHeader* msg = UNBOX(MessageHeader, return_value);
@@ -1666,7 +1694,6 @@
PHP_METHOD(Duration, __construct) {
init_file_duration(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -1701,7 +1728,6 @@
PHP_METHOD(Timestamp, __construct) {
init_file_timestamp(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -1710,7 +1736,6 @@
PHP_METHOD(Timestamp, fromDateTime) {
zval* datetime;
- zval member;
PHP_PROTO_CE_DECLARE date_interface_ce;
if (php_proto_zend_lookup_class("\\DatetimeInterface", 18,
@@ -1903,7 +1928,6 @@
PHP_METHOD(Api, __construct) {
init_file_api(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -1937,7 +1961,6 @@
PHP_METHOD(BoolValue, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -1965,7 +1988,6 @@
PHP_METHOD(BytesValue, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -1993,7 +2015,6 @@
PHP_METHOD(DoubleValue, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2037,7 +2058,6 @@
PHP_METHOD(Enum, __construct) {
init_file_type(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2077,7 +2097,6 @@
PHP_METHOD(EnumValue, __construct) {
init_file_type(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2107,7 +2126,6 @@
PHP_METHOD(FieldMask, __construct) {
init_file_field_mask(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2172,7 +2190,6 @@
PHP_METHOD(Field, __construct) {
init_file_type(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2209,7 +2226,6 @@
PHP_METHOD(FloatValue, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2233,7 +2249,6 @@
PHP_METHOD(GPBEmpty, __construct) {
init_file_empty(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2260,7 +2275,6 @@
PHP_METHOD(Int32Value, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2288,7 +2302,6 @@
PHP_METHOD(Int64Value, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2316,7 +2329,6 @@
PHP_METHOD(ListValue, __construct) {
init_file_struct(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2372,7 +2384,6 @@
PHP_METHOD(Method, __construct) {
init_file_api(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2410,7 +2421,6 @@
PHP_METHOD(Mixin, __construct) {
init_file_api(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2443,7 +2453,6 @@
PHP_METHOD(Option, __construct) {
init_file_type(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2473,7 +2482,6 @@
PHP_METHOD(SourceContext, __construct) {
init_file_source_context(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2501,7 +2509,6 @@
PHP_METHOD(StringValue, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2529,7 +2536,6 @@
PHP_METHOD(Struct, __construct) {
init_file_struct(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2577,7 +2583,6 @@
PHP_METHOD(Type, __construct) {
init_file_type(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2610,7 +2615,6 @@
PHP_METHOD(UInt32Value, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2638,7 +2642,6 @@
PHP_METHOD(UInt64Value, __construct) {
init_file_wrappers(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
@@ -2677,7 +2680,6 @@
PHP_METHOD(Value, __construct) {
init_file_struct(TSRMLS_C);
- MessageHeader* intern = UNBOX(MessageHeader, getThis());
INIT_MESSAGE_WITH_ARRAY;
}
diff --git a/php/ext/google/protobuf/package.xml b/php/ext/google/protobuf/package.xml
index bee8b03..4b9066a 100644
--- a/php/ext/google/protobuf/package.xml
+++ b/php/ext/google/protobuf/package.xml
@@ -10,11 +10,11 @@
<email>protobuf-opensource@google.com</email>
<active>yes</active>
</lead>
- <date>2019-11-15</date>
- <time>11:44:18</time>
+ <date>2020-05-12</date>
+ <time>12:48:03</time>
<version>
- <release>3.11.0RC1</release>
- <api>3.11.0</api>
+ <release>3.12.0RC2</release>
+ <api>3.12.0</api>
</version>
<stability>
<release>beta</release>
@@ -445,5 +445,117 @@
<license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
<notes>GA release.</notes>
</release>
+ <release>
+ <version>
+ <release>3.11.0RC2</release>
+ <api>3.11.0</api>
+ </version>
+ <stability>
+ <release>beta</release>
+ <api>beta</api>
+ </stability>
+ <date>2019-11-21</date>
+ <time>10:38:49</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
+ <release>
+ <version>
+ <release>3.11.0</release>
+ <api>3.11.0</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2019-11-25</date>
+ <time>11:47:41</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
+ <release>
+ <version>
+ <release>3.11.1</release>
+ <api>3.11.1</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2019-12-02</date>
+ <time>11:09:17</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
+ <release>
+ <version>
+ <release>3.11.2</release>
+ <api>3.11.2</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2019-12-10</date>
+ <time>11:22:54</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
+ <release>
+ <version>
+ <release>3.11.3</release>
+ <api>3.11.3</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2020-01-28</date>
+ <time>10:20:43</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
+ <release>
+ <version>
+ <release>3.11.4</release>
+ <api>3.11.4</api>
+ </version>
+ <stability>
+ <release>stable</release>
+ <api>stable</api>
+ </stability>
+ <date>2020-02-12</date>
+ <time>12:46:57</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
+ <release>
+ <version>
+ <release>3.12.0RC1</release>
+ <api>3.12.0</api>
+ </version>
+ <stability>
+ <release>beta</release>
+ <api>beta</api>
+ </stability>
+ <date>2020-04-30</date>
+ <time>14:23:34</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
+ <release>
+ <version>
+ <release>3.12.0RC2</release>
+ <api>3.12.0</api>
+ </version>
+ <stability>
+ <release>beta</release>
+ <api>beta</api>
+ </stability>
+ <date>2020-05-12</date>
+ <time>12:48:03</time>
+ <license uri="https://opensource.org/licenses/BSD-3-Clause">3-Clause BSD License</license>
+ <notes>GA release.</notes>
+ </release>
</changelog>
</package>
diff --git a/php/ext/google/protobuf/protobuf.c b/php/ext/google/protobuf/protobuf.c
index fd97c89..e9ac935 100644
--- a/php/ext/google/protobuf/protobuf.c
+++ b/php/ext/google/protobuf/protobuf.c
@@ -39,6 +39,8 @@
static PHP_MINIT_FUNCTION(protobuf);
static PHP_MSHUTDOWN_FUNCTION(protobuf);
+ZEND_DECLARE_MODULE_GLOBALS(protobuf)
+
// Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
// instances.
static HashTable* upb_def_to_php_obj_map;
@@ -47,12 +49,12 @@
// Global map from message/enum's php class entry to corresponding wrapper
// Descriptor/EnumDescriptor instances.
static HashTable* ce_to_php_obj_map;
-static upb_inttable ce_to_desc_map_persistent;
-static upb_inttable ce_to_enumdesc_map_persistent;
+static upb_strtable ce_to_desc_map_persistent;
+static upb_strtable ce_to_enumdesc_map_persistent;
// Global map from message/enum's proto fully-qualified name to corresponding
// wrapper Descriptor/EnumDescriptor instances.
static upb_strtable proto_to_desc_map_persistent;
-static upb_strtable proto_to_enumdesc_map_persistent;
+static upb_strtable class_to_desc_map_persistent;
upb_strtable reserved_names;
@@ -61,8 +63,6 @@
// -----------------------------------------------------------------------------
static void add_to_table(HashTable* t, const void* def, void* value) {
- uint nIndex = (ulong)def & t->nTableMask;
-
zval* pDest = NULL;
php_proto_zend_hash_index_update_mem(t, (zend_ulong)def, &value,
sizeof(zval*), (void**)&pDest);
@@ -77,28 +77,6 @@
return *value;
}
-static bool exist_in_table(const HashTable* t, const void* def) {
- void** value;
- return (php_proto_zend_hash_index_find_mem(t, (zend_ulong)def,
- (void**)&value) == SUCCESS);
-}
-
-static void add_to_strtable(HashTable* t, const char* key, int key_size,
- void* value) {
- zval* pDest = NULL;
- php_proto_zend_hash_update_mem(t, key, key_size, &value, sizeof(void*),
- (void**)&pDest);
-}
-
-static void* get_from_strtable(const HashTable* t, const char* key, int key_size) {
- void** value;
- if (php_proto_zend_hash_find_mem(t, key, key_size, (void**)&value) ==
- FAILURE) {
- return NULL;
- }
- return *value;
-}
-
void add_def_obj(const void* def, PHP_PROTO_HASHTABLE_VALUE value) {
#if PHP_MAJOR_VERSION < 7
Z_ADDREF_P(value);
@@ -160,16 +138,28 @@
}
void add_ce_desc(const zend_class_entry* ce, DescriptorInternal* desc) {
- upb_inttable_insertptr(&ce_to_desc_map_persistent,
- ce, upb_value_ptr(desc));
+#if PHP_MAJOR_VERSION < 7
+ const char* klass = ce->name;
+#else
+ const char* klass = ZSTR_VAL(ce->name);
+#endif
+ upb_strtable_insert(&ce_to_desc_map_persistent, klass,
+ upb_value_ptr(desc));
}
DescriptorInternal* get_ce_desc(const zend_class_entry* ce) {
+#if PHP_MAJOR_VERSION < 7
+ const char* klass = ce->name;
+#else
+ const char* klass = ZSTR_VAL(ce->name);
+#endif
+
upb_value v;
#ifndef NDEBUG
v.ctype = UPB_CTYPE_PTR;
#endif
- if (!upb_inttable_lookupptr(&ce_to_desc_map_persistent, ce, &v)) {
+
+ if (!upb_strtable_lookup(&ce_to_desc_map_persistent, klass, &v)) {
return NULL;
} else {
return upb_value_getptr(v);
@@ -177,16 +167,26 @@
}
void add_ce_enumdesc(const zend_class_entry* ce, EnumDescriptorInternal* desc) {
- upb_inttable_insertptr(&ce_to_enumdesc_map_persistent,
- ce, upb_value_ptr(desc));
+#if PHP_MAJOR_VERSION < 7
+ const char* klass = ce->name;
+#else
+ const char* klass = ZSTR_VAL(ce->name);
+#endif
+ upb_strtable_insert(&ce_to_enumdesc_map_persistent, klass,
+ upb_value_ptr(desc));
}
EnumDescriptorInternal* get_ce_enumdesc(const zend_class_entry* ce) {
+#if PHP_MAJOR_VERSION < 7
+ const char* klass = ce->name;
+#else
+ const char* klass = ZSTR_VAL(ce->name);
+#endif
upb_value v;
#ifndef NDEBUG
v.ctype = UPB_CTYPE_PTR;
#endif
- if (!upb_inttable_lookupptr(&ce_to_enumdesc_map_persistent, ce, &v)) {
+ if (!upb_strtable_lookup(&ce_to_enumdesc_map_persistent, klass, &v)) {
return NULL;
} else {
return upb_value_getptr(v);
@@ -194,7 +194,7 @@
}
bool class_added(const void* ce) {
- return exist_in_table(ce_to_php_obj_map, ce);
+ return get_ce_desc(ce) != NULL;
}
void add_proto_desc(const char* proto, DescriptorInternal* desc) {
@@ -214,18 +214,34 @@
}
}
-void add_proto_enumdesc(const char* proto, EnumDescriptorInternal* desc) {
- upb_strtable_insert2(&proto_to_enumdesc_map_persistent, proto,
- strlen(proto), upb_value_ptr(desc));
+void add_class_desc(const char* klass, DescriptorInternal* desc) {
+ upb_strtable_insert(&class_to_desc_map_persistent, klass,
+ upb_value_ptr(desc));
}
-EnumDescriptorInternal* get_proto_enumdesc(const char* proto) {
+DescriptorInternal* get_class_desc(const char* klass) {
upb_value v;
#ifndef NDEBUG
v.ctype = UPB_CTYPE_PTR;
#endif
- if (!upb_strtable_lookupptr(&proto_to_enumdesc_map_persistent,
- proto, strlen(proto), &v)) {
+ if (!upb_strtable_lookup(&class_to_desc_map_persistent, klass, &v)) {
+ return NULL;
+ } else {
+ return upb_value_getptr(v);
+ }
+}
+
+void add_class_enumdesc(const char* klass, EnumDescriptorInternal* desc) {
+ upb_strtable_insert(&class_to_desc_map_persistent, klass,
+ upb_value_ptr(desc));
+}
+
+EnumDescriptorInternal* get_class_enumdesc(const char* klass) {
+ upb_value v;
+#ifndef NDEBUG
+ v.ctype = UPB_CTYPE_PTR;
+#endif
+ if (!upb_strtable_lookup(&class_to_desc_map_persistent, klass, &v)) {
return NULL;
} else {
return upb_value_getptr(v);
@@ -331,19 +347,15 @@
}
efree(ptr);
}
-
-static void test_release(void* value) {
- void* ptr = value;
-}
#endif
-static initialize_persistent_descriptor_pool(TSRMLS_D) {
+static void initialize_persistent_descriptor_pool(TSRMLS_D) {
upb_inttable_init(&upb_def_to_desc_map_persistent, UPB_CTYPE_PTR);
upb_inttable_init(&upb_def_to_enumdesc_map_persistent, UPB_CTYPE_PTR);
- upb_inttable_init(&ce_to_desc_map_persistent, UPB_CTYPE_PTR);
- upb_inttable_init(&ce_to_enumdesc_map_persistent, UPB_CTYPE_PTR);
+ upb_strtable_init(&ce_to_desc_map_persistent, UPB_CTYPE_PTR);
+ upb_strtable_init(&ce_to_enumdesc_map_persistent, UPB_CTYPE_PTR);
upb_strtable_init(&proto_to_desc_map_persistent, UPB_CTYPE_PTR);
- upb_strtable_init(&proto_to_enumdesc_map_persistent, UPB_CTYPE_PTR);
+ upb_strtable_init(&class_to_desc_map_persistent, UPB_CTYPE_PTR);
internal_descriptor_pool_impl_init(&generated_pool_impl TSRMLS_CC);
@@ -370,7 +382,29 @@
generated_pool_php = NULL;
internal_generated_pool_php = NULL;
- if (!PROTOBUF_G(keep_descriptor_pool_after_request)) {
+ if (PROTOBUF_G(keep_descriptor_pool_after_request)) {
+ // Needs to clean up obsolete class entry
+ upb_strtable_iter i;
+ upb_value v;
+
+ DescriptorInternal* desc;
+ for(upb_strtable_begin(&i, &ce_to_desc_map_persistent);
+ !upb_strtable_done(&i);
+ upb_strtable_next(&i)) {
+ v = upb_strtable_iter_value(&i);
+ desc = upb_value_getptr(v);
+ desc->klass = NULL;
+ }
+
+ EnumDescriptorInternal* enumdesc;
+ for(upb_strtable_begin(&i, &ce_to_enumdesc_map_persistent);
+ !upb_strtable_done(&i);
+ upb_strtable_next(&i)) {
+ v = upb_strtable_iter_value(&i);
+ enumdesc = upb_value_getptr(v);
+ enumdesc->klass = NULL;
+ }
+ } else {
initialize_persistent_descriptor_pool(TSRMLS_C);
}
@@ -388,7 +422,9 @@
desc = upb_value_getptr(v);
if (desc->layout) {
free_layout(desc->layout);
+ desc->layout = NULL;
}
+ free(desc->classname);
SYS_FREE(desc);
}
}
@@ -402,11 +438,12 @@
upb_inttable_next(&i)) {
v = upb_inttable_iter_value(&i);
desc = upb_value_getptr(v);
+ free(desc->classname);
SYS_FREE(desc);
}
}
-static cleanup_persistent_descriptor_pool(TSRMLS_D) {
+static void cleanup_persistent_descriptor_pool(TSRMLS_D) {
// Clean up
// Only needs to clean one map out of three (def=>desc, ce=>desc, proto=>desc)
@@ -417,10 +454,10 @@
upb_inttable_uninit(&upb_def_to_desc_map_persistent);
upb_inttable_uninit(&upb_def_to_enumdesc_map_persistent);
- upb_inttable_uninit(&ce_to_desc_map_persistent);
- upb_inttable_uninit(&ce_to_enumdesc_map_persistent);
+ upb_strtable_uninit(&ce_to_desc_map_persistent);
+ upb_strtable_uninit(&ce_to_enumdesc_map_persistent);
upb_strtable_uninit(&proto_to_desc_map_persistent);
- upb_strtable_uninit(&proto_to_enumdesc_map_persistent);
+ upb_strtable_uninit(&class_to_desc_map_persistent);
}
static PHP_RSHUTDOWN_FUNCTION(protobuf) {
@@ -461,10 +498,7 @@
static void reserved_names_init() {
size_t i;
- upb_value v;
-#ifndef NDEBUG
- v.ctype = UPB_CTYPE_UINT64;
-#endif
+ upb_value v = upb_value_bool(false);
for (i = 0; i < kReservedNamesSize; i++) {
upb_strtable_insert2(&reserved_names, kReservedNames[i],
strlen(kReservedNames[i]), v);
diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h
index 1fd90f2..bc293b8 100644
--- a/php/ext/google/protobuf/protobuf.h
+++ b/php/ext/google/protobuf/protobuf.h
@@ -37,7 +37,7 @@
#include "upb.h"
#define PHP_PROTOBUF_EXTNAME "protobuf"
-#define PHP_PROTOBUF_VERSION "3.11.0RC1"
+#define PHP_PROTOBUF_VERSION "3.12.0RC2"
#define MAX_LENGTH_OF_INT64 20
#define SIZEOF_INT64 8
@@ -143,7 +143,6 @@
#define PHP_PROTO_INIT_SUBMSGCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
void LOWWERNAME##_init(TSRMLS_D) { \
zend_class_entry class_type; \
- const char* class_name = CLASSNAME; \
INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
LOWWERNAME##_methods); \
LOWWERNAME##_type = zend_register_internal_class_ex( \
@@ -156,7 +155,6 @@
#define PHP_PROTO_INIT_ENUMCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
void LOWWERNAME##_init(TSRMLS_D) { \
zend_class_entry class_type; \
- const char* class_name = CLASSNAME; \
INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
LOWWERNAME##_methods); \
LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC);
@@ -166,7 +164,6 @@
#define PHP_PROTO_INIT_CLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
void LOWWERNAME##_init(TSRMLS_D) { \
zend_class_entry class_type; \
- const char* class_name = CLASSNAME; \
INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
LOWWERNAME##_methods); \
LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
@@ -187,6 +184,9 @@
PHP_PROTO_FREE_CLASS_OBJECT(NAME, LOWWERNAME##_free, LOWWERNAME##_handlers); \
}
+#define PHP_PROTO_OBJECT_EMPTY_FREE_START(classname, lowername) \
+ void lowername##_free(void* object TSRMLS_DC) { \
+ classname* intern = object;
#define PHP_PROTO_OBJECT_FREE_START(classname, lowername) \
void lowername##_free(void* object TSRMLS_DC) { \
classname* intern = object;
@@ -195,6 +195,7 @@
efree(intern); \
}
+#define PHP_PROTO_OBJECT_EMPTY_DTOR_START(classname, lowername)
#define PHP_PROTO_OBJECT_DTOR_START(classname, lowername)
#define PHP_PROTO_OBJECT_DTOR_END
@@ -291,7 +292,7 @@
#define PHP_PROTO_HASH_OF(array) Z_ARRVAL_P(&array)
-static inline int php_proto_zend_hash_index_update_zval(HashTable* ht, ulong h,
+static inline int php_proto_zend_hash_index_update_zval(HashTable* ht, zend_ulong h,
zval* pData) {
void* result = NULL;
result = zend_hash_index_update(ht, h, pData);
@@ -307,7 +308,7 @@
return result != NULL ? SUCCESS : FAILURE;
}
-static inline int php_proto_zend_hash_index_update_mem(HashTable* ht, ulong h,
+static inline int php_proto_zend_hash_index_update_mem(HashTable* ht, zend_ulong h,
void* pData, uint nDataSize,
void** pDest) {
void* result = NULL;
@@ -336,7 +337,7 @@
}
static inline int php_proto_zend_hash_index_find_zval(const HashTable* ht,
- ulong h, void** pDest) {
+ zend_ulong h, void** pDest) {
zval* result = zend_hash_index_find(ht, h);
if (pDest != NULL) *pDest = result;
return result != NULL ? SUCCESS : FAILURE;
@@ -350,7 +351,7 @@
}
static inline int php_proto_zend_hash_index_find_mem(const HashTable* ht,
- ulong h, void** pDest) {
+ zend_ulong h, void** pDest) {
void* result = NULL;
result = zend_hash_index_find_ptr(ht, h);
if (pDest != NULL) *pDest = result;
@@ -410,32 +411,28 @@
zend_object std; \
};
-#define PHP_PROTO_INIT_SUBMSGCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
- void LOWWERNAME##_init(TSRMLS_D) { \
- zend_class_entry class_type; \
- const char* class_name = CLASSNAME; \
- INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
- LOWWERNAME##_methods); \
- LOWWERNAME##_type = zend_register_internal_class_ex( \
- &class_type, message_type TSRMLS_CC); \
- zend_do_inheritance(LOWWERNAME##_type, message_type TSRMLS_CC);
+#define PHP_PROTO_INIT_SUBMSGCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
+ void LOWWERNAME##_init(TSRMLS_D) { \
+ zend_class_entry class_type; \
+ INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
+ LOWWERNAME##_methods); \
+ LOWWERNAME##_type = zend_register_internal_class(&class_type); \
+ zend_do_inheritance(LOWWERNAME##_type, message_type);
#define PHP_PROTO_INIT_SUBMSGCLASS_END \
}
#define PHP_PROTO_INIT_ENUMCLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
void LOWWERNAME##_init(TSRMLS_D) { \
zend_class_entry class_type; \
- const char* class_name = CLASSNAME; \
INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
LOWWERNAME##_methods); \
- LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC);
+ LOWWERNAME##_type = zend_register_internal_class(&class_type);
#define PHP_PROTO_INIT_ENUMCLASS_END \
}
#define PHP_PROTO_INIT_CLASS_START(CLASSNAME, CAMELNAME, LOWWERNAME) \
void LOWWERNAME##_init(TSRMLS_D) { \
zend_class_entry class_type; \
- const char* class_name = CLASSNAME; \
INIT_CLASS_ENTRY_EX(class_type, CLASSNAME, strlen(CLASSNAME), \
LOWWERNAME##_methods); \
LOWWERNAME##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
@@ -449,6 +446,8 @@
#define PHP_PROTO_INIT_CLASS_END \
}
+#define PHP_PROTO_OBJECT_EMPTY_FREE_START(classname, lowername) \
+ void lowername##_free(zend_object* object) {
#define PHP_PROTO_OBJECT_FREE_START(classname, lowername) \
void lowername##_free(zend_object* object) { \
classname* intern = \
@@ -456,6 +455,8 @@
#define PHP_PROTO_OBJECT_FREE_END \
}
+#define PHP_PROTO_OBJECT_EMPTY_DTOR_START(classname, lowername) \
+ void lowername##_dtor(zend_object* object) {
#define PHP_PROTO_OBJECT_DTOR_START(classname, lowername) \
void lowername##_dtor(zend_object* object) { \
classname* intern = \
@@ -569,8 +570,8 @@
LOWERNAME##_free_c(intern TSRMLS_CC); \
PHP_PROTO_OBJECT_FREE_END
-#define DEFINE_PROTOBUF_DTOR(CAMELNAME, LOWERNAME) \
- PHP_PROTO_OBJECT_DTOR_START(CAMELNAME, LOWERNAME) \
+#define DEFINE_PROTOBUF_DTOR(CAMELNAME, LOWERNAME) \
+ PHP_PROTO_OBJECT_EMPTY_DTOR_START(CAMELNAME, LOWERNAME) \
PHP_PROTO_OBJECT_DTOR_END
#define DEFINE_CLASS(NAME, LOWERNAME, string_name) \
@@ -689,7 +690,7 @@
zend_bool keep_descriptor_pool_after_request;
ZEND_END_MODULE_GLOBALS(protobuf)
-ZEND_DECLARE_MODULE_GLOBALS(protobuf)
+ZEND_EXTERN_MODULE_GLOBALS(protobuf)
#ifdef ZTS
#define PROTOBUF_G(v) TSRMG(protobuf_globals_id, zend_protobuf_globals *, v)
@@ -777,8 +778,10 @@
// wrapper Descriptor/EnumDescriptor instances.
void add_proto_desc(const char* proto, DescriptorInternal* desc);
DescriptorInternal* get_proto_desc(const char* proto);
-void add_proto_enumdesc(const char* proto, EnumDescriptorInternal* desc);
-EnumDescriptorInternal* get_proto_enumdesc(const char* proto);
+void add_class_desc(const char* klass, DescriptorInternal* desc);
+DescriptorInternal* get_class_desc(const char* klass);
+void add_class_enumdesc(const char* klass, EnumDescriptorInternal* desc);
+EnumDescriptorInternal* get_class_enumdesc(const char* klass);
extern zend_class_entry* map_field_type;
extern zend_class_entry* repeated_field_type;
@@ -817,6 +820,7 @@
bool use_nested_submsg TSRMLS_DC);
void init_generated_pool_once(TSRMLS_D);
void add_handlers_for_message(const void* closure, upb_handlers* h);
+void register_class(void *desc, bool is_enum TSRMLS_DC);
// wrapper of generated pool
#if PHP_MAJOR_VERSION < 7
@@ -844,6 +848,8 @@
const upb_msgdef* msgdef;
MessageLayout* layout;
zend_class_entry* klass; // begins as NULL
+ bool use_nested_submsg;
+ char* classname;
};
PHP_PROTO_WRAP_OBJECT_START(Descriptor)
@@ -878,6 +884,8 @@
struct EnumDescriptorInternal {
const upb_enumdef* enumdef;
zend_class_entry* klass; // begins as NULL
+ bool use_nested_submsg;
+ char* classname;
};
PHP_PROTO_WRAP_OBJECT_START(EnumDescriptor)
@@ -907,12 +915,6 @@
void custom_data_init(const zend_class_entry* ce,
MessageHeader* msg PHP_PROTO_TSRMLS_DC);
-// Build PHP class for given descriptor. Instead of building from scratch, this
-// function modifies existing class which has been partially defined in PHP
-// code.
-void build_class_from_descriptor(
- PHP_PROTO_HASHTABLE_VALUE php_descriptor TSRMLS_DC);
-
extern zend_class_entry* message_type;
extern zend_object_handlers* message_handlers;
diff --git a/php/ext/google/protobuf/storage.c b/php/ext/google/protobuf/storage.c
index 2521af5..fec7335 100644
--- a/php/ext/google/protobuf/storage.c
+++ b/php/ext/google/protobuf/storage.c
@@ -100,8 +100,10 @@
if (EXPECTED(cached_zval != NULL)) {
#if PHP_MAJOR_VERSION < 7
REPLACE_ZVAL_VALUE((zval**)memory, value, 1);
-#else
+#elif PHP_VERSION_ID < 70400
zend_assign_to_variable(cached_zval, value, IS_CV);
+#else
+ zend_assign_to_variable(cached_zval, value, IS_CV, 0);
#endif
}
break;
@@ -272,7 +274,6 @@
}
void native_slot_init(upb_fieldtype_t type, void* memory, CACHED_VALUE* cache) {
- zval* tmp = NULL;
switch (type) {
case UPB_TYPE_FLOAT:
DEREF(memory, float) = 0.0;
@@ -551,10 +552,12 @@
const upb_fielddef* field PHP_PROTO_TSRMLS_DC) {
if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
DescriptorInternal* desc = get_msgdef_desc(upb_fielddef_msgsubdef(field));
+ register_class(desc, false TSRMLS_CC);
return desc->klass;
} else if (upb_fielddef_type(field) == UPB_TYPE_ENUM) {
EnumDescriptorInternal* desc =
get_enumdef_enumdesc(upb_fielddef_enumsubdef(field));
+ register_class(desc, false TSRMLS_CC);
return desc->klass;
}
return NULL;
@@ -575,11 +578,6 @@
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;
-}
-
void* slot_memory(MessageLayout* layout, const void* storage,
const upb_fielddef* field) {
return ((uint8_t*)storage) + layout->fields[upb_fielddef_index(field)].offset;
@@ -600,6 +598,7 @@
TSRMLS_FETCH();
DescriptorInternal* desc = get_msgdef_desc(msgdef);
+ register_class(desc, false TSRMLS_CC);
layout->fields = SYS_MALLOC_N(MessageField, nfields);
for (upb_msg_field_begin(&it, msgdef); !upb_msg_field_done(&it);
@@ -822,6 +821,7 @@
const upb_fielddef* value_field = upb_msgdef_itof(submsgdef, 1);
MessageHeader* submsg;
DescriptorInternal* subdesc = get_msgdef_desc(submsgdef);
+ register_class(subdesc, false TSRMLS_CC);
zend_class_entry* subklass = subdesc->klass;
#if PHP_MAJOR_VERSION < 7
zval* val = NULL;
@@ -877,6 +877,7 @@
UPB_DESCRIPTOR_TYPE_MESSAGE) {
const upb_msgdef* submsg = upb_fielddef_msgsubdef(valuefield);
DescriptorInternal* subdesc = get_msgdef_desc(submsg);
+ register_class(subdesc, false TSRMLS_CC);
subce = subdesc->klass;
}
check_map_field(subce, upb_fielddef_descriptortype(keyfield),
@@ -886,6 +887,7 @@
if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
const upb_msgdef* submsg = upb_fielddef_msgsubdef(field);
DescriptorInternal* subdesc = get_msgdef_desc(submsg);
+ register_class(subdesc, false TSRMLS_CC);
subce = subdesc->klass;
}
@@ -908,6 +910,7 @@
if (type == UPB_TYPE_MESSAGE) {
const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
DescriptorInternal* desc = get_msgdef_desc(msg);
+ register_class(desc, false TSRMLS_CC);
ce = desc->klass;
}
CACHED_VALUE* cache = find_zval_property(header, field);
@@ -946,6 +949,7 @@
case UPB_TYPE_MESSAGE: {
const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
DescriptorInternal* desc = get_msgdef_desc(msg);
+ register_class(desc, false TSRMLS_CC);
ce = desc->klass;
if (native_slot_is_default(type, to_memory)) {
#if PHP_MAJOR_VERSION < 7
@@ -990,8 +994,8 @@
break;
}
case UPB_TYPE_MESSAGE: {
- const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
DescriptorInternal* desc = get_msgdef_desc(upb_fielddef_msgsubdef(field));
+ register_class(desc, false TSRMLS_CC);
zend_class_entry* ce = desc->klass;
#if PHP_MAJOR_VERSION < 7
MAKE_STD_ZVAL(DEREF(to_memory, zval*));
@@ -1159,7 +1163,7 @@
const char* layout_get_oneof_case(MessageLayout* layout, const void* storage,
const upb_oneofdef* oneof TSRMLS_DC) {
upb_oneof_iter i;
- const upb_fielddef* first_field;
+ const upb_fielddef* first_field = NULL;
// Oneof is guaranteed to have at least one field. Get the first field.
for(upb_oneof_begin(&i, oneof); !upb_oneof_done(&i); upb_oneof_next(&i)) {
diff --git a/php/ext/google/protobuf/type_check.c b/php/ext/google/protobuf/type_check.c
index af35b90..84d06be 100644
--- a/php/ext/google/protobuf/type_check.c
+++ b/php/ext/google/protobuf/type_check.c
@@ -407,8 +407,6 @@
*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;
@@ -496,7 +494,11 @@
if (!instanceof_function(Z_OBJCE_P(val), klass TSRMLS_CC)) {
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Given value is not an instance of %s.",
+#if PHP_MAJOR_VERSION < 7
klass->name);
+#else
+ ZSTR_VAL(klass->name));
+#endif
return;
}
RETURN_ZVAL(val, 1, 0);
@@ -541,7 +543,11 @@
if (!instanceof_function(Z_OBJCE_P(val), repeated_field_type TSRMLS_CC)) {
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Given value is not an instance of %s.",
+#if PHP_MAJOR_VERSION < 7
repeated_field_type->name);
+#else
+ ZSTR_VAL(repeated_field_type->name));
+#endif
return;
}
RepeatedField* intern = UNBOX(RepeatedField, val);
@@ -553,7 +559,12 @@
if (klass != NULL && intern->msg_ce != klass) {
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Expect a repeated field of %s, but %s is given.",
+#if PHP_MAJOR_VERSION < 7
klass->name, intern->msg_ce->name);
+#else
+ ZSTR_VAL(klass->name),
+ ZSTR_VAL(intern->msg_ce->name));
+#endif
return;
}
RETURN_ZVAL(val, 1, 0);
@@ -617,7 +628,11 @@
if (!instanceof_function(Z_OBJCE_P(val), map_field_type TSRMLS_CC)) {
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Given value is not an instance of %s.",
+#if PHP_MAJOR_VERSION < 7
map_field_type->name);
+#else
+ ZSTR_VAL(map_field_type->name));
+#endif
return;
}
Map* intern = UNBOX(Map, val);
@@ -636,7 +651,12 @@
if (klass != NULL && intern->msg_ce != klass) {
zend_throw_exception_ex(NULL, 0 TSRMLS_CC,
"Expect a map field of %s, but %s is given.",
+#if PHP_MAJOR_VERSION < 7
klass->name, intern->msg_ce->name);
+#else
+ ZSTR_VAL(klass->name),
+ ZSTR_VAL(intern->msg_ce->name));
+#endif
return;
}
RETURN_ZVAL(val, 1, 0);
diff --git a/php/ext/google/protobuf/upb.c b/php/ext/google/protobuf/upb.c
index e695447..cf27432 100644
--- a/php/ext/google/protobuf/upb.c
+++ b/php/ext/google/protobuf/upb.c
@@ -22,9 +22,8 @@
*
* This file is private and must not be included by users!
*/
-#ifndef UINTPTR_MAX
-#error must include stdint.h first
-#endif
+#include <stdint.h>
+#include <stddef.h>
#if UINTPTR_MAX == 0xffffffff
#define UPB_SIZE(size32, size64) size32
@@ -32,17 +31,21 @@
#define UPB_SIZE(size32, size64) size64
#endif
-#define UPB_FIELD_AT(msg, fieldtype, offset) \
- *(fieldtype*)((const char*)(msg) + offset)
+/* If we always read/write as a consistent type to each address, this shouldn't
+ * violate aliasing.
+ */
+#define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
#define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
- UPB_FIELD_AT(msg, int, case_offset) == case_val \
- ? UPB_FIELD_AT(msg, fieldtype, offset) \
+ *UPB_PTR_AT(msg, case_offset, int) == case_val \
+ ? *UPB_PTR_AT(msg, offset, fieldtype) \
: default
#define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
- UPB_FIELD_AT(msg, int, case_offset) = case_val; \
- UPB_FIELD_AT(msg, fieldtype, offset) = value;
+ *UPB_PTR_AT(msg, case_offset, int) = case_val; \
+ *UPB_PTR_AT(msg, offset, fieldtype) = value;
+
+#define UPB_MAPTYPE_STRING 0
/* UPB_INLINE: inline if possible, emit standalone code if required. */
#ifdef __cplusplus
@@ -53,6 +56,11 @@
#define UPB_INLINE static
#endif
+#define UPB_ALIGN_UP(size, align) (((size) + (align) - 1) / (align) * (align))
+#define UPB_ALIGN_DOWN(size, align) ((size) / (align) * (align))
+#define UPB_ALIGN_MALLOC(size) UPB_ALIGN_UP(size, 16)
+#define UPB_ALIGN_OF(type) offsetof (struct { char c; type member; }, member)
+
/* Hints to the compiler about likely/unlikely branches. */
#if defined (__GNUC__) || defined(__clang__)
#define UPB_LIKELY(x) __builtin_expect((x),1)
@@ -127,6 +135,18 @@
#define UPB_UNUSED(var) (void)var
+/* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
+ */
+#ifdef NDEBUG
+#ifdef __GNUC__
+#define UPB_ASSUME(expr) if (!(expr)) __builtin_unreachable()
+#else
+#define UPB_ASSUME(expr) do {} if (false && (expr))
+#endif
+#else
+#define UPB_ASSUME(expr) assert(expr)
+#endif
+
/* UPB_ASSERT(): in release mode, we use the expression without letting it be
* evaluated. This prevents "unused variable" warnings. */
#ifdef NDEBUG
@@ -153,607 +173,572 @@
#define UPB_INFINITY (1.0 / 0.0)
#endif
+#include <setjmp.h>
#include <string.h>
+
/* Maps descriptor type -> upb field type. */
-const uint8_t upb_desctype_to_fieldtype[] = {
- UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
- UPB_TYPE_DOUBLE, /* DOUBLE */
- UPB_TYPE_FLOAT, /* FLOAT */
- UPB_TYPE_INT64, /* INT64 */
- UPB_TYPE_UINT64, /* UINT64 */
- UPB_TYPE_INT32, /* INT32 */
- UPB_TYPE_UINT64, /* FIXED64 */
- UPB_TYPE_UINT32, /* FIXED32 */
- UPB_TYPE_BOOL, /* BOOL */
- UPB_TYPE_STRING, /* STRING */
- UPB_TYPE_MESSAGE, /* GROUP */
- UPB_TYPE_MESSAGE, /* MESSAGE */
- UPB_TYPE_BYTES, /* BYTES */
- UPB_TYPE_UINT32, /* UINT32 */
- UPB_TYPE_ENUM, /* ENUM */
- UPB_TYPE_INT32, /* SFIXED32 */
- UPB_TYPE_INT64, /* SFIXED64 */
- UPB_TYPE_INT32, /* SINT32 */
- UPB_TYPE_INT64, /* SINT64 */
+static const uint8_t desctype_to_fieldtype[] = {
+ -1, /* invalid descriptor type */
+ UPB_TYPE_DOUBLE, /* DOUBLE */
+ UPB_TYPE_FLOAT, /* FLOAT */
+ UPB_TYPE_INT64, /* INT64 */
+ UPB_TYPE_UINT64, /* UINT64 */
+ UPB_TYPE_INT32, /* INT32 */
+ UPB_TYPE_UINT64, /* FIXED64 */
+ UPB_TYPE_UINT32, /* FIXED32 */
+ UPB_TYPE_BOOL, /* BOOL */
+ UPB_TYPE_STRING, /* STRING */
+ UPB_TYPE_MESSAGE, /* GROUP */
+ UPB_TYPE_MESSAGE, /* MESSAGE */
+ UPB_TYPE_BYTES, /* BYTES */
+ UPB_TYPE_UINT32, /* UINT32 */
+ UPB_TYPE_ENUM, /* ENUM */
+ UPB_TYPE_INT32, /* SFIXED32 */
+ UPB_TYPE_INT64, /* SFIXED64 */
+ UPB_TYPE_INT32, /* SINT32 */
+ UPB_TYPE_INT64, /* SINT64 */
+};
+
+/* Maps descriptor type -> upb map size. */
+static const uint8_t desctype_to_mapsize[] = {
+ -1, /* invalid descriptor type */
+ 8, /* DOUBLE */
+ 4, /* FLOAT */
+ 8, /* INT64 */
+ 8, /* UINT64 */
+ 4, /* INT32 */
+ 8, /* FIXED64 */
+ 4, /* FIXED32 */
+ 1, /* BOOL */
+ UPB_MAPTYPE_STRING, /* STRING */
+ sizeof(void *), /* GROUP */
+ sizeof(void *), /* MESSAGE */
+ UPB_MAPTYPE_STRING, /* BYTES */
+ 4, /* UINT32 */
+ 4, /* ENUM */
+ 4, /* SFIXED32 */
+ 8, /* SFIXED64 */
+ 4, /* SINT32 */
+ 8, /* SINT64 */
+};
+
+static const unsigned fixed32_ok = (1 << UPB_DTYPE_FLOAT) |
+ (1 << UPB_DTYPE_FIXED32) |
+ (1 << UPB_DTYPE_SFIXED32);
+
+static const unsigned fixed64_ok = (1 << UPB_DTYPE_DOUBLE) |
+ (1 << UPB_DTYPE_FIXED64) |
+ (1 << UPB_DTYPE_SFIXED64);
+
+/* Op: an action to be performed for a wire-type/field-type combination. */
+#define OP_SCALAR_LG2(n) (n)
+#define OP_FIXPCK_LG2(n) (n + 4)
+#define OP_VARPCK_LG2(n) (n + 8)
+#define OP_STRING 4
+#define OP_SUBMSG 5
+
+static const int8_t varint_ops[19] = {
+ -1, /* field not found */
+ -1, /* DOUBLE */
+ -1, /* FLOAT */
+ OP_SCALAR_LG2(3), /* INT64 */
+ OP_SCALAR_LG2(3), /* UINT64 */
+ OP_SCALAR_LG2(2), /* INT32 */
+ -1, /* FIXED64 */
+ -1, /* FIXED32 */
+ OP_SCALAR_LG2(0), /* BOOL */
+ -1, /* STRING */
+ -1, /* GROUP */
+ -1, /* MESSAGE */
+ -1, /* BYTES */
+ OP_SCALAR_LG2(2), /* UINT32 */
+ OP_SCALAR_LG2(2), /* ENUM */
+ -1, /* SFIXED32 */
+ -1, /* SFIXED64 */
+ OP_SCALAR_LG2(2), /* SINT32 */
+ OP_SCALAR_LG2(3), /* SINT64 */
+};
+
+static const int8_t delim_ops[37] = {
+ /* For non-repeated field type. */
+ -1, /* field not found */
+ -1, /* DOUBLE */
+ -1, /* FLOAT */
+ -1, /* INT64 */
+ -1, /* UINT64 */
+ -1, /* INT32 */
+ -1, /* FIXED64 */
+ -1, /* FIXED32 */
+ -1, /* BOOL */
+ OP_STRING, /* STRING */
+ -1, /* GROUP */
+ OP_SUBMSG, /* MESSAGE */
+ OP_STRING, /* BYTES */
+ -1, /* UINT32 */
+ -1, /* ENUM */
+ -1, /* SFIXED32 */
+ -1, /* SFIXED64 */
+ -1, /* SINT32 */
+ -1, /* SINT64 */
+ /* For repeated field type. */
+ OP_FIXPCK_LG2(3), /* REPEATED DOUBLE */
+ OP_FIXPCK_LG2(2), /* REPEATED FLOAT */
+ OP_VARPCK_LG2(3), /* REPEATED INT64 */
+ OP_VARPCK_LG2(3), /* REPEATED UINT64 */
+ OP_VARPCK_LG2(2), /* REPEATED INT32 */
+ OP_FIXPCK_LG2(3), /* REPEATED FIXED64 */
+ OP_FIXPCK_LG2(2), /* REPEATED FIXED32 */
+ OP_VARPCK_LG2(0), /* REPEATED BOOL */
+ OP_STRING, /* REPEATED STRING */
+ OP_SUBMSG, /* REPEATED GROUP */
+ OP_SUBMSG, /* REPEATED MESSAGE */
+ OP_STRING, /* REPEATED BYTES */
+ OP_VARPCK_LG2(2), /* REPEATED UINT32 */
+ OP_VARPCK_LG2(2), /* REPEATED ENUM */
+ OP_FIXPCK_LG2(2), /* REPEATED SFIXED32 */
+ OP_FIXPCK_LG2(3), /* REPEATED SFIXED64 */
+ OP_VARPCK_LG2(2), /* REPEATED SINT32 */
+ OP_VARPCK_LG2(3), /* REPEATED SINT64 */
};
/* Data pertaining to the parse. */
typedef struct {
- const char *ptr; /* Current parsing position. */
- const char *field_start; /* Start of this field. */
- const char *limit; /* End of delimited region or end of buffer. */
+ const char *limit; /* End of delimited region or end of buffer. */
upb_arena *arena;
int depth;
- uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
+ uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
+ jmp_buf err;
} upb_decstate;
-/* Data passed by value to each parsing function. */
-typedef struct {
- char *msg;
- const upb_msglayout *layout;
- upb_decstate *state;
-} upb_decframe;
+typedef union {
+ bool bool_val;
+ int32_t int32_val;
+ int64_t int64_val;
+ uint32_t uint32_val;
+ uint64_t uint64_val;
+ upb_strview str_val;
+} wireval;
-#define CHK(x) if (!(x)) { return 0; }
+static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
+ const upb_msglayout *layout);
-static bool upb_skip_unknowngroup(upb_decstate *d, int field_number);
-static bool upb_decode_message(upb_decstate *d, char *msg,
- const upb_msglayout *l);
+UPB_NORETURN static void decode_err(upb_decstate *d) { longjmp(d->err, 1); }
-static bool upb_decode_varint(const char **ptr, const char *limit,
- uint64_t *val) {
+static bool decode_reserve(upb_decstate *d, upb_array *arr, int elem) {
+ bool need_realloc = arr->size - arr->len < elem;
+ if (need_realloc && !_upb_array_realloc(arr, arr->len + elem, d->arena)) {
+ decode_err(d);
+ }
+ return need_realloc;
+}
+
+UPB_NOINLINE
+static const char *decode_longvarint64(upb_decstate *d, const char *ptr,
+ const char *limit, uint64_t *val) {
uint8_t byte;
int bitpos = 0;
- const char *p = *ptr;
- *val = 0;
+ uint64_t out = 0;
do {
- CHK(bitpos < 70 && p < limit);
- byte = *p;
- *val |= (uint64_t)(byte & 0x7F) << bitpos;
- p++;
+ if (bitpos >= 70 || ptr == limit) decode_err(d);
+ byte = *ptr;
+ out |= (uint64_t)(byte & 0x7F) << bitpos;
+ ptr++;
bitpos += 7;
} while (byte & 0x80);
- *ptr = p;
- return true;
+ *val = out;
+ return ptr;
}
-static bool upb_decode_varint32(const char **ptr, const char *limit,
- uint32_t *val) {
+UPB_FORCEINLINE
+static const char *decode_varint64(upb_decstate *d, const char *ptr,
+ const char *limit, uint64_t *val) {
+ if (UPB_LIKELY(ptr < limit && (*ptr & 0x80) == 0)) {
+ *val = (uint8_t)*ptr;
+ return ptr + 1;
+ } else {
+ return decode_longvarint64(d, ptr, limit, val);
+ }
+}
+
+static const char *decode_varint32(upb_decstate *d, const char *ptr,
+ const char *limit, uint32_t *val) {
uint64_t u64;
- CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
+ ptr = decode_varint64(d, ptr, limit, &u64);
+ if (u64 > UINT32_MAX) decode_err(d);
*val = (uint32_t)u64;
- return true;
+ return ptr;
}
-static bool upb_decode_64bit(const char **ptr, const char *limit,
- uint64_t *val) {
- CHK(limit - *ptr >= 8);
- memcpy(val, *ptr, 8);
- *ptr += 8;
- return true;
-}
-
-static bool upb_decode_32bit(const char **ptr, const char *limit,
- uint32_t *val) {
- CHK(limit - *ptr >= 4);
- memcpy(val, *ptr, 4);
- *ptr += 4;
- return true;
-}
-
-static int32_t upb_zzdecode_32(uint32_t n) {
- return (n >> 1) ^ -(int32_t)(n & 1);
-}
-
-static int64_t upb_zzdecode_64(uint64_t n) {
- return (n >> 1) ^ -(int64_t)(n & 1);
-}
-
-static bool upb_decode_string(const char **ptr, const char *limit,
- int *outlen) {
- uint32_t len;
-
- CHK(upb_decode_varint32(ptr, limit, &len) &&
- len < INT32_MAX &&
- limit - *ptr >= (int32_t)len);
-
- *outlen = len;
- return true;
-}
-
-static void upb_set32(void *msg, size_t ofs, uint32_t val) {
- memcpy((char*)msg + ofs, &val, sizeof(val));
-}
-
-static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame) {
- upb_msg_addunknown(frame->msg, d->field_start, d->ptr - d->field_start,
- d->arena);
- return true;
-}
-
-
-static bool upb_skip_unknownfielddata(upb_decstate *d, uint32_t tag,
- uint32_t group_fieldnum) {
- switch (tag & 7) {
- case UPB_WIRE_TYPE_VARINT: {
- uint64_t val;
- return upb_decode_varint(&d->ptr, d->limit, &val);
- }
- case UPB_WIRE_TYPE_32BIT: {
- uint32_t val;
- return upb_decode_32bit(&d->ptr, d->limit, &val);
- }
- case UPB_WIRE_TYPE_64BIT: {
- uint64_t val;
- return upb_decode_64bit(&d->ptr, d->limit, &val);
- }
- case UPB_WIRE_TYPE_DELIMITED: {
- int len;
- CHK(upb_decode_string(&d->ptr, d->limit, &len));
- d->ptr += len;
- return true;
- }
- case UPB_WIRE_TYPE_START_GROUP:
- return upb_skip_unknowngroup(d, tag >> 3);
- case UPB_WIRE_TYPE_END_GROUP:
- return (tag >> 3) == group_fieldnum;
- }
- return false;
-}
-
-static bool upb_skip_unknowngroup(upb_decstate *d, int field_number) {
- while (d->ptr < d->limit && d->end_group == 0) {
- uint32_t tag = 0;
- CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
- CHK(upb_skip_unknownfielddata(d, tag, field_number));
- }
-
- CHK(d->end_group == field_number);
- d->end_group = 0;
- return true;
-}
-
-static bool upb_array_grow(upb_array *arr, size_t elements, size_t elem_size,
- upb_arena *arena) {
- size_t needed = arr->len + elements;
- size_t new_size = UPB_MAX(arr->size, 8);
- size_t new_bytes;
- size_t old_bytes;
- void *new_data;
- upb_alloc *alloc = upb_arena_alloc(arena);
-
- while (new_size < needed) {
- new_size *= 2;
- }
-
- old_bytes = arr->len * elem_size;
- new_bytes = new_size * elem_size;
- new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
- CHK(new_data);
-
- arr->data = new_data;
- arr->size = new_size;
- return true;
-}
-
-static void *upb_array_reserve(upb_array *arr, size_t elements,
- size_t elem_size, upb_arena *arena) {
- if (arr->size - arr->len < elements) {
- CHK(upb_array_grow(arr, elements, elem_size, arena));
- }
- return (char*)arr->data + (arr->len * elem_size);
-}
-
-bool upb_array_add(upb_array *arr, size_t elements, size_t elem_size,
- const void *data, upb_arena *arena) {
- void *dest = upb_array_reserve(arr, elements, elem_size, arena);
-
- CHK(dest);
- arr->len += elements;
- memcpy(dest, data, elements * elem_size);
-
- return true;
-}
-
-static upb_array *upb_getarr(upb_decframe *frame,
- const upb_msglayout_field *field) {
- UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
- return *(upb_array**)&frame->msg[field->offset];
-}
-
-static upb_array *upb_getorcreatearr(upb_decframe *frame,
- const upb_msglayout_field *field) {
- upb_array *arr = upb_getarr(frame, field);
-
- if (!arr) {
- arr = upb_array_new(frame->state->arena);
- CHK(arr);
- *(upb_array**)&frame->msg[field->offset] = arr;
- }
-
- return arr;
-}
-
-static upb_msg *upb_getorcreatemsg(upb_decframe *frame,
- const upb_msglayout_field *field,
- const upb_msglayout **subm) {
- upb_msg **submsg = (void*)(frame->msg + field->offset);
- *subm = frame->layout->submsgs[field->submsg_index];
-
- UPB_ASSERT(field->label != UPB_LABEL_REPEATED);
-
- if (!*submsg) {
- *submsg = upb_msg_new(*subm, frame->state->arena);
- CHK(*submsg);
- }
-
- return *submsg;
-}
-
-static upb_msg *upb_addmsg(upb_decframe *frame,
- const upb_msglayout_field *field,
- const upb_msglayout **subm) {
- upb_msg *submsg;
- upb_array *arr = upb_getorcreatearr(frame, field);
-
- *subm = frame->layout->submsgs[field->submsg_index];
- submsg = upb_msg_new(*subm, frame->state->arena);
- CHK(submsg);
- upb_array_add(arr, 1, sizeof(submsg), &submsg, frame->state->arena);
-
- return submsg;
-}
-
-static void upb_sethasbit(upb_decframe *frame,
- const upb_msglayout_field *field) {
- int32_t hasbit = field->presence;
- UPB_ASSERT(field->presence > 0);
- frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
-}
-
-static void upb_setoneofcase(upb_decframe *frame,
- const upb_msglayout_field *field) {
- UPB_ASSERT(field->presence < 0);
- upb_set32(frame->msg, ~field->presence, field->number);
-}
-
-static bool upb_decode_addval(upb_decframe *frame,
- const upb_msglayout_field *field, void *val,
- size_t size) {
- char *field_mem = frame->msg + field->offset;
- upb_array *arr;
-
- if (field->label == UPB_LABEL_REPEATED) {
- arr = upb_getorcreatearr(frame, field);
- CHK(arr);
- field_mem = upb_array_reserve(arr, 1, size, frame->state->arena);
- CHK(field_mem);
- }
-
- memcpy(field_mem, val, size);
- return true;
-}
-
-static void upb_decode_setpresent(upb_decframe *frame,
- const upb_msglayout_field *field) {
- if (field->label == UPB_LABEL_REPEATED) {
- upb_array *arr = upb_getarr(frame, field);
- UPB_ASSERT(arr->len < arr->size);
- arr->len++;
- } else if (field->presence < 0) {
- upb_setoneofcase(frame, field);
- } else if (field->presence > 0) {
- upb_sethasbit(frame, field);
- }
-}
-
-static bool upb_decode_msgfield(upb_decstate *d, upb_msg *msg,
- const upb_msglayout *layout, int limit) {
- const char* saved_limit = d->limit;
- d->limit = d->ptr + limit;
- CHK(--d->depth >= 0);
- upb_decode_message(d, msg, layout);
- d->depth++;
- d->limit = saved_limit;
- CHK(d->end_group == 0);
- return true;
-}
-
-static bool upb_decode_groupfield(upb_decstate *d, upb_msg *msg,
- const upb_msglayout *layout,
- int field_number) {
- CHK(--d->depth >= 0);
- upb_decode_message(d, msg, layout);
- d->depth++;
- CHK(d->end_group == field_number);
- d->end_group = 0;
- return true;
-}
-
-static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- uint64_t val;
- CHK(upb_decode_varint(&d->ptr, d->limit, &val));
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_INT64:
- case UPB_DESCRIPTOR_TYPE_UINT64:
- CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
+static void decode_munge(int type, wireval *val) {
+ switch (type) {
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ val->bool_val = val->uint64_val != 0;
break;
- case UPB_DESCRIPTOR_TYPE_INT32:
- case UPB_DESCRIPTOR_TYPE_UINT32:
- case UPB_DESCRIPTOR_TYPE_ENUM: {
- uint32_t val32 = (uint32_t)val;
- CHK(upb_decode_addval(frame, field, &val32, sizeof(val32)));
- break;
- }
- case UPB_DESCRIPTOR_TYPE_BOOL: {
- bool valbool = val != 0;
- CHK(upb_decode_addval(frame, field, &valbool, sizeof(valbool)));
- break;
- }
case UPB_DESCRIPTOR_TYPE_SINT32: {
- int32_t decoded = upb_zzdecode_32((uint32_t)val);
- CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
+ uint32_t n = val->uint32_val;
+ val->int32_val = (n >> 1) ^ -(int32_t)(n & 1);
break;
}
case UPB_DESCRIPTOR_TYPE_SINT64: {
- int64_t decoded = upb_zzdecode_64(val);
- CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
+ uint64_t n = val->uint64_val;
+ val->int64_val = (n >> 1) ^ -(int64_t)(n & 1);
break;
}
- default:
- return upb_append_unknown(d, frame);
- }
-
- upb_decode_setpresent(frame, field);
- return true;
-}
-
-static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- uint64_t val;
- CHK(upb_decode_64bit(&d->ptr, d->limit, &val));
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_DOUBLE:
- case UPB_DESCRIPTOR_TYPE_FIXED64:
- case UPB_DESCRIPTOR_TYPE_SFIXED64:
- CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
- break;
- default:
- return upb_append_unknown(d, frame);
- }
-
- upb_decode_setpresent(frame, field);
- return true;
-}
-
-static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- uint32_t val;
- CHK(upb_decode_32bit(&d->ptr, d->limit, &val));
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_FLOAT:
- case UPB_DESCRIPTOR_TYPE_FIXED32:
- case UPB_DESCRIPTOR_TYPE_SFIXED32:
- CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
- break;
- default:
- return upb_append_unknown(d, frame);
- }
-
- upb_decode_setpresent(frame, field);
- return true;
-}
-
-static bool upb_decode_fixedpacked(upb_decstate *d, upb_array *arr,
- uint32_t len, int elem_size) {
- size_t elements = len / elem_size;
-
- CHK((size_t)(elements * elem_size) == len);
- CHK(upb_array_add(arr, elements, elem_size, d->ptr, d->arena));
- d->ptr += len;
-
- return true;
-}
-
-static upb_strview upb_decode_strfield(upb_decstate *d, uint32_t len) {
- upb_strview ret;
- ret.data = d->ptr;
- ret.size = len;
- d->ptr += len;
- return ret;
-}
-
-static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field, int len) {
- upb_array *arr = upb_getorcreatearr(frame, field);
- CHK(arr);
-
-#define VARINT_CASE(ctype, decode) \
- VARINT_CASE_EX(ctype, decode, decode)
-
-#define VARINT_CASE_EX(ctype, decode, dtype) \
- { \
- const char *ptr = d->ptr; \
- const char *limit = ptr + len; \
- while (ptr < limit) { \
- uint64_t val; \
- ctype decoded; \
- CHK(upb_decode_varint(&ptr, limit, &val)); \
- decoded = (decode)((dtype)val); \
- CHK(upb_array_add(arr, 1, sizeof(decoded), &decoded, d->arena)); \
- } \
- d->ptr = ptr; \
- return true; \
- }
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_STRING:
- case UPB_DESCRIPTOR_TYPE_BYTES: {
- upb_strview str = upb_decode_strfield(d, len);
- return upb_array_add(arr, 1, sizeof(str), &str, d->arena);
- }
- case UPB_DESCRIPTOR_TYPE_FLOAT:
- case UPB_DESCRIPTOR_TYPE_FIXED32:
- case UPB_DESCRIPTOR_TYPE_SFIXED32:
- return upb_decode_fixedpacked(d, arr, len, sizeof(int32_t));
- case UPB_DESCRIPTOR_TYPE_DOUBLE:
- case UPB_DESCRIPTOR_TYPE_FIXED64:
- case UPB_DESCRIPTOR_TYPE_SFIXED64:
- return upb_decode_fixedpacked(d, arr, len, sizeof(int64_t));
- case UPB_DESCRIPTOR_TYPE_INT32:
- case UPB_DESCRIPTOR_TYPE_UINT32:
- case UPB_DESCRIPTOR_TYPE_ENUM:
- VARINT_CASE(uint32_t, uint32_t);
- case UPB_DESCRIPTOR_TYPE_INT64:
- case UPB_DESCRIPTOR_TYPE_UINT64:
- VARINT_CASE(uint64_t, uint64_t);
- case UPB_DESCRIPTOR_TYPE_BOOL:
- VARINT_CASE(bool, bool);
- case UPB_DESCRIPTOR_TYPE_SINT32:
- VARINT_CASE_EX(int32_t, upb_zzdecode_32, uint32_t);
- case UPB_DESCRIPTOR_TYPE_SINT64:
- VARINT_CASE_EX(int64_t, upb_zzdecode_64, uint64_t);
- case UPB_DESCRIPTOR_TYPE_MESSAGE: {
- const upb_msglayout *subm;
- upb_msg *submsg = upb_addmsg(frame, field, &subm);
- CHK(submsg);
- return upb_decode_msgfield(d, submsg, subm, len);
- }
- case UPB_DESCRIPTOR_TYPE_GROUP:
- return upb_append_unknown(d, frame);
- }
-#undef VARINT_CASE
- UPB_UNREACHABLE();
-}
-
-static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- int len;
-
- CHK(upb_decode_string(&d->ptr, d->limit, &len));
-
- if (field->label == UPB_LABEL_REPEATED) {
- return upb_decode_toarray(d, frame, field, len);
- } else {
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_STRING:
- case UPB_DESCRIPTOR_TYPE_BYTES: {
- upb_strview str = upb_decode_strfield(d, len);
- CHK(upb_decode_addval(frame, field, &str, sizeof(str)));
- break;
- }
- case UPB_DESCRIPTOR_TYPE_MESSAGE: {
- const upb_msglayout *subm;
- upb_msg *submsg = upb_getorcreatemsg(frame, field, &subm);
- CHK(submsg);
- CHK(upb_decode_msgfield(d, submsg, subm, len));
- break;
- }
- default:
- /* TODO(haberman): should we accept the last element of a packed? */
- d->ptr += len;
- return upb_append_unknown(d, frame);
- }
- upb_decode_setpresent(frame, field);
- return true;
}
}
static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
uint32_t field_number) {
+ static upb_msglayout_field none = {0};
+
/* Lots of optimization opportunities here. */
int i;
+ if (l == NULL) return &none;
for (i = 0; i < l->field_count; i++) {
if (l->fields[i].number == field_number) {
return &l->fields[i];
}
}
- return NULL; /* Unknown field. */
+ return &none; /* Unknown field. */
}
-static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
- uint32_t tag;
- const upb_msglayout_field *field;
- int field_number;
+static upb_msg *decode_newsubmsg(upb_decstate *d, const upb_msglayout *layout,
+ const upb_msglayout_field *field) {
+ const upb_msglayout *subl = layout->submsgs[field->submsg_index];
+ return _upb_msg_new(subl, d->arena);
+}
- d->field_start = d->ptr;
- CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
- field_number = tag >> 3;
- field = upb_find_field(frame->layout, field_number);
+static void decode_tosubmsg(upb_decstate *d, upb_msg *submsg,
+ const upb_msglayout *layout,
+ const upb_msglayout_field *field, upb_strview val) {
+ const upb_msglayout *subl = layout->submsgs[field->submsg_index];
+ const char *saved_limit = d->limit;
+ if (--d->depth < 0) decode_err(d);
+ d->limit = val.data + val.size;
+ decode_msg(d, val.data, submsg, subl);
+ d->limit = saved_limit;
+ if (d->end_group != 0) decode_err(d);
+ d->depth++;
+}
- if (field) {
- switch (tag & 7) {
- case UPB_WIRE_TYPE_VARINT:
- return upb_decode_varintfield(d, frame, field);
- case UPB_WIRE_TYPE_32BIT:
- return upb_decode_32bitfield(d, frame, field);
- case UPB_WIRE_TYPE_64BIT:
- return upb_decode_64bitfield(d, frame, field);
- case UPB_WIRE_TYPE_DELIMITED:
- return upb_decode_delimitedfield(d, frame, field);
- case UPB_WIRE_TYPE_START_GROUP: {
- const upb_msglayout *layout;
- upb_msg *group;
+static const char *decode_group(upb_decstate *d, const char *ptr,
+ upb_msg *submsg, const upb_msglayout *subl,
+ uint32_t number) {
+ if (--d->depth < 0) decode_err(d);
+ ptr = decode_msg(d, ptr, submsg, subl);
+ if (d->end_group != number) decode_err(d);
+ d->end_group = 0;
+ d->depth++;
+ return ptr;
+}
- if (field->label == UPB_LABEL_REPEATED) {
- group = upb_addmsg(frame, field, &layout);
- } else {
- group = upb_getorcreatemsg(frame, field, &layout);
- }
+static const char *decode_togroup(upb_decstate *d, const char *ptr,
+ upb_msg *submsg, const upb_msglayout *layout,
+ const upb_msglayout_field *field) {
+ const upb_msglayout *subl = layout->submsgs[field->submsg_index];
+ return decode_group(d, ptr, submsg, subl, field->number);
+}
- return upb_decode_groupfield(d, group, layout, field_number);
+static const char *decode_toarray(upb_decstate *d, const char *ptr,
+ upb_msg *msg, const upb_msglayout *layout,
+ const upb_msglayout_field *field, wireval val,
+ int op) {
+ upb_array **arrp = UPB_PTR_AT(msg, field->offset, void);
+ upb_array *arr = *arrp;
+ void *mem;
+
+ if (!arr) {
+ upb_fieldtype_t type = desctype_to_fieldtype[field->descriptortype];
+ arr = _upb_array_new(d->arena, type);
+ if (!arr) decode_err(d);
+ *arrp = arr;
+ }
+
+ decode_reserve(d, arr, 1);
+
+ switch (op) {
+ case OP_SCALAR_LG2(0):
+ case OP_SCALAR_LG2(2):
+ case OP_SCALAR_LG2(3):
+ /* Append scalar value. */
+ mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << op, void);
+ arr->len++;
+ memcpy(mem, &val, 1 << op);
+ return ptr;
+ case OP_STRING:
+ /* Append string. */
+ mem =
+ UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(upb_strview), void);
+ arr->len++;
+ memcpy(mem, &val, sizeof(upb_strview));
+ return ptr;
+ case OP_SUBMSG: {
+ /* Append submessage / group. */
+ upb_msg *submsg = decode_newsubmsg(d, layout, field);
+ *UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(void *), upb_msg *) =
+ submsg;
+ arr->len++;
+ if (UPB_UNLIKELY(field->descriptortype == UPB_DTYPE_GROUP)) {
+ ptr = decode_togroup(d, ptr, submsg, layout, field);
+ } else {
+ decode_tosubmsg(d, submsg, layout, field, val.str_val);
}
+ return ptr;
+ }
+ case OP_FIXPCK_LG2(2):
+ case OP_FIXPCK_LG2(3): {
+ /* Fixed packed. */
+ int lg2 = op - OP_FIXPCK_LG2(0);
+ int mask = (1 << lg2) - 1;
+ int count = val.str_val.size >> lg2;
+ if ((val.str_val.size & mask) != 0) {
+ decode_err(d); /* Length isn't a round multiple of elem size. */
+ }
+ decode_reserve(d, arr, count);
+ mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
+ arr->len += count;
+ memcpy(mem, val.str_val.data, val.str_val.size);
+ return ptr;
+ }
+ case OP_VARPCK_LG2(0):
+ case OP_VARPCK_LG2(2):
+ case OP_VARPCK_LG2(3): {
+ /* Varint packed. */
+ int lg2 = op - OP_VARPCK_LG2(0);
+ int scale = 1 << lg2;
+ const char *ptr = val.str_val.data;
+ const char *end = ptr + val.str_val.size;
+ char *out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
+ while (ptr < end) {
+ wireval elem;
+ ptr = decode_varint64(d, ptr, end, &elem.uint64_val);
+ decode_munge(field->descriptortype, &elem);
+ if (decode_reserve(d, arr, 1)) {
+ out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
+ }
+ arr->len++;
+ memcpy(out, &elem, scale);
+ out += scale;
+ }
+ if (ptr != end) decode_err(d);
+ return ptr;
+ }
+ default:
+ UPB_UNREACHABLE();
+ }
+}
+
+static void decode_tomap(upb_decstate *d, upb_msg *msg,
+ const upb_msglayout *layout,
+ const upb_msglayout_field *field, wireval val) {
+ upb_map **map_p = UPB_PTR_AT(msg, field->offset, upb_map *);
+ upb_map *map = *map_p;
+ upb_map_entry ent;
+ const upb_msglayout *entry = layout->submsgs[field->submsg_index];
+
+ if (!map) {
+ /* Lazily create map. */
+ const upb_msglayout *entry = layout->submsgs[field->submsg_index];
+ const upb_msglayout_field *key_field = &entry->fields[0];
+ const upb_msglayout_field *val_field = &entry->fields[1];
+ char key_size = desctype_to_mapsize[key_field->descriptortype];
+ char val_size = desctype_to_mapsize[val_field->descriptortype];
+ UPB_ASSERT(key_field->offset == 0);
+ UPB_ASSERT(val_field->offset == sizeof(upb_strview));
+ map = _upb_map_new(d->arena, key_size, val_size);
+ *map_p = map;
+ }
+
+ /* Parse map entry. */
+ memset(&ent, 0, sizeof(ent));
+
+ if (entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
+ entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_GROUP) {
+ /* Create proactively to handle the case where it doesn't appear. */
+ ent.v.val.val = (uint64_t)_upb_msg_new(entry->submsgs[0], d->arena);
+ }
+
+ decode_tosubmsg(d, &ent.k, layout, field, val.str_val);
+
+ /* Insert into map. */
+ _upb_map_set(map, &ent.k, map->key_size, &ent.v, map->val_size, d->arena);
+}
+
+static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
+ const upb_msglayout *layout,
+ const upb_msglayout_field *field, wireval val,
+ int op) {
+ void *mem = UPB_PTR_AT(msg, field->offset, void);
+ int type = field->descriptortype;
+
+ /* Set presence if necessary. */
+ if (field->presence < 0) {
+ /* Oneof case */
+ *UPB_PTR_AT(msg, -field->presence, int32_t) = field->number;
+ } else if (field->presence > 0) {
+ /* Hasbit */
+ uint32_t hasbit = field->presence;
+ *UPB_PTR_AT(msg, hasbit / 8, uint8_t) |= (1 << (hasbit % 8));
+ }
+
+ /* Store into message. */
+ switch (op) {
+ case OP_SUBMSG: {
+ upb_msg **submsgp = mem;
+ upb_msg *submsg = *submsgp;
+ if (!submsg) {
+ submsg = decode_newsubmsg(d, layout, field);
+ *submsgp = submsg;
+ }
+ if (UPB_UNLIKELY(type == UPB_DTYPE_GROUP)) {
+ ptr = decode_togroup(d, ptr, submsg, layout, field);
+ } else {
+ decode_tosubmsg(d, submsg, layout, field, val.str_val);
+ }
+ break;
+ }
+ case OP_STRING:
+ memcpy(mem, &val, sizeof(upb_strview));
+ break;
+ case OP_SCALAR_LG2(3):
+ memcpy(mem, &val, 8);
+ break;
+ case OP_SCALAR_LG2(2):
+ memcpy(mem, &val, 4);
+ break;
+ case OP_SCALAR_LG2(0):
+ memcpy(mem, &val, 1);
+ break;
+ default:
+ UPB_UNREACHABLE();
+ }
+
+ return ptr;
+}
+
+static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
+ const upb_msglayout *layout) {
+ while (ptr < d->limit) {
+ uint32_t tag;
+ const upb_msglayout_field *field;
+ int field_number;
+ int wire_type;
+ const char *field_start = ptr;
+ wireval val;
+ int op;
+
+ ptr = decode_varint32(d, ptr, d->limit, &tag);
+ field_number = tag >> 3;
+ wire_type = tag & 7;
+
+ field = upb_find_field(layout, field_number);
+
+ switch (wire_type) {
+ case UPB_WIRE_TYPE_VARINT:
+ ptr = decode_varint64(d, ptr, d->limit, &val.uint64_val);
+ op = varint_ops[field->descriptortype];
+ decode_munge(field->descriptortype, &val);
+ break;
+ case UPB_WIRE_TYPE_32BIT:
+ if (d->limit - ptr < 4) decode_err(d);
+ memcpy(&val, ptr, 4);
+ ptr += 4;
+ op = OP_SCALAR_LG2(2);
+ if (((1 << field->descriptortype) & fixed32_ok) == 0) goto unknown;
+ break;
+ case UPB_WIRE_TYPE_64BIT:
+ if (d->limit - ptr < 8) decode_err(d);
+ memcpy(&val, ptr, 8);
+ ptr += 8;
+ op = OP_SCALAR_LG2(3);
+ if (((1 << field->descriptortype) & fixed64_ok) == 0) goto unknown;
+ break;
+ case UPB_WIRE_TYPE_DELIMITED: {
+ uint32_t size;
+ int ndx = field->descriptortype;
+ if (_upb_isrepeated(field)) ndx += 18;
+ ptr = decode_varint32(d, ptr, d->limit, &size);
+ if (size >= INT32_MAX || (size_t)(d->limit - ptr) < size) {
+ decode_err(d); /* Length overflow. */
+ }
+ val.str_val.data = ptr;
+ val.str_val.size = size;
+ ptr += size;
+ op = delim_ops[ndx];
+ break;
+ }
+ case UPB_WIRE_TYPE_START_GROUP:
+ val.int32_val = field_number;
+ op = OP_SUBMSG;
+ if (field->descriptortype != UPB_DTYPE_GROUP) goto unknown;
+ break;
case UPB_WIRE_TYPE_END_GROUP:
d->end_group = field_number;
- return true;
+ return ptr;
default:
- CHK(false);
+ decode_err(d);
}
- } else {
- CHK(field_number != 0);
- CHK(upb_skip_unknownfielddata(d, tag, -1));
- CHK(upb_append_unknown(d, frame));
- return true;
- }
- UPB_UNREACHABLE();
-}
-static bool upb_decode_message(upb_decstate *d, char *msg, const upb_msglayout *l) {
- upb_decframe frame;
- frame.msg = msg;
- frame.layout = l;
- frame.state = d;
-
- while (d->ptr < d->limit) {
- CHK(upb_decode_field(d, &frame));
+ if (op >= 0) {
+ /* Parse, using op for dispatch. */
+ switch (field->label) {
+ case UPB_LABEL_REPEATED:
+ case _UPB_LABEL_PACKED:
+ ptr = decode_toarray(d, ptr, msg, layout, field, val, op);
+ break;
+ case _UPB_LABEL_MAP:
+ decode_tomap(d, msg, layout, field, val);
+ break;
+ default:
+ ptr = decode_tomsg(d, ptr, msg, layout, field, val, op);
+ break;
+ }
+ } else {
+ unknown:
+ /* Skip unknown field. */
+ if (field_number == 0) decode_err(d);
+ if (wire_type == UPB_WIRE_TYPE_START_GROUP) {
+ ptr = decode_group(d, ptr, NULL, NULL, field_number);
+ }
+ if (msg) {
+ if (!_upb_msg_addunknown(msg, field_start, ptr - field_start,
+ d->arena)) {
+ decode_err(d);
+ }
+ }
+ }
}
- return true;
+ if (ptr != d->limit) decode_err(d);
+ return ptr;
}
bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
upb_arena *arena) {
upb_decstate state;
- state.ptr = buf;
state.limit = buf + size;
state.arena = arena;
state.depth = 64;
state.end_group = 0;
- CHK(upb_decode_message(&state, msg, l));
+ if (setjmp(state.err)) return false;
+
+ if (size == 0) return true;
+ decode_msg(&state, buf, msg, l);
+
return state.end_group == 0;
}
-#undef CHK
+#undef OP_SCALAR_LG2
+#undef OP_FIXPCK_LG2
+#undef OP_VARPCK_LG2
+#undef OP_STRING
+#undef OP_SUBMSG
/* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
@@ -822,6 +807,7 @@
/* Writes the given bytes to the buffer, handling reserve/advance. */
static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
+ if (len == 0) return true;
CHK(upb_encode_reserve(e, len));
memcpy(e->ptr, data, len);
return true;
@@ -864,15 +850,14 @@
static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
uint32_t ret;
- uint32_t offset = ~f->presence;
- memcpy(&ret, msg + offset, sizeof(ret));
+ memcpy(&ret, msg - f->presence, sizeof(ret));
return ret;
}
static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
uint32_t hasbit = f->presence;
UPB_ASSERT(f->presence > 0);
- return msg[hasbit / 8] & (1 << (hasbit % 8));
+ return (*UPB_PTR_AT(msg, hasbit / 8, uint8_t)) & (1 << (hasbit % 8));
}
static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
@@ -880,116 +865,30 @@
}
static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
- size_t size) {
- size_t bytes = arr->len * size;
- return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
+ size_t elem_size, uint32_t tag) {
+ size_t bytes = arr->len * elem_size;
+ const char* data = _upb_array_constptr(arr);
+ const char* ptr = data + bytes - elem_size;
+ if (tag) {
+ while (true) {
+ CHK(upb_put_bytes(e, ptr, elem_size) && upb_put_varint(e, tag));
+ if (ptr == data) break;
+ ptr -= elem_size;
+ }
+ return true;
+ } else {
+ return upb_put_bytes(e, data, bytes) && upb_put_varint(e, bytes);
+ }
}
bool upb_encode_message(upb_encstate *e, const char *msg,
const upb_msglayout *m, size_t *size);
-static bool upb_encode_array(upb_encstate *e, const char *field_mem,
- const upb_msglayout *m,
- const upb_msglayout_field *f) {
- const upb_array *arr = *(const upb_array**)field_mem;
-
- if (arr == NULL || arr->len == 0) {
- return true;
- }
-
-#define VARINT_CASE(ctype, encode) { \
- ctype *start = arr->data; \
- ctype *ptr = start + arr->len; \
- size_t pre_len = e->limit - e->ptr; \
- do { \
- ptr--; \
- CHK(upb_put_varint(e, encode)); \
- } while (ptr != start); \
- CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
-} \
-break; \
-do { ; } while(0)
-
- switch (f->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_DOUBLE:
- CHK(upb_put_fixedarray(e, arr, sizeof(double)));
- break;
- case UPB_DESCRIPTOR_TYPE_FLOAT:
- CHK(upb_put_fixedarray(e, arr, sizeof(float)));
- break;
- case UPB_DESCRIPTOR_TYPE_SFIXED64:
- case UPB_DESCRIPTOR_TYPE_FIXED64:
- CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
- break;
- case UPB_DESCRIPTOR_TYPE_FIXED32:
- case UPB_DESCRIPTOR_TYPE_SFIXED32:
- CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
- break;
- case UPB_DESCRIPTOR_TYPE_INT64:
- case UPB_DESCRIPTOR_TYPE_UINT64:
- VARINT_CASE(uint64_t, *ptr);
- case UPB_DESCRIPTOR_TYPE_UINT32:
- VARINT_CASE(uint32_t, *ptr);
- case UPB_DESCRIPTOR_TYPE_INT32:
- case UPB_DESCRIPTOR_TYPE_ENUM:
- VARINT_CASE(int32_t, (int64_t)*ptr);
- case UPB_DESCRIPTOR_TYPE_BOOL:
- VARINT_CASE(bool, *ptr);
- case UPB_DESCRIPTOR_TYPE_SINT32:
- VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
- case UPB_DESCRIPTOR_TYPE_SINT64:
- VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
- case UPB_DESCRIPTOR_TYPE_STRING:
- case UPB_DESCRIPTOR_TYPE_BYTES: {
- upb_strview *start = arr->data;
- upb_strview *ptr = start + arr->len;
- do {
- ptr--;
- CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
- upb_put_varint(e, ptr->size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- } while (ptr != start);
- return true;
- }
- case UPB_DESCRIPTOR_TYPE_GROUP: {
- void **start = arr->data;
- void **ptr = start + arr->len;
- const upb_msglayout *subm = m->submsgs[f->submsg_index];
- do {
- size_t size;
- ptr--;
- CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
- upb_encode_message(e, *ptr, subm, &size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
- } while (ptr != start);
- return true;
- }
- case UPB_DESCRIPTOR_TYPE_MESSAGE: {
- void **start = arr->data;
- void **ptr = start + arr->len;
- const upb_msglayout *subm = m->submsgs[f->submsg_index];
- do {
- size_t size;
- ptr--;
- CHK(upb_encode_message(e, *ptr, subm, &size) &&
- upb_put_varint(e, size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- } while (ptr != start);
- return true;
- }
- }
-#undef VARINT_CASE
-
- /* We encode all primitive arrays as packed, regardless of what was specified
- * in the .proto file. Could special case 1-sized arrays. */
- CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- return true;
-}
-
-static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
+static bool upb_encode_scalarfield(upb_encstate *e, const void *_field_mem,
const upb_msglayout *m,
const upb_msglayout_field *f,
bool skip_zero_value) {
+ const char *field_mem = _field_mem;
#define CASE(ctype, type, wire_type, encodeval) do { \
ctype val = *(ctype*)field_mem; \
if (skip_zero_value && val == 0) { \
@@ -1061,6 +960,146 @@
UPB_UNREACHABLE();
}
+static bool upb_encode_array(upb_encstate *e, const char *field_mem,
+ const upb_msglayout *m,
+ const upb_msglayout_field *f) {
+ const upb_array *arr = *(const upb_array**)field_mem;
+ bool packed = f->label == _UPB_LABEL_PACKED;
+
+ if (arr == NULL || arr->len == 0) {
+ return true;
+ }
+
+#define VARINT_CASE(ctype, encode) \
+ { \
+ const ctype *start = _upb_array_constptr(arr); \
+ const ctype *ptr = start + arr->len; \
+ size_t pre_len = e->limit - e->ptr; \
+ uint32_t tag = packed ? 0 : (f->number << 3) | UPB_WIRE_TYPE_VARINT; \
+ do { \
+ ptr--; \
+ CHK(upb_put_varint(e, encode)); \
+ if (tag) CHK(upb_put_varint(e, tag)); \
+ } while (ptr != start); \
+ if (!tag) CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
+ } \
+ break; \
+ do { \
+ ; \
+ } while (0)
+
+#define TAG(wire_type) (packed ? 0 : (f->number << 3 | wire_type))
+
+ switch (f->descriptortype) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ CHK(upb_put_fixedarray(e, arr, sizeof(double), TAG(UPB_WIRE_TYPE_64BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ CHK(upb_put_fixedarray(e, arr, sizeof(float), TAG(UPB_WIRE_TYPE_32BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t), TAG(UPB_WIRE_TYPE_64BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t), TAG(UPB_WIRE_TYPE_32BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ VARINT_CASE(uint64_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ VARINT_CASE(uint32_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ VARINT_CASE(int32_t, (int64_t)*ptr);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ VARINT_CASE(bool, *ptr);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ const upb_strview *start = _upb_array_constptr(arr);
+ const upb_strview *ptr = start + arr->len;
+ do {
+ ptr--;
+ CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
+ upb_put_varint(e, ptr->size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_GROUP: {
+ const void *const*start = _upb_array_constptr(arr);
+ const void *const*ptr = start + arr->len;
+ const upb_msglayout *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
+ upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ const void *const*start = _upb_array_constptr(arr);
+ const void *const*ptr = start + arr->len;
+ const upb_msglayout *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_varint(e, size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ }
+#undef VARINT_CASE
+
+ if (packed) {
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ }
+ return true;
+}
+
+static bool upb_encode_map(upb_encstate *e, const char *field_mem,
+ const upb_msglayout *m,
+ const upb_msglayout_field *f) {
+ const upb_map *map = *(const upb_map**)field_mem;
+ const upb_msglayout *entry = m->submsgs[f->submsg_index];
+ const upb_msglayout_field *key_field = &entry->fields[0];
+ const upb_msglayout_field *val_field = &entry->fields[1];
+ upb_strtable_iter i;
+ if (map == NULL) {
+ return true;
+ }
+
+ upb_strtable_begin(&i, &map->table);
+ for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ size_t pre_len = e->limit - e->ptr;
+ size_t size;
+ upb_strview key = upb_strtable_iter_key(&i);
+ const upb_value val = upb_strtable_iter_value(&i);
+ const void *keyp =
+ map->key_size == UPB_MAPTYPE_STRING ? (void *)&key : key.data;
+ const void *valp =
+ map->val_size == UPB_MAPTYPE_STRING ? upb_value_getptr(val) : &val;
+
+ CHK(upb_encode_scalarfield(e, valp, entry, val_field, false));
+ CHK(upb_encode_scalarfield(e, keyp, entry, key_field, false));
+ size = (e->limit - e->ptr) - pre_len;
+ CHK(upb_put_varint(e, size));
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ }
+
+ return true;
+}
+
+
bool upb_encode_message(upb_encstate *e, const char *msg,
const upb_msglayout *m, size_t *size) {
int i;
@@ -1068,11 +1107,19 @@
const char *unknown;
size_t unknown_size;
+ unknown = upb_msg_getunknown(msg, &unknown_size);
+
+ if (unknown) {
+ upb_put_bytes(e, unknown, unknown_size);
+ }
+
for (i = m->field_count - 1; i >= 0; i--) {
const upb_msglayout_field *f = &m->fields[i];
- if (f->label == UPB_LABEL_REPEATED) {
+ if (_upb_isrepeated(f)) {
CHK(upb_encode_array(e, msg + f->offset, m, f));
+ } else if (f->label == _UPB_LABEL_MAP) {
+ CHK(upb_encode_map(e, msg + f->offset, m, f));
} else {
bool skip_empty = false;
if (f->presence == 0) {
@@ -1093,12 +1140,6 @@
}
}
- unknown = upb_msg_getunknown(msg, &unknown_size);
-
- if (unknown) {
- upb_put_bytes(e, unknown, unknown_size);
- }
-
*size = (e->limit - e->ptr) - pre_len;
return true;
}
@@ -1132,24 +1173,27 @@
-#define VOIDPTR_AT(msg, ofs) (void*)((char*)msg + (int)ofs)
+/** upb_msg *******************************************************************/
-/* Internal members of a upb_msg. We can change this without breaking binary
- * compatibility. We put these before the user's data. The user's upb_msg*
- * points after the upb_msg_internal. */
+static const char _upb_fieldtype_to_sizelg2[12] = {
+ 0,
+ 0, /* UPB_TYPE_BOOL */
+ 2, /* UPB_TYPE_FLOAT */
+ 2, /* UPB_TYPE_INT32 */
+ 2, /* UPB_TYPE_UINT32 */
+ 2, /* UPB_TYPE_ENUM */
+ UPB_SIZE(2, 3), /* UPB_TYPE_MESSAGE */
+ 3, /* UPB_TYPE_DOUBLE */
+ 3, /* UPB_TYPE_INT64 */
+ 3, /* UPB_TYPE_UINT64 */
+ UPB_SIZE(3, 4), /* UPB_TYPE_STRING */
+ UPB_SIZE(3, 4), /* UPB_TYPE_BYTES */
+};
-/* Used when a message is not extendable. */
-typedef struct {
- char *unknown;
- size_t unknown_len;
- size_t unknown_size;
-} upb_msg_internal;
-
-/* Used when a message is extendable. */
-typedef struct {
- upb_inttable *extdict;
- upb_msg_internal base;
-} upb_msg_internal_withext;
+static uintptr_t tag_arrptr(void* ptr, int elem_size_lg2) {
+ UPB_ASSERT(elem_size_lg2 <= 4);
+ return (uintptr_t)ptr | elem_size_lg2;
+}
static int upb_msg_internalsize(const upb_msglayout *l) {
return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
@@ -1160,22 +1204,22 @@
}
static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
- return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+ return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
}
static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
- return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+ return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
}
static upb_msg_internal_withext *upb_msg_getinternalwithext(
upb_msg *msg, const upb_msglayout *l) {
UPB_ASSERT(l->extendable);
- return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
+ return UPB_PTR_AT(msg, -sizeof(upb_msg_internal_withext),
+ upb_msg_internal_withext);
}
-upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
- upb_alloc *alloc = upb_arena_alloc(a);
- void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
+upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a) {
+ void *mem = upb_arena_malloc(a, upb_msg_sizeof(l));
upb_msg_internal *in;
upb_msg *msg;
@@ -1183,7 +1227,7 @@
return NULL;
}
- msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
+ msg = UPB_PTR_AT(mem, upb_msg_internalsize(l), upb_msg);
/* Initialize normal members. */
memset(msg, 0, l->size);
@@ -1201,66 +1245,122 @@
return msg;
}
-upb_array *upb_array_new(upb_arena *a) {
- upb_array *ret = upb_arena_malloc(a, sizeof(upb_array));
-
- if (!ret) {
- return NULL;
- }
-
- ret->data = NULL;
- ret->len = 0;
- ret->size = 0;
-
- return ret;
-}
-
-void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
- upb_arena *arena) {
+bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
+ upb_arena *arena) {
upb_msg_internal *in = upb_msg_getinternal(msg);
if (len > in->unknown_size - in->unknown_len) {
upb_alloc *alloc = upb_arena_alloc(arena);
size_t need = in->unknown_size + len;
size_t newsize = UPB_MAX(in->unknown_size * 2, need);
- in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
+ void *mem = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
+ if (!mem) return false;
+ in->unknown = mem;
in->unknown_size = newsize;
}
memcpy(in->unknown + in->unknown_len, data, len);
in->unknown_len += len;
+ return true;
}
const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
- const upb_msg_internal* in = upb_msg_getinternal_const(msg);
+ const upb_msg_internal *in = upb_msg_getinternal_const(msg);
*len = in->unknown_len;
return in->unknown;
}
-#undef VOIDPTR_AT
+/** upb_array *****************************************************************/
+upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type) {
+ upb_array *arr = upb_arena_malloc(a, sizeof(upb_array));
-#ifdef UPB_MSVC_VSNPRINTF
-/* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
- * vsnprintf. To support them, missing functions are manually implemented
- * using the existing secure functions. */
-int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
- if (!s) {
- return _vscprintf(format, arg);
+ if (!arr) {
+ return NULL;
}
- int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
- if (ret < 0) {
- ret = _vscprintf(format, arg);
- }
- return ret;
+
+ arr->data = tag_arrptr(NULL, _upb_fieldtype_to_sizelg2[type]);
+ arr->len = 0;
+ arr->size = 0;
+
+ return arr;
}
-int msvc_snprintf(char* s, size_t n, const char* format, ...) {
- va_list arg;
- va_start(arg, format);
- int ret = msvc_vsnprintf(s, n, format, arg);
- va_end(arg);
- return ret;
+bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena) {
+ size_t new_size = UPB_MAX(arr->size, 4);
+ int elem_size_lg2 = arr->data & 7;
+ size_t old_bytes = arr->size << elem_size_lg2;
+ size_t new_bytes;
+ void* ptr = _upb_array_ptr(arr);
+
+ /* Log2 ceiling of size. */
+ while (new_size < min_size) new_size *= 2;
+
+ new_bytes = new_size << elem_size_lg2;
+ ptr = upb_arena_realloc(arena, ptr, old_bytes, new_bytes);
+
+ if (!ptr) {
+ return false;
+ }
+
+ arr->data = tag_arrptr(ptr, elem_size_lg2);
+ arr->size = new_size;
+ return true;
}
-#endif
+
+static upb_array *getorcreate_array(upb_array **arr_ptr, upb_fieldtype_t type,
+ upb_arena *arena) {
+ upb_array *arr = *arr_ptr;
+ if (!arr) {
+ arr = _upb_array_new(arena, type);
+ if (!arr) return NULL;
+ *arr_ptr = arr;
+ }
+ return arr;
+}
+
+static bool resize_array(upb_array *arr, size_t size, upb_arena *arena) {
+ if (size > arr->size && !_upb_array_realloc(arr, size, arena)) {
+ return false;
+ }
+
+ arr->len = size;
+ return true;
+}
+
+void *_upb_array_resize_fallback(upb_array **arr_ptr, size_t size,
+ upb_fieldtype_t type, upb_arena *arena) {
+ upb_array *arr = getorcreate_array(arr_ptr, type, arena);
+ return arr && resize_array(arr, size, arena) ? _upb_array_ptr(arr) : NULL;
+}
+
+bool _upb_array_append_fallback(upb_array **arr_ptr, const void *value,
+ upb_fieldtype_t type, upb_arena *arena) {
+ upb_array *arr = getorcreate_array(arr_ptr, type, arena);
+ size_t elem = arr->len;
+ int lg2 = _upb_fieldtype_to_sizelg2[type];
+ char *data;
+
+ if (!arr || !resize_array(arr, elem + 1, arena)) return false;
+
+ data = _upb_array_ptr(arr);
+ memcpy(data + (elem << lg2), value, 1 << lg2);
+ return true;
+}
+
+/** upb_map *******************************************************************/
+
+upb_map *_upb_map_new(upb_arena *a, size_t key_size, size_t value_size) {
+ upb_map *map = upb_arena_malloc(a, sizeof(upb_map));
+
+ if (!map) {
+ return NULL;
+ }
+
+ upb_strtable_init2(&map->table, UPB_CTYPE_INT32, upb_arena_alloc(a));
+ map->key_size = key_size;
+ map->val_size = value_size;
+
+ return map;
+}
/*
** upb_table Implementation
**
@@ -1277,12 +1377,6 @@
#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
@@ -1361,17 +1455,12 @@
}
}
-static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
- upb_alloc *a) {
+static bool init(upb_table *t, 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 = upb_malloc(a, bytes);
@@ -1384,7 +1473,6 @@
}
static void uninit(upb_table *t, upb_alloc *a) {
- upb_check_alloc(t, a);
upb_free(a, mutable_entries(t));
}
@@ -1420,7 +1508,7 @@
const upb_tabent *e = findentry(t, key, hash, eql);
if (e) {
if (v) {
- _upb_value_setval(v, e->val.val, t->ctype);
+ _upb_value_setval(v, e->val.val);
}
return true;
} else {
@@ -1436,7 +1524,6 @@
upb_tabent *our_e;
UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
- UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
t->count++;
mainpos_e = getentry_mutable(t, hash);
@@ -1482,7 +1569,7 @@
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);
if (removed) *removed = chain->key;
if (chain->next) {
upb_tabent *move = (upb_tabent*)chain->next;
@@ -1502,7 +1589,7 @@
/* Found element to remove. */
upb_tabent *rm = (upb_tabent*)chain->next;
t->count--;
- if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
+ if (val) _upb_value_setval(val, chain->next->val.val);
if (removed) *removed = rm->key;
rm->key = 0; /* Make the slot empty. */
chain->next = rm->next;
@@ -1555,7 +1642,13 @@
}
bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
- return init(&t->t, ctype, 2, a);
+ return init(&t->t, 2, a);
+}
+
+void upb_strtable_clear(upb_strtable *t) {
+ size_t bytes = upb_table_size(&t->t) * sizeof(upb_tabent);
+ t->t.count = 0;
+ memset((char*)t->t.entries, 0, bytes);
}
void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
@@ -1569,18 +1662,14 @@
upb_strtable new_table;
upb_strtable_iter i;
- upb_check_alloc(&t->t, a);
-
- if (!init(&new_table.t, t->t.ctype, size_lg2, a))
+ if (!init(&new_table.t, size_lg2, a))
return false;
upb_strtable_begin(&i, t);
for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ upb_strview key = upb_strtable_iter_key(&i);
upb_strtable_insert3(
- &new_table,
- upb_strtable_iter_key(&i),
- upb_strtable_iter_keylength(&i),
- upb_strtable_iter_value(&i),
- a);
+ &new_table, key.data, key.size,
+ upb_strtable_iter_value(&i), a);
}
upb_strtable_uninit2(t, a);
*t = new_table;
@@ -1593,8 +1682,6 @@
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, a)) {
@@ -1622,7 +1709,10 @@
uint32_t hash = upb_murmur_hash2(key, len, 0);
upb_tabkey tabkey;
if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
- upb_free(alloc, (void*)tabkey);
+ if (alloc) {
+ /* Arena-based allocs don't need to free and won't pass this. */
+ upb_free(alloc, (void*)tabkey);
+ }
return true;
} else {
return false;
@@ -1631,10 +1721,6 @@
/* Iteration */
-static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
- return &i->t->t.entries[i->index];
-}
-
void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
i->t = t;
i->index = begin(&t->t);
@@ -1650,21 +1736,18 @@
upb_tabent_isempty(str_tabent(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(const upb_strtable_iter *i) {
+upb_strview upb_strtable_iter_key(const upb_strtable_iter *i) {
+ upb_strview key;
uint32_t len;
UPB_ASSERT(!upb_strtable_done(i));
- upb_tabstr(str_tabent(i)->key, &len);
- return len;
+ key.data = upb_tabstr(str_tabent(i)->key, &len);
+ key.size = len;
+ return key;
}
upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
UPB_ASSERT(!upb_strtable_done(i));
- return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
+ return _upb_value_val(str_tabent(i)->val.val);
}
void upb_strtable_iter_setdone(upb_strtable_iter *i) {
@@ -1730,11 +1813,11 @@
#endif
}
-bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
- size_t asize, int hsize_lg2, upb_alloc *a) {
+bool upb_inttable_sizedinit(upb_inttable *t, size_t asize, int hsize_lg2,
+ upb_alloc *a) {
size_t array_bytes;
- if (!init(&t->t, ctype, hsize_lg2, a)) return false;
+ if (!init(&t->t, 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);
@@ -1751,7 +1834,7 @@
}
bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
- return upb_inttable_sizedinit(t, ctype, 0, 4, a);
+ return upb_inttable_sizedinit(t, 0, 4, a);
}
void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
@@ -1765,8 +1848,6 @@
tabval.val = val.val;
UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
- upb_check_alloc(&t->t, a);
-
if (key < t->array_size) {
UPB_ASSERT(!upb_arrhas(t->array[key]));
t->array_count++;
@@ -1777,7 +1858,7 @@
size_t i;
upb_table new_table;
- if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
+ if (!init(&new_table, t->t.size_lg2 + 1, a)) {
return false;
}
@@ -1786,7 +1867,7 @@
uint32_t hash;
upb_value v;
- _upb_value_setval(&v, e->val.val, t->t.ctype);
+ _upb_value_setval(&v, e->val.val);
hash = upb_inthash(e->key);
insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
}
@@ -1805,7 +1886,7 @@
bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
const upb_tabval *table_v = inttable_val_const(t, key);
if (!table_v) return false;
- if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
+ if (v) _upb_value_setval(v, table_v->val);
return true;
}
@@ -1823,7 +1904,7 @@
upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
t->array_count--;
if (val) {
- _upb_value_setval(val, t->array[key].val, t->t.ctype);
+ _upb_value_setval(val, t->array[key].val);
}
mutable_array(t)[key] = empty;
success = true;
@@ -1838,7 +1919,6 @@
}
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);
}
@@ -1851,7 +1931,6 @@
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);
}
@@ -1876,8 +1955,6 @@
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);
@@ -1910,7 +1987,7 @@
size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
int hashsize_lg2 = log2ceil(hash_size);
- upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
+ upb_inttable_sizedinit(&new_t, 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);
@@ -1976,8 +2053,7 @@
upb_value upb_inttable_iter_value(const upb_inttable_iter *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);
+ i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val);
}
void upb_inttable_iter_setdone(upb_inttable_iter *i) {
@@ -2017,7 +2093,8 @@
/* Mix 4 bytes at a time into the hash */
const uint8_t * data = (const uint8_t *)key;
while(len >= 4) {
- uint32_t k = *(uint32_t *)data;
+ uint32_t k;
+ memcpy(&k, data, sizeof(k));
k *= m;
k ^= k >> r;
@@ -2182,17 +2259,6 @@
#include <string.h>
-/* Guarantee null-termination and provide ellipsis truncation.
- * It may be tempting to "optimize" this by initializing these final
- * four bytes up-front and then being careful never to overwrite them,
- * this is safer and simpler. */
-static void nullz(upb_status *status) {
- const char *ellipsis = "...";
- size_t len = strlen(ellipsis);
- UPB_ASSERT(sizeof(status->msg) > len);
- memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
-}
-
/* upb_status *****************************************************************/
void upb_status_clear(upb_status *status) {
@@ -2208,8 +2274,8 @@
void upb_status_seterrmsg(upb_status *status, const char *msg) {
if (!status) return;
status->ok = false;
- strncpy(status->msg, msg, sizeof(status->msg));
- nullz(status);
+ strncpy(status->msg, msg, UPB_STATUS_MAX_MESSAGE - 1);
+ status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
}
void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
@@ -2223,7 +2289,7 @@
if (!status) return;
status->ok = false;
_upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
- nullz(status);
+ status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
}
/* upb_alloc ******************************************************************/
@@ -2245,190 +2311,216 @@
/* upb_arena ******************************************************************/
/* Be conservative and choose 16 in case anyone is using SSE. */
-static const size_t maxalign = 16;
-
-static size_t align_up_max(size_t size) {
- return ((size + maxalign - 1) / maxalign) * maxalign;
-}
-
-struct upb_arena {
- /* 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;
-};
typedef struct mem_block {
struct mem_block *next;
- size_t size;
- size_t used;
- bool owned;
+ uint32_t size;
+ uint32_t cleanups;
/* 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) {
+struct upb_arena {
+ _upb_arena_head head;
+ uint32_t *cleanups;
+
+ /* Allocator to allocate arena blocks. We are responsible for freeing these
+ * when we are destroyed. */
+ upb_alloc *block_alloc;
+ uint32_t last_size;
+
+ /* When multiple arenas are fused together, each arena points to a parent
+ * arena (root points to itself). The root tracks how many live arenas
+ * reference it. */
+ uint32_t refcount; /* Only used when a->parent == a */
+ struct upb_arena *parent;
+
+ /* Linked list of blocks to free/cleanup. */
+ mem_block *freelist, *freelist_tail;
+};
+
+static const size_t memblock_reserve = UPB_ALIGN_UP(sizeof(mem_block), 16);
+
+static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size) {
mem_block *block = ptr;
- block->next = a->block_head;
+ block->next = a->freelist;
block->size = size;
- block->used = align_up_max(sizeof(mem_block));
- block->owned = owned;
+ block->cleanups = 0;
+ a->freelist = block;
+ a->last_size = size;
+ if (!a->freelist_tail) a->freelist_tail = block;
- a->block_head = block;
+ a->head.ptr = UPB_PTR_AT(block, memblock_reserve, char);
+ a->head.end = UPB_PTR_AT(block, size, char);
+ a->cleanups = &block->cleanups;
/* 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);
+static bool upb_arena_allocblock(upb_arena *a, size_t size) {
+ size_t block_size = UPB_MAX(size, a->last_size * 2) + memblock_reserve;
mem_block *block = upb_malloc(a->block_alloc, block_size);
- if (!block) {
- return NULL;
- }
+ if (!block) return false;
+ upb_arena_addblock(a, block, block_size);
+ return true;
+}
- upb_arena_addblock(a, block, block_size, true);
- a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
+static bool arena_has(upb_arena *a, size_t size) {
+ _upb_arena_head *h = (_upb_arena_head*)a;
+ return (size_t)(h->end - h->ptr) >= size;
+}
- return block;
+void *_upb_arena_slowmalloc(upb_arena *a, size_t size) {
+ if (!upb_arena_allocblock(a, size)) return NULL; /* Out of memory. */
+ UPB_ASSERT(arena_has(a, size));
+ return upb_arena_malloc(a, size);
}
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;
+ return upb_arena_realloc(a, ptr, oldsize, size);
+}
- if (size == 0) {
- return NULL; /* We are an arena, don't need individual frees. */
+static upb_arena *arena_findroot(upb_arena *a) {
+ /* Path splitting keeps time complexity down, see:
+ * https://en.wikipedia.org/wiki/Disjoint-set_data_structure */
+ while (a->parent != a) {
+ upb_arena *next = a->parent;
+ a->parent = next->parent;
+ a = next;
}
-
- size = align_up_max(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;
+ return a;
}
/* Public Arena API ***********************************************************/
-#define upb_alignof(type) offsetof (struct { char c; type member; }, member)
-
-upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
- const size_t first_block_overhead = sizeof(upb_arena) + sizeof(mem_block);
+upb_arena *arena_initslow(void *mem, size_t n, upb_alloc *alloc) {
+ const size_t first_block_overhead = sizeof(upb_arena) + memblock_reserve;
upb_arena *a;
- bool owned = false;
- /* Round block size down to alignof(*a) since we will allocate the arena
- * itself at the end. */
- n &= ~(upb_alignof(upb_arena) - 1);
-
- if (n < first_block_overhead) {
- /* We need to malloc the initial block. */
- n = first_block_overhead + 256;
- owned = true;
- if (!alloc || !(mem = upb_malloc(alloc, n))) {
- return NULL;
- }
+ /* We need to malloc the initial block. */
+ n = first_block_overhead + 256;
+ if (!alloc || !(mem = upb_malloc(alloc, n))) {
+ return NULL;
}
- a = (void*)((char*)mem + n - sizeof(*a));
+ a = UPB_PTR_AT(mem, n - sizeof(*a), upb_arena);
n -= sizeof(*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;
+ a->head.alloc.func = &upb_arena_doalloc;
a->block_alloc = alloc;
+ a->parent = a;
+ a->refcount = 1;
+ a->freelist = NULL;
+ a->freelist_tail = NULL;
- upb_arena_addblock(a, mem, n, owned);
+ upb_arena_addblock(a, mem, n);
return a;
}
-#undef upb_alignof
+upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc) {
+ upb_arena *a;
-void upb_arena_free(upb_arena *a) {
- cleanup_ent *ent = a->cleanup_head;
- mem_block *block = a->block_head;
+ /* Round block size down to alignof(*a) since we will allocate the arena
+ * itself at the end. */
+ n = UPB_ALIGN_DOWN(n, UPB_ALIGN_OF(upb_arena));
- while (ent) {
- ent->cleanup(ent->ud);
- ent = ent->next;
+ if (UPB_UNLIKELY(n < sizeof(upb_arena))) {
+ return arena_initslow(mem, n, alloc);
}
- /* Must do this after running cleanup functions, because this will delete
- * the memory we store our cleanup entries in! */
+ a = UPB_PTR_AT(mem, n - sizeof(*a), upb_arena);
+ n -= sizeof(*a);
+
+ a->head.alloc.func = &upb_arena_doalloc;
+ a->block_alloc = alloc;
+ a->parent = a;
+ a->refcount = 1;
+ a->last_size = 128;
+ a->head.ptr = mem;
+ a->head.end = UPB_PTR_AT(mem, n, char);
+ a->freelist = NULL;
+ a->cleanups = NULL;
+
+ return a;
+}
+
+static void arena_dofree(upb_arena *a) {
+ mem_block *block = a->freelist;
+ UPB_ASSERT(a->parent == a);
+ UPB_ASSERT(a->refcount == 0);
+
while (block) {
/* Load first since we are deleting block. */
mem_block *next = block->next;
- if (block->owned) {
- upb_free(a->block_alloc, block);
+ if (block->cleanups > 0) {
+ cleanup_ent *end = UPB_PTR_AT(block, block->size, void);
+ cleanup_ent *ptr = end - block->cleanups;
+
+ for (; ptr < end; ptr++) {
+ ptr->cleanup(ptr->ud);
+ }
}
+ upb_free(a->block_alloc, block);
block = next;
}
}
+void upb_arena_free(upb_arena *a) {
+ a = arena_findroot(a);
+ if (--a->refcount == 0) arena_dofree(a);
+}
+
bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
- cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
- if (!ent) {
- return false; /* Out of memory. */
+ cleanup_ent *ent;
+
+ if (!a->cleanups || !arena_has(a, sizeof(cleanup_ent))) {
+ if (!upb_arena_allocblock(a, 128)) return false; /* Out of memory. */
+ UPB_ASSERT(arena_has(a, sizeof(cleanup_ent)));
}
+ a->head.end -= sizeof(cleanup_ent);
+ ent = (cleanup_ent*)a->head.end;
+ (*a->cleanups)++;
+
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;
+void upb_arena_fuse(upb_arena *a1, upb_arena *a2) {
+ upb_arena *r1 = arena_findroot(a1);
+ upb_arena *r2 = arena_findroot(a2);
+
+ if (r1 == r2) return; /* Already fused. */
+
+ /* We want to join the smaller tree to the larger tree.
+ * So swap first if they are backwards. */
+ if (r1->refcount < r2->refcount) {
+ upb_arena *tmp = r1;
+ r1 = r2;
+ r2 = tmp;
+ }
+
+ /* r1 takes over r2's freelist and refcount. */
+ r1->refcount += r2->refcount;
+ if (r2->freelist_tail) {
+ UPB_ASSERT(r2->freelist_tail->next == NULL);
+ r2->freelist_tail->next = r1->freelist;
+ r1->freelist = r2->freelist;
+ }
+ r2->parent = r1;
}
/* This file was generated by upbc (the upb compiler) from the input
* file:
@@ -2559,23 +2651,24 @@
&google_protobuf_FieldOptions_msginit,
};
-static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
- {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
- {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
+static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[11] = {
+ {1, UPB_SIZE(36, 40), 6, 0, 9, 1},
+ {2, UPB_SIZE(44, 56), 7, 0, 9, 1},
{3, UPB_SIZE(24, 24), 3, 0, 5, 1},
{4, UPB_SIZE(8, 8), 1, 0, 14, 1},
{5, UPB_SIZE(16, 16), 2, 0, 14, 1},
- {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
- {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
- {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
+ {6, UPB_SIZE(52, 72), 8, 0, 9, 1},
+ {7, UPB_SIZE(60, 88), 9, 0, 9, 1},
+ {8, UPB_SIZE(76, 120), 11, 0, 11, 1},
{9, UPB_SIZE(28, 28), 4, 0, 5, 1},
- {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
+ {10, UPB_SIZE(68, 104), 10, 0, 9, 1},
+ {17, UPB_SIZE(32, 32), 5, 0, 8, 1},
};
const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
&google_protobuf_FieldDescriptorProto_submsgs[0],
&google_protobuf_FieldDescriptorProto__fields[0],
- UPB_SIZE(80, 128), 10, false,
+ UPB_SIZE(80, 128), 11, false,
};
static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
@@ -2870,8 +2963,8 @@
};
static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
- {1, UPB_SIZE(20, 40), 0, 0, 5, 3},
- {2, UPB_SIZE(24, 48), 0, 0, 5, 3},
+ {1, UPB_SIZE(20, 40), 0, 0, 5, _UPB_LABEL_PACKED},
+ {2, UPB_SIZE(24, 48), 0, 0, 5, _UPB_LABEL_PACKED},
{3, UPB_SIZE(4, 8), 1, 0, 9, 1},
{4, UPB_SIZE(12, 24), 2, 0, 9, 1},
{6, UPB_SIZE(28, 56), 0, 0, 9, 3},
@@ -2898,7 +2991,7 @@
};
static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
- {1, UPB_SIZE(20, 32), 0, 0, 5, 3},
+ {1, UPB_SIZE(20, 32), 0, 0, 5, _UPB_LABEL_PACKED},
{2, UPB_SIZE(12, 16), 3, 0, 9, 1},
{3, UPB_SIZE(4, 4), 1, 0, 5, 1},
{4, UPB_SIZE(8, 8), 2, 0, 5, 1},
@@ -2937,6 +3030,7 @@
const upb_filedef *file;
const upb_msgdef *msgdef;
const char *full_name;
+ const char *json_name;
union {
int64_t sint;
uint64_t uint;
@@ -2952,16 +3046,19 @@
const google_protobuf_FieldDescriptorProto *unresolved;
} sub;
uint32_t number_;
- uint32_t index_;
+ uint16_t index_;
+ uint16_t layout_index;
uint32_t selector_base; /* Used to index into a upb::Handlers table. */
bool is_extension_;
bool lazy_;
bool packed_;
+ bool proto3_optional_;
upb_descriptortype_t type_;
upb_label_t label_;
};
struct upb_msgdef {
+ const upb_msglayout *layout;
const upb_filedef *file;
const char *full_name;
uint32_t selector_count;
@@ -2975,6 +3072,7 @@
const upb_oneofdef *oneofs;
int field_count;
int oneof_count;
+ int real_oneof_count;
/* Is this a map-entry message? */
bool map_entry;
@@ -3025,10 +3123,15 @@
/* Inside a symtab we store tagged pointers to specific def types. */
typedef enum {
- UPB_DEFTYPE_MSG = 0,
- UPB_DEFTYPE_ENUM = 1,
- UPB_DEFTYPE_FIELD = 2,
- UPB_DEFTYPE_ONEOF = 3
+ UPB_DEFTYPE_FIELD = 0,
+
+ /* Only inside symtab table. */
+ UPB_DEFTYPE_MSG = 1,
+ UPB_DEFTYPE_ENUM = 2,
+
+ /* Only inside message table. */
+ UPB_DEFTYPE_ONEOF = 1,
+ UPB_DEFTYPE_FIELD_JSONNAME = 2
} upb_deftype_t;
static const void *unpack_def(upb_value v, upb_deftype_t type) {
@@ -3141,11 +3244,14 @@
return ret;
}
+static void upb_status_setoom(upb_status *status) {
+ upb_status_seterrmsg(status, "out of memory");
+}
+
static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
/* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
* lowest indexes, but we do not publicly guarantee this. */
upb_msg_field_iter j;
- upb_msg_oneof_iter k;
int i;
uint32_t selector;
int n = upb_msgdef_numfields(m);
@@ -3186,14 +3292,38 @@
}
m->selector_count = selector;
- for(upb_msg_oneof_begin(&k, m), i = 0;
- !upb_msg_oneof_done(&k);
- upb_msg_oneof_next(&k), i++) {
- upb_oneofdef *o = (upb_oneofdef*)upb_msg_iter_oneof(&k);
- o->index = i;
+ upb_gfree(fields);
+ return true;
+}
+
+static bool check_oneofs(upb_msgdef *m, upb_status *s) {
+ int i;
+ int first_synthetic = -1;
+ upb_oneofdef *mutable_oneofs = (upb_oneofdef*)m->oneofs;
+
+ for (i = 0; i < m->oneof_count; i++) {
+ mutable_oneofs[i].index = i;
+
+ if (upb_oneofdef_issynthetic(&mutable_oneofs[i])) {
+ if (first_synthetic == -1) {
+ first_synthetic = i;
+ }
+ } else {
+ if (first_synthetic != -1) {
+ upb_status_seterrf(
+ s, "Synthetic oneofs must be after all other oneofs: %s",
+ upb_oneofdef_name(&mutable_oneofs[i]));
+ return false;
+ }
+ }
}
- upb_gfree(fields);
+ if (first_synthetic == -1) {
+ m->real_oneof_count = m->oneof_count;
+ } else {
+ m->real_oneof_count = first_synthetic;
+ }
+
return true;
}
@@ -3261,7 +3391,7 @@
}
int upb_enumdef_numvals(const upb_enumdef *e) {
- return upb_strtable_count(&e->ntoi);
+ return (int)upb_strtable_count(&e->ntoi);
}
void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
@@ -3289,7 +3419,7 @@
}
const char *upb_enum_iter_name(upb_enum_iter *iter) {
- return upb_strtable_iter_key(iter);
+ return upb_strtable_iter_key(iter).data;
}
int32_t upb_enum_iter_number(upb_enum_iter *iter) {
@@ -3370,47 +3500,16 @@
return shortdefname(f->full_name);
}
+const char *upb_fielddef_jsonname(const upb_fielddef *f) {
+ return f->json_name;
+}
+
uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
return f->selector_base;
}
-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_filedef *upb_fielddef_file(const upb_fielddef *f) {
+ return f->file;
}
const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
@@ -3421,6 +3520,11 @@
return f->oneof;
}
+const upb_oneofdef *upb_fielddef_realcontainingoneof(const upb_fielddef *f) {
+ if (!f->oneof || upb_oneofdef_issynthetic(f->oneof)) return NULL;
+ return f->oneof;
+}
+
static void chkdefaulttype(const upb_fielddef *f, int ctype) {
UPB_UNUSED(f);
UPB_UNUSED(ctype);
@@ -3433,7 +3537,7 @@
int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
chkdefaulttype(f, UPB_TYPE_INT32);
- return f->defaultval.sint;
+ return (int32_t)f->defaultval.sint;
}
uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
@@ -3443,7 +3547,7 @@
uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
chkdefaulttype(f, UPB_TYPE_UINT32);
- return f->defaultval.uint;
+ return (uint32_t)f->defaultval.uint;
}
bool upb_fielddef_defaultbool(const upb_fielddef *f) {
@@ -3485,6 +3589,10 @@
return f->sub.enumdef;
}
+const upb_msglayout_field *upb_fielddef_layout(const upb_fielddef *f) {
+ return &f->msgdef->layout->fields[f->layout_index];
+}
+
bool upb_fielddef_issubmsg(const upb_fielddef *f) {
return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
}
@@ -3513,8 +3621,8 @@
bool upb_fielddef_haspresence(const upb_fielddef *f) {
if (upb_fielddef_isseq(f)) return false;
- if (upb_fielddef_issubmsg(f)) return true;
- return f->file->syntax == UPB_SYNTAX_PROTO2;
+ return upb_fielddef_issubmsg(f) || upb_fielddef_containingoneof(f) ||
+ f->file->syntax == UPB_SYNTAX_PROTO2;
}
static bool between(int32_t x, int32_t low, int32_t high) {
@@ -3593,18 +3701,43 @@
*o = unpack_def(val, UPB_DEFTYPE_ONEOF);
*f = unpack_def(val, UPB_DEFTYPE_FIELD);
- UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
- return true;
+ return *o || *f; /* False if this was a JSON name. */
+}
+
+const upb_fielddef *upb_msgdef_lookupjsonname(const upb_msgdef *m,
+ const char *name, size_t len) {
+ upb_value val;
+ const upb_fielddef* f;
+
+ if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
+ return NULL;
+ }
+
+ f = unpack_def(val, UPB_DEFTYPE_FIELD);
+ if (!f) f = unpack_def(val, UPB_DEFTYPE_FIELD_JSONNAME);
+
+ return f;
}
int upb_msgdef_numfields(const upb_msgdef *m) {
- /* The number table contains only fields. */
- return upb_inttable_count(&m->itof);
+ return m->field_count;
}
int upb_msgdef_numoneofs(const upb_msgdef *m) {
- /* The name table includes oneofs, and the number table does not. */
- return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
+ return m->oneof_count;
+}
+
+int upb_msgdef_numrealoneofs(const upb_msgdef *m) {
+ return m->real_oneof_count;
+}
+
+const upb_msglayout *upb_msgdef_layout(const upb_msgdef *m) {
+ return m->layout;
+}
+
+const upb_fielddef *_upb_msgdef_field(const upb_msgdef *m, int i) {
+ if (i >= m->field_count) return NULL;
+ return &m->fields[i];
}
bool upb_msgdef_mapentry(const upb_msgdef *m) {
@@ -3689,13 +3822,23 @@
}
int upb_oneofdef_numfields(const upb_oneofdef *o) {
- return upb_strtable_count(&o->ntof);
+ return (int)upb_strtable_count(&o->ntof);
}
uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
return o->index;
}
+bool upb_oneofdef_issynthetic(const upb_oneofdef *o) {
+ upb_inttable_iter iter;
+ const upb_fielddef *f;
+ upb_inttable_begin(&iter, &o->itof);
+ if (upb_oneofdef_numfields(o) != 1) return false;
+ f = upb_value_getptr(upb_inttable_iter_value(&iter));
+ UPB_ASSERT(f);
+ return f->proto3_optional_;
+}
+
const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
const char *name, size_t length) {
upb_value val;
@@ -3729,6 +3872,215 @@
upb_inttable_iter_setdone(iter);
}
+/* Dynamic Layout Generation. *************************************************/
+
+static size_t div_round_up(size_t n, size_t d) {
+ return (n + d - 1) / d;
+}
+
+static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ return 8;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_FLOAT:
+ return 4;
+ case UPB_TYPE_BOOL:
+ return 1;
+ case UPB_TYPE_MESSAGE:
+ return sizeof(void*);
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_STRING:
+ return sizeof(upb_strview);
+ }
+ UPB_UNREACHABLE();
+}
+
+static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
+ if (upb_msgdef_mapentry(upb_fielddef_containingtype(f))) {
+ upb_map_entry ent;
+ UPB_ASSERT(sizeof(ent.k) == sizeof(ent.v));
+ return sizeof(ent.k);
+ } else if (upb_fielddef_isseq(f)) {
+ return sizeof(void*);
+ } else {
+ return upb_msgval_sizeof(upb_fielddef_type(f));
+ }
+}
+
+static uint32_t upb_msglayout_place(upb_msglayout *l, size_t size) {
+ uint32_t ret;
+
+ l->size = UPB_ALIGN_UP(l->size, size);
+ ret = l->size;
+ l->size += size;
+ return ret;
+}
+
+/* This function is the dynamic equivalent of message_layout.{cc,h} in upbc.
+ * It computes a dynamic layout for all of the fields in |m|. */
+static bool make_layout(const upb_symtab *symtab, const upb_msgdef *m) {
+ upb_msglayout *l = (upb_msglayout*)m->layout;
+ upb_msg_field_iter it;
+ upb_msg_oneof_iter oit;
+ size_t hasbit;
+ size_t submsg_count = m->submsg_field_count;
+ const upb_msglayout **submsgs;
+ upb_msglayout_field *fields;
+ upb_alloc *alloc = upb_arena_alloc(symtab->arena);
+
+ memset(l, 0, sizeof(*l));
+
+ fields = upb_malloc(alloc, upb_msgdef_numfields(m) * sizeof(*fields));
+ submsgs = upb_malloc(alloc, submsg_count * sizeof(*submsgs));
+
+ if ((!fields && upb_msgdef_numfields(m)) ||
+ (!submsgs && submsg_count)) {
+ /* OOM. */
+ return false;
+ }
+
+ l->field_count = upb_msgdef_numfields(m);
+ l->fields = fields;
+ l->submsgs = submsgs;
+
+ if (upb_msgdef_mapentry(m)) {
+ /* TODO(haberman): refactor this method so this special case is more
+ * elegant. */
+ const upb_fielddef *key = upb_msgdef_itof(m, 1);
+ const upb_fielddef *val = upb_msgdef_itof(m, 2);
+ fields[0].number = 1;
+ fields[1].number = 2;
+ fields[0].label = UPB_LABEL_OPTIONAL;
+ fields[1].label = UPB_LABEL_OPTIONAL;
+ fields[0].presence = 0;
+ fields[1].presence = 0;
+ fields[0].descriptortype = upb_fielddef_descriptortype(key);
+ fields[1].descriptortype = upb_fielddef_descriptortype(val);
+ fields[0].offset = 0;
+ fields[1].offset = sizeof(upb_strview);
+ fields[1].submsg_index = 0;
+
+ if (upb_fielddef_type(val) == UPB_TYPE_MESSAGE) {
+ submsgs[0] = upb_fielddef_msgsubdef(val)->layout;
+ }
+
+ l->field_count = 2;
+ l->size = 2 * sizeof(upb_strview);
+ l->size = UPB_ALIGN_UP(l->size, 8);
+ return true;
+ }
+
+ /* Allocate data offsets in three stages:
+ *
+ * 1. hasbits.
+ * 2. regular fields.
+ * 3. oneof fields.
+ *
+ * OPT: There is a lot of room for optimization here to minimize the size.
+ */
+
+ /* Allocate hasbits and set basic field attributes. */
+ submsg_count = 0;
+ for (upb_msg_field_begin(&it, m), hasbit = 0;
+ !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ upb_fielddef* f = upb_msg_iter_field(&it);
+ upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
+
+ field->number = upb_fielddef_number(f);
+ field->descriptortype = upb_fielddef_descriptortype(f);
+ field->label = upb_fielddef_label(f);
+
+ if (upb_fielddef_ismap(f)) {
+ field->label = _UPB_LABEL_MAP;
+ } else if (upb_fielddef_packed(f)) {
+ field->label = _UPB_LABEL_PACKED;
+ }
+
+ /* TODO: we probably should sort the fields by field number to match the
+ * output of upbc, and to improve search speed for the table parser. */
+ f->layout_index = f->index_;
+
+ if (upb_fielddef_issubmsg(f)) {
+ const upb_msgdef *subm = upb_fielddef_msgsubdef(f);
+ field->submsg_index = submsg_count++;
+ submsgs[field->submsg_index] = subm->layout;
+ }
+
+ if (upb_fielddef_haspresence(f) && !upb_fielddef_realcontainingoneof(f)) {
+ /* We don't use hasbit 0, so that 0 can indicate "no presence" in the
+ * table. This wastes one hasbit, but we don't worry about it for now. */
+ field->presence = ++hasbit;
+ } else {
+ field->presence = 0;
+ }
+ }
+
+ /* Account for space used by hasbits. */
+ l->size = div_round_up(hasbit, 8);
+
+ /* Allocate non-oneof fields. */
+ for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ size_t field_size = upb_msg_fielddefsize(f);
+ size_t index = upb_fielddef_index(f);
+
+ if (upb_fielddef_realcontainingoneof(f)) {
+ /* Oneofs are handled separately below. */
+ continue;
+ }
+
+ fields[index].offset = upb_msglayout_place(l, field_size);
+ }
+
+ /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
+ * and space for the actual data. */
+ for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
+ upb_msg_oneof_next(&oit)) {
+ const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
+ upb_oneof_iter fit;
+
+ size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
+ size_t field_size = 0;
+ uint32_t case_offset;
+ uint32_t data_offset;
+
+ if (upb_oneofdef_issynthetic(o)) continue;
+
+ /* Calculate field size: the max of all field sizes. */
+ for (upb_oneof_begin(&fit, o);
+ !upb_oneof_done(&fit);
+ upb_oneof_next(&fit)) {
+ const upb_fielddef* f = upb_oneof_iter_field(&fit);
+ field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
+ }
+
+ /* Align and allocate case offset. */
+ case_offset = upb_msglayout_place(l, case_size);
+ data_offset = upb_msglayout_place(l, field_size);
+
+ for (upb_oneof_begin(&fit, o);
+ !upb_oneof_done(&fit);
+ upb_oneof_next(&fit)) {
+ const upb_fielddef* f = upb_oneof_iter_field(&fit);
+ fields[upb_fielddef_index(f)].offset = data_offset;
+ fields[upb_fielddef_index(f)].presence = ~case_offset;
+ }
+ }
+
+ /* Size of the entire structure should be a multiple of its greatest
+ * alignment. TODO: track overall alignment for real? */
+ l->size = UPB_ALIGN_UP(l->size, 8);
+
+ return true;
+}
+
/* Code to build defs from descriptor protos. *********************************/
/* There is a question of how much validation to do here. It will be difficult
@@ -3741,11 +4093,12 @@
typedef struct {
const upb_symtab *symtab;
- upb_filedef *file; /* File we are building. */
- upb_alloc *alloc; /* Allocate defs here. */
- upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
- upb_strtable *addtab; /* full_name -> packed def ptr for new defs. */
- upb_status *status; /* Record errors here. */
+ upb_filedef *file; /* File we are building. */
+ upb_alloc *alloc; /* Allocate defs here. */
+ upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
+ upb_strtable *addtab; /* full_name -> packed def ptr for new defs */
+ const upb_msglayout **layouts; /* NULL if we should build layouts. */
+ upb_status *status; /* Record errors here. */
} symtab_addctx;
static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
@@ -3777,6 +4130,51 @@
}
}
+size_t getjsonname(const char *name, char *buf, size_t len) {
+ 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
+}
+
+static char* makejsonname(const char* name, upb_alloc *alloc) {
+ size_t size = getjsonname(name, NULL, 0);
+ char* json_name = upb_malloc(alloc, size);
+ getjsonname(name, json_name, size);
+ return json_name;
+}
+
static bool symtab_add(const symtab_addctx *ctx, const char *name,
upb_value v) {
upb_value tmp;
@@ -3900,7 +4298,7 @@
}
case UPB_TYPE_INT64: {
/* XXX: Need to write our own strtoll, since it's not available in c89. */
- long long val = strtol(str, &end, 0);
+ int64_t val = strtol(str, &end, 0);
CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
f->defaultval.sint = val;
break;
@@ -3913,7 +4311,7 @@
}
case UPB_TYPE_UINT64: {
/* XXX: Need to write our own strtoull, since it's not available in c89. */
- unsigned long long val = strtoul(str, &end, 0);
+ uint64_t val = strtoul(str, &end, 0);
CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
f->defaultval.uint = val;
break;
@@ -3990,6 +4388,7 @@
const google_protobuf_FieldOptions *options;
upb_strview name;
const char *full_name;
+ const char *json_name;
const char *shortname;
uint32_t field_number;
@@ -4003,6 +4402,13 @@
full_name = makefullname(ctx, prefix, name);
shortname = shortdefname(full_name);
+ if (google_protobuf_FieldDescriptorProto_has_json_name(field_proto)) {
+ json_name = strviewdup(
+ ctx, google_protobuf_FieldDescriptorProto_json_name(field_proto));
+ } else {
+ json_name = makejsonname(shortname, ctx->alloc);
+ }
+
field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
@@ -4012,38 +4418,72 @@
if (m) {
/* direct message field. */
- upb_value v, packed_v;
+ upb_value v, field_v, json_v;
+ size_t json_size;
f = (upb_fielddef*)&m->fields[m->field_count++];
f->msgdef = m;
f->is_extension_ = false;
- packed_v = pack_def(f, UPB_DEFTYPE_FIELD);
- v = upb_value_constptr(f);
-
- if (!upb_strtable_insert3(&m->ntof, name.data, name.size, packed_v, alloc)) {
+ if (upb_strtable_lookup(&m->ntof, shortname, NULL)) {
upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
return false;
}
- if (!upb_inttable_insert2(&m->itof, field_number, v, alloc)) {
+ if (upb_strtable_lookup(&m->ntof, json_name, NULL)) {
+ upb_status_seterrf(ctx->status, "duplicate json_name (%s)", json_name);
+ return false;
+ }
+
+ if (upb_inttable_lookup(&m->itof, field_number, NULL)) {
upb_status_seterrf(ctx->status, "duplicate field number (%u)",
field_number);
return false;
}
+
+ field_v = pack_def(f, UPB_DEFTYPE_FIELD);
+ json_v = pack_def(f, UPB_DEFTYPE_FIELD_JSONNAME);
+ v = upb_value_constptr(f);
+ json_size = strlen(json_name);
+
+ CHK_OOM(
+ upb_strtable_insert3(&m->ntof, name.data, name.size, field_v, alloc));
+ CHK_OOM(upb_inttable_insert2(&m->itof, field_number, v, alloc));
+
+ if (strcmp(shortname, json_name) != 0) {
+ upb_strtable_insert3(&m->ntof, json_name, json_size, json_v, alloc);
+ }
+
+ if (ctx->layouts) {
+ const upb_msglayout_field *fields = m->layout->fields;
+ int count = m->layout->field_count;
+ bool found = false;
+ int i;
+ for (i = 0; i < count; i++) {
+ if (fields[i].number == field_number) {
+ f->layout_index = i;
+ found = true;
+ break;
+ }
+ }
+ UPB_ASSERT(found);
+ }
} else {
/* extension field. */
- f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count];
+ f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count++];
f->is_extension_ = true;
CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
}
f->full_name = full_name;
+ f->json_name = json_name;
f->file = ctx->file;
f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
f->number_ = field_number;
f->oneof = NULL;
+ f->proto3_optional_ =
+ google_protobuf_FieldDescriptorProto_proto3_optional(field_proto);
/* We can't resolve the subdef or (in the case of extensions) the containing
* message yet, because it may not have been defined yet. We stash a pointer
@@ -4167,7 +4607,7 @@
return true;
}
-static bool create_msgdef(const symtab_addctx *ctx, const char *prefix,
+static bool create_msgdef(symtab_addctx *ctx, const char *prefix,
const google_protobuf_DescriptorProto *msg_proto) {
upb_msgdef *m;
const google_protobuf_MessageOptions *options;
@@ -4197,6 +4637,14 @@
m->map_entry = google_protobuf_MessageOptions_map_entry(options);
}
+ if (ctx->layouts) {
+ m->layout = *ctx->layouts;
+ ctx->layouts++;
+ } else {
+ /* Allocate now (to allow cross-linking), populate later. */
+ m->layout = upb_malloc(ctx->alloc, sizeof(*m->layout));
+ }
+
oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
m->oneof_count = 0;
m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
@@ -4212,6 +4660,7 @@
}
CHK(assign_msg_indices(m, ctx->status));
+ CHK(check_oneofs(m, ctx->status));
assign_msg_wellknowntype(m);
upb_inttable_compact2(&m->itof, ctx->alloc);
@@ -4343,7 +4792,7 @@
}
static bool build_filedef(
- const symtab_addctx *ctx, upb_filedef *file,
+ symtab_addctx *ctx, upb_filedef *file,
const google_protobuf_FileDescriptorProto *file_proto) {
upb_alloc *alloc = ctx->alloc;
const google_protobuf_FileOptions *file_options_proto;
@@ -4397,7 +4846,8 @@
} else if (streql_view(syntax, "proto3")) {
file->syntax = UPB_SYNTAX_PROTO3;
} else {
- upb_status_seterrf(ctx->status, "Invalid syntax '%s'", syntax);
+ upb_status_seterrf(ctx->status, "Invalid syntax '" UPB_STRVIEW_FORMAT "'",
+ UPB_STRVIEW_ARGS(syntax));
return false;
}
} else {
@@ -4457,7 +4907,7 @@
CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
}
- /* Now that all names are in the table, resolve references. */
+ /* Now that all names are in the table, build layouts and resolve refs. */
for (i = 0; i < file->ext_count; i++) {
CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
}
@@ -4470,6 +4920,13 @@
}
}
+ if (!ctx->layouts) {
+ for (i = 0; i < file->msg_count; i++) {
+ const upb_msgdef *m = &file->msgs[i];
+ make_layout(ctx->symtab, m);
+ }
+ }
+
return true;
}
@@ -4484,10 +4941,9 @@
upb_strtable_begin(&iter, ctx->addtab);
for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- const char *key = upb_strtable_iter_key(&iter);
- size_t keylen = upb_strtable_iter_keylength(&iter);
+ upb_strview key = upb_strtable_iter_key(&iter);
upb_value value = upb_strtable_iter_value(&iter);
- CHK_OOM(upb_strtable_insert3(&s->syms, key, keylen, value, alloc));
+ CHK_OOM(upb_strtable_insert3(&s->syms, key.data, key.size, value, alloc));
}
return true;
@@ -4596,9 +5052,13 @@
upb_value_getconstptr(v) : NULL;
}
-const upb_filedef *upb_symtab_addfile(
+int upb_symtab_filecount(const upb_symtab *s) {
+ return (int)upb_strtable_count(&s->files);
+}
+
+static const upb_filedef *_upb_symtab_addfile(
upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
- upb_status *status) {
+ const upb_msglayout **layouts, upb_status *status) {
upb_arena *tmparena = upb_arena_new();
upb_strtable addtab;
upb_alloc *alloc = upb_arena_alloc(s->arena);
@@ -4611,6 +5071,7 @@
ctx.alloc = alloc;
ctx.tmp = upb_arena_alloc(tmparena);
ctx.addtab = &addtab;
+ ctx.layouts = layouts;
ctx.status = status;
ok = file &&
@@ -4622,6 +5083,12 @@
return ok ? file : NULL;
}
+const upb_filedef *upb_symtab_addfile(
+ upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
+ upb_status *status) {
+ return _upb_symtab_addfile(s, file_proto, NULL, status);
+}
+
/* Include here since we want most of this file to be stdio-free. */
#include <stdio.h>
@@ -4657,7 +5124,7 @@
goto err;
}
- if (!upb_symtab_addfile(s, file, &status)) goto err;
+ if (!_upb_symtab_addfile(s, file, init->layouts, &status)) goto err;
upb_arena_free(arena);
return true;
@@ -4673,250 +5140,311 @@
#undef CHK_OOM
+#include <string.h>
-static bool is_power_of_two(size_t val) {
- return (val & (val - 1)) == 0;
+
+static char field_size[] = {
+ 0,/* 0 */
+ 8, /* UPB_DESCRIPTOR_TYPE_DOUBLE */
+ 4, /* UPB_DESCRIPTOR_TYPE_FLOAT */
+ 8, /* UPB_DESCRIPTOR_TYPE_INT64 */
+ 8, /* UPB_DESCRIPTOR_TYPE_UINT64 */
+ 4, /* UPB_DESCRIPTOR_TYPE_INT32 */
+ 8, /* UPB_DESCRIPTOR_TYPE_FIXED64 */
+ 4, /* UPB_DESCRIPTOR_TYPE_FIXED32 */
+ 1, /* UPB_DESCRIPTOR_TYPE_BOOL */
+ sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_STRING */
+ sizeof(void*), /* UPB_DESCRIPTOR_TYPE_GROUP */
+ sizeof(void*), /* UPB_DESCRIPTOR_TYPE_MESSAGE */
+ sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_BYTES */
+ 4, /* UPB_DESCRIPTOR_TYPE_UINT32 */
+ 4, /* UPB_DESCRIPTOR_TYPE_ENUM */
+ 4, /* UPB_DESCRIPTOR_TYPE_SFIXED32 */
+ 8, /* UPB_DESCRIPTOR_TYPE_SFIXED64 */
+ 4, /* UPB_DESCRIPTOR_TYPE_SINT32 */
+ 8, /* UPB_DESCRIPTOR_TYPE_SINT64 */
+};
+
+/* Strings/bytes are special-cased in maps. */
+static char _upb_fieldtype_to_mapsize[12] = {
+ 0,
+ 1, /* UPB_TYPE_BOOL */
+ 4, /* UPB_TYPE_FLOAT */
+ 4, /* UPB_TYPE_INT32 */
+ 4, /* UPB_TYPE_UINT32 */
+ 4, /* UPB_TYPE_ENUM */
+ sizeof(void*), /* UPB_TYPE_MESSAGE */
+ 8, /* UPB_TYPE_DOUBLE */
+ 8, /* UPB_TYPE_INT64 */
+ 8, /* UPB_TYPE_UINT64 */
+ 0, /* UPB_TYPE_STRING */
+ 0, /* UPB_TYPE_BYTES */
+};
+
+/** upb_msg *******************************************************************/
+
+upb_msg *upb_msg_new(const upb_msgdef *m, upb_arena *a) {
+ return _upb_msg_new(upb_msgdef_layout(m), a);
}
-/* Align up to the given power of 2. */
-static size_t align_up(size_t val, size_t align) {
- UPB_ASSERT(is_power_of_two(align));
- return (val + align - 1) & ~(align - 1);
+static bool in_oneof(const upb_msglayout_field *field) {
+ return field->presence < 0;
}
-static size_t div_round_up(size_t n, size_t d) {
- return (n + d - 1) / d;
+static uint32_t *oneofcase(const upb_msg *msg,
+ const upb_msglayout_field *field) {
+ UPB_ASSERT(in_oneof(field));
+ return UPB_PTR_AT(msg, -field->presence, uint32_t);
}
-static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
- switch (type) {
- case UPB_TYPE_DOUBLE:
- case UPB_TYPE_INT64:
- case UPB_TYPE_UINT64:
- return 8;
- case UPB_TYPE_ENUM:
- case UPB_TYPE_INT32:
- case UPB_TYPE_UINT32:
- case UPB_TYPE_FLOAT:
- return 4;
- case UPB_TYPE_BOOL:
- return 1;
- case UPB_TYPE_MESSAGE:
- return sizeof(void*);
- case UPB_TYPE_BYTES:
- case UPB_TYPE_STRING:
- return sizeof(upb_strview);
- }
- UPB_UNREACHABLE();
+static upb_msgval _upb_msg_getraw(const upb_msg *msg, const upb_fielddef *f) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ const char *mem = UPB_PTR_AT(msg, field->offset, char);
+ upb_msgval val = {0};
+ int size = upb_fielddef_isseq(f) ? sizeof(void *)
+ : field_size[field->descriptortype];
+ memcpy(&val, mem, size);
+ return val;
}
-static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
- if (upb_fielddef_isseq(f)) {
- return sizeof(void*);
+bool upb_msg_has(const upb_msg *msg, const upb_fielddef *f) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ if (in_oneof(field)) {
+ return *oneofcase(msg, field) == field->number;
+ } else if (field->presence > 0) {
+ uint32_t hasbit = field->presence;
+ return *UPB_PTR_AT(msg, hasbit / 8, uint8_t) & (1 << (hasbit % 8));
} else {
- return upb_msgval_sizeof2(upb_fielddef_type(f));
+ UPB_ASSERT(field->descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
+ field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
+ return _upb_msg_getraw(msg, f).msg_val != NULL;
}
}
+bool upb_msg_hasoneof(const upb_msg *msg, const upb_oneofdef *o) {
+ upb_oneof_iter i;
+ const upb_fielddef *f;
+ const upb_msglayout_field *field;
-/** upb_msglayout *************************************************************/
-
-static void upb_msglayout_free(upb_msglayout *l) {
- upb_gfree(l);
+ upb_oneof_begin(&i, o);
+ if (upb_oneof_done(&i)) return false;
+ f = upb_oneof_iter_field(&i);
+ field = upb_fielddef_layout(f);
+ return *oneofcase(msg, field) != 0;
}
-static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
- size_t ret;
+upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f) {
+ if (!upb_fielddef_haspresence(f) || upb_msg_has(msg, f)) {
+ return _upb_msg_getraw(msg, f);
+ } else {
+ /* TODO(haberman): change upb_fielddef to not require this switch(). */
+ upb_msgval val = {0};
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_ENUM:
+ val.int32_val = upb_fielddef_defaultint32(f);
+ break;
+ case UPB_TYPE_INT64:
+ val.int64_val = upb_fielddef_defaultint64(f);
+ break;
+ case UPB_TYPE_UINT32:
+ val.uint32_val = upb_fielddef_defaultuint32(f);
+ break;
+ case UPB_TYPE_UINT64:
+ val.uint64_val = upb_fielddef_defaultuint64(f);
+ break;
+ case UPB_TYPE_FLOAT:
+ val.float_val = upb_fielddef_defaultfloat(f);
+ break;
+ case UPB_TYPE_DOUBLE:
+ val.double_val = upb_fielddef_defaultdouble(f);
+ break;
+ case UPB_TYPE_BOOL:
+ val.double_val = upb_fielddef_defaultbool(f);
+ break;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ val.str_val.data = upb_fielddef_defaultstr(f, &val.str_val.size);
+ break;
+ case UPB_TYPE_MESSAGE:
+ val.msg_val = NULL;
+ break;
+ }
+ return val;
+ }
+}
- l->size = align_up(l->size, size);
- ret = l->size;
- l->size += size;
+upb_mutmsgval upb_msg_mutable(upb_msg *msg, const upb_fielddef *f,
+ upb_arena *a) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ upb_mutmsgval ret;
+ char *mem = UPB_PTR_AT(msg, field->offset, char);
+ bool wrong_oneof = in_oneof(field) && *oneofcase(msg, field) != field->number;
+
+ memcpy(&ret, mem, sizeof(void*));
+
+ if (a && (!ret.msg || wrong_oneof)) {
+ if (upb_fielddef_ismap(f)) {
+ const upb_msgdef *entry = upb_fielddef_msgsubdef(f);
+ const upb_fielddef *key = upb_msgdef_itof(entry, UPB_MAPENTRY_KEY);
+ const upb_fielddef *value = upb_msgdef_itof(entry, UPB_MAPENTRY_VALUE);
+ ret.map = upb_map_new(a, upb_fielddef_type(key), upb_fielddef_type(value));
+ } else if (upb_fielddef_isseq(f)) {
+ ret.array = upb_array_new(a, upb_fielddef_type(f));
+ } else {
+ UPB_ASSERT(upb_fielddef_issubmsg(f));
+ ret.msg = upb_msg_new(upb_fielddef_msgsubdef(f), a);
+ }
+
+ memcpy(mem, &ret, sizeof(void*));
+
+ if (wrong_oneof) {
+ *oneofcase(msg, field) = field->number;
+ }
+ }
return ret;
}
-static bool upb_msglayout_init(const upb_msgdef *m,
- upb_msglayout *l,
- upb_msgfactory *factory) {
- upb_msg_field_iter it;
- upb_msg_oneof_iter oit;
- size_t hasbit;
- size_t submsg_count = 0;
- const upb_msglayout **submsgs;
- upb_msglayout_field *fields;
-
- for (upb_msg_field_begin(&it, m);
- !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* f = upb_msg_iter_field(&it);
- if (upb_fielddef_issubmsg(f)) {
- submsg_count++;
- }
+void upb_msg_set(upb_msg *msg, const upb_fielddef *f, upb_msgval val,
+ upb_arena *a) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ char *mem = UPB_PTR_AT(msg, field->offset, char);
+ int size = upb_fielddef_isseq(f) ? sizeof(void *)
+ : field_size[field->descriptortype];
+ memcpy(mem, &val, size);
+ if (in_oneof(field)) {
+ *oneofcase(msg, field) = field->number;
}
+}
- memset(l, 0, sizeof(*l));
+bool upb_msg_next(const upb_msg *msg, const upb_msgdef *m,
+ const upb_symtab *ext_pool, const upb_fielddef **out_f,
+ upb_msgval *out_val, size_t *iter) {
+ size_t i = *iter;
+ const upb_msgval zero = {0};
+ const upb_fielddef *f;
+ while ((f = _upb_msgdef_field(m, (int)++i)) != NULL) {
+ upb_msgval val = _upb_msg_getraw(msg, f);
- fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
- submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
+ /* Skip field if unset or empty. */
+ if (upb_fielddef_haspresence(f)) {
+ if (!upb_msg_has(msg, f)) continue;
+ } else {
+ upb_msgval test = val;
+ if (upb_fielddef_isstring(f) && !upb_fielddef_isseq(f)) {
+ /* Clear string pointer, only size matters (ptr could be non-NULL). */
+ test.str_val.data = NULL;
+ }
+ /* Continue if NULL or 0. */
+ if (memcmp(&test, &zero, sizeof(test)) == 0) continue;
- if ((!fields && upb_msgdef_numfields(m)) ||
- (!submsgs && submsg_count)) {
- /* OOM. */
- upb_gfree(fields);
- upb_gfree(submsgs);
+ /* Continue on empty array or map. */
+ if (upb_fielddef_ismap(f)) {
+ if (upb_map_size(test.map_val) == 0) continue;
+ } else if (upb_fielddef_isseq(f)) {
+ if (upb_array_size(test.array_val) == 0) continue;
+ }
+ }
+
+ *out_val = val;
+ *out_f = f;
+ *iter = i;
+ return true;
+ }
+ *iter = i;
+ return false;
+}
+
+/** upb_array *****************************************************************/
+
+upb_array *upb_array_new(upb_arena *a, upb_fieldtype_t type) {
+ return _upb_array_new(a, type);
+}
+
+size_t upb_array_size(const upb_array *arr) {
+ return arr->len;
+}
+
+upb_msgval upb_array_get(const upb_array *arr, size_t i) {
+ upb_msgval ret;
+ const char* data = _upb_array_constptr(arr);
+ int lg2 = arr->data & 7;
+ UPB_ASSERT(i < arr->len);
+ memcpy(&ret, data + (i << lg2), 1 << lg2);
+ return ret;
+}
+
+void upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
+ char* data = _upb_array_ptr(arr);
+ int lg2 = arr->data & 7;
+ UPB_ASSERT(i < arr->len);
+ memcpy(data + (i << lg2), &val, 1 << lg2);
+}
+
+bool upb_array_append(upb_array *arr, upb_msgval val, upb_arena *arena) {
+ if (!_upb_array_realloc(arr, arr->len + 1, arena)) {
return false;
}
-
- l->field_count = upb_msgdef_numfields(m);
- l->fields = fields;
- l->submsgs = submsgs;
-
- /* Allocate data offsets in three stages:
- *
- * 1. hasbits.
- * 2. regular fields.
- * 3. oneof fields.
- *
- * OPT: There is a lot of room for optimization here to minimize the size.
- */
-
- /* Allocate hasbits and set basic field attributes. */
- submsg_count = 0;
- for (upb_msg_field_begin(&it, m), hasbit = 0;
- !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* f = upb_msg_iter_field(&it);
- upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
-
- field->number = upb_fielddef_number(f);
- field->descriptortype = upb_fielddef_descriptortype(f);
- field->label = upb_fielddef_label(f);
-
- if (upb_fielddef_issubmsg(f)) {
- const upb_msglayout *sub_layout =
- upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
- field->submsg_index = submsg_count++;
- submsgs[field->submsg_index] = sub_layout;
- }
-
- if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
- field->presence = (hasbit++);
- } else {
- field->presence = 0;
- }
- }
-
- /* Account for space used by hasbits. */
- l->size = div_round_up(hasbit, 8);
-
- /* Allocate non-oneof fields. */
- for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* f = upb_msg_iter_field(&it);
- size_t field_size = upb_msg_fielddefsize(f);
- size_t index = upb_fielddef_index(f);
-
- if (upb_fielddef_containingoneof(f)) {
- /* Oneofs are handled separately below. */
- continue;
- }
-
- fields[index].offset = upb_msglayout_place(l, field_size);
- }
-
- /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
- * and space for the actual data. */
- for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
- upb_msg_oneof_next(&oit)) {
- const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
- upb_oneof_iter fit;
-
- size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
- size_t field_size = 0;
- uint32_t case_offset;
- uint32_t data_offset;
-
- /* Calculate field size: the max of all field sizes. */
- for (upb_oneof_begin(&fit, o);
- !upb_oneof_done(&fit);
- upb_oneof_next(&fit)) {
- const upb_fielddef* f = upb_oneof_iter_field(&fit);
- field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
- }
-
- /* Align and allocate case offset. */
- case_offset = upb_msglayout_place(l, case_size);
- data_offset = upb_msglayout_place(l, field_size);
-
- for (upb_oneof_begin(&fit, o);
- !upb_oneof_done(&fit);
- upb_oneof_next(&fit)) {
- const upb_fielddef* f = upb_oneof_iter_field(&fit);
- fields[upb_fielddef_index(f)].offset = data_offset;
- fields[upb_fielddef_index(f)].presence = ~case_offset;
- }
- }
-
- /* Size of the entire structure should be a multiple of its greatest
- * alignment. TODO: track overall alignment for real? */
- l->size = align_up(l->size, 8);
-
+ arr->len++;
+ upb_array_set(arr, arr->len - 1, val);
return true;
}
+/* Resizes the array to the given size, reallocating if necessary, and returns a
+ * pointer to the new array elements. */
+bool upb_array_resize(upb_array *arr, size_t size, upb_arena *arena) {
+ return _upb_array_realloc(arr, size, arena);
+}
-/** upb_msgfactory ************************************************************/
+/** upb_map *******************************************************************/
-struct upb_msgfactory {
- const upb_symtab *symtab; /* We own a ref. */
- upb_inttable layouts;
-};
+upb_map *upb_map_new(upb_arena *a, upb_fieldtype_t key_type,
+ upb_fieldtype_t value_type) {
+ return _upb_map_new(a, _upb_fieldtype_to_mapsize[key_type],
+ _upb_fieldtype_to_mapsize[value_type]);
+}
-upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
- upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
+size_t upb_map_size(const upb_map *map) {
+ return _upb_map_size(map);
+}
- ret->symtab = symtab;
- upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
+ return _upb_map_get(map, &key, map->key_size, val, map->val_size);
+}
+bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
+ upb_arena *arena) {
+ return _upb_map_set(map, &key, map->key_size, &val, map->val_size, arena);
+}
+
+bool upb_map_delete(upb_map *map, upb_msgval key) {
+ return _upb_map_delete(map, &key, map->key_size);
+}
+
+bool upb_mapiter_next(const upb_map *map, size_t *iter) {
+ return _upb_map_next(map, iter);
+}
+
+/* Returns the key and value for this entry of the map. */
+upb_msgval upb_mapiter_key(const upb_map *map, size_t iter) {
+ upb_strtable_iter i;
+ upb_msgval ret;
+ i.t = &map->table;
+ i.index = iter;
+ _upb_map_fromkey(upb_strtable_iter_key(&i), &ret, map->key_size);
return ret;
}
-void upb_msgfactory_free(upb_msgfactory *f) {
- upb_inttable_iter i;
- upb_inttable_begin(&i, &f->layouts);
- for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
- upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
- upb_msglayout_free(l);
- }
-
- upb_inttable_uninit(&f->layouts);
- upb_gfree(f);
+upb_msgval upb_mapiter_value(const upb_map *map, size_t iter) {
+ upb_strtable_iter i;
+ upb_msgval ret;
+ i.t = &map->table;
+ i.index = iter;
+ _upb_map_fromvalue(upb_strtable_iter_value(&i), &ret, map->val_size);
+ return ret;
}
-const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
- return f->symtab;
-}
-
-const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
- const upb_msgdef *m) {
- upb_value v;
- UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
- UPB_ASSERT(!upb_msgdef_mapentry(m));
-
- if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
- UPB_ASSERT(upb_value_getptr(v));
- return upb_value_getptr(v);
- } else {
- /* In case of circular dependency, layout has to be inserted first. */
- upb_msglayout *l = upb_gmalloc(sizeof(*l));
- upb_msgfactory *mutable_f = (void*)f;
- upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
- UPB_ASSERT(l);
- if (!upb_msglayout_init(m, l, f)) {
- upb_msglayout_free(l);
- }
- return l;
- }
-}
+/* void upb_mapiter_setvalue(upb_map *map, size_t iter, upb_msgval value); */
/*
** TODO(haberman): it's unclear whether a lot of the consistency checks should
** UPB_ASSERT() or return false.
@@ -5096,7 +5624,8 @@
int extra;
upb_handlers *h;
- extra = sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1);
+ extra =
+ (int)(sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1));
h = upb_calloc(arena, sizeof(*h) + extra);
if (!h) return NULL;
@@ -5497,6 +6026,31 @@
}
return ret;
}
+
+
+#ifdef UPB_MSVC_VSNPRINTF
+/* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
+ * vsnprintf. To support them, missing functions are manually implemented
+ * using the existing secure functions. */
+int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
+ if (!s) {
+ return _vscprintf(format, arg);
+ }
+ int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
+ if (ret < 0) {
+ ret = _vscprintf(format, arg);
+ }
+ return ret;
+}
+
+int msvc_snprintf(char* s, size_t n, const char* format, ...) {
+ va_list arg;
+ va_start(arg, format);
+ int ret = msvc_vsnprintf(s, n, format, arg);
+ va_end(arg);
+ return ret;
+}
+#endif
/*
** protobuf decoder bytecode compiler
**
@@ -5652,7 +6206,9 @@
UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
}
-static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
+static uint32_t pcofs(compiler *c) {
+ return (uint32_t)(c->pc - c->group->bytecode);
+}
/* Defines a local label at the current PC location. All previous forward
* references are updated to point to this location. The location is noted
@@ -5666,7 +6222,7 @@
codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
while (codep) {
int ofs = getofs(*codep);
- setofs(codep, c->pc - codep - instruction_len(*codep));
+ setofs(codep, (int32_t)(c->pc - codep - instruction_len(*codep)));
codep = ofs ? codep + ofs : NULL;
}
c->fwd_labels[label] = EMPTYLABEL;
@@ -5688,7 +6244,7 @@
return 0;
} else if (label < 0) {
/* Backward local label. Relative to the next instruction. */
- uint32_t from = (c->pc + 1) - c->group->bytecode;
+ uint32_t from = (uint32_t)((c->pc + 1) - c->group->bytecode);
return c->back_labels[-label] - from;
} else {
/* Forward local label: prepend to (possibly-empty) linked list. */
@@ -5722,7 +6278,7 @@
case OP_SETDISPATCH: {
uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
put32(c, OP_SETDISPATCH);
- put32(c, ptr);
+ put32(c, (uint32_t)ptr);
if (sizeof(uintptr_t) > sizeof(uint32_t))
put32(c, (uint64_t)ptr >> 32);
break;
@@ -5781,7 +6337,7 @@
case OP_TAG2: {
int label = va_arg(ap, int);
uint64_t tag = va_arg(ap, uint64_t);
- uint32_t instruction = op | (tag << 16);
+ uint32_t instruction = (uint32_t)(op | (tag << 16));
UPB_ASSERT(tag <= 0xffff);
setofs(&instruction, labelref(c, label));
put32(c, instruction);
@@ -5793,7 +6349,7 @@
uint32_t instruction = op | (upb_value_size(tag) << 16);
setofs(&instruction, labelref(c, label));
put32(c, instruction);
- put32(c, tag);
+ put32(c, (uint32_t)tag);
put32(c, tag >> 32);
break;
}
@@ -6406,11 +6962,11 @@
} else {
g = mgroup_new(h, c->lazy);
ok = upb_inttable_insertptr(&c->groups, md, upb_value_constptr(g));
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
}
ok = upb_inttable_lookupptr(&g->methods, h, &v);
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
return upb_value_getptr(v);
}
/*
@@ -6597,7 +7153,7 @@
UPB_ASSERT(d->skip == 0);
if (bytes > delim_remaining(d)) {
seterr(d, "Skipped value extended beyond enclosing submessage.");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
} else if (bufleft(d) >= bytes) {
/* Skipped data is all in current buffer, and more is still available. */
advance(d, bytes);
@@ -6610,7 +7166,7 @@
d->bufstart_ofs += (d->end - d->buf);
d->residual_end = d->residual;
switchtobuf(d, d->residual, d->residual_end);
- return d->size_param + d->skip;
+ return (int32_t)(d->size_param + d->skip);
}
}
@@ -6650,7 +7206,7 @@
/* 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);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
if (d->residual_end > d->residual) {
@@ -6760,9 +7316,9 @@
return DECODE_OK;
} else if (d->data_end == d->delim_end) {
seterr(d, "Submessage ended in the middle of a value or group");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
} else {
- return suspend_save(d);
+ return (int32_t)suspend_save(d);
}
}
@@ -6818,7 +7374,7 @@
}
if(bitpos == 70 && (byte & 0x80)) {
seterr(d, kUnterminatedVarint);
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
return DECODE_OK;
}
@@ -6835,7 +7391,7 @@
upb_decoderet r = upb_vdecode_fast(d->ptr);
if (r.p == NULL) {
seterr(d, kUnterminatedVarint);
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
advance(d, r.p - d->ptr);
*u64 = r.val;
@@ -6859,9 +7415,9 @@
* Right now the size_t -> int32_t can overflow and produce negative values.
*/
*u32 = 0;
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
- *u32 = u64;
+ *u32 = (uint32_t)u64;
return DECODE_OK;
}
@@ -6937,7 +7493,7 @@
UPB_ASSERT(ok < 0);
return DECODE_OK;
} else if (read < bytes && memcmp(&data, &expected, read) == 0) {
- return suspend_save(d);
+ return (int32_t)suspend_save(d);
} else {
return DECODE_MISMATCH;
}
@@ -6957,7 +7513,7 @@
have_tag:
if (fieldnum == 0) {
seterr(d, "Saw invalid field number (0)");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
switch (wire_type) {
@@ -6979,7 +7535,9 @@
break;
}
case UPB_WIRE_TYPE_START_GROUP:
- CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
+ if (!pushtagdelim(d, -fieldnum)) {
+ return (int32_t)upb_pbdecoder_suspend(d);
+ }
break;
case UPB_WIRE_TYPE_END_GROUP:
if (fieldnum == -d->top->groupnum) {
@@ -6988,12 +7546,12 @@
return DECODE_ENDGROUP;
} else {
seterr(d, "Unmatched ENDGROUP tag.");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
break;
default:
seterr(d, "Invalid wire type");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
if (d->top->groupnum >= 0) {
@@ -7165,7 +7723,7 @@
CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, subsink, arg));
)
VMCASE(OP_STARTSTR,
- uint32_t len = delim_remaining(d);
+ uint32_t len = (uint32_t)delim_remaining(d);
upb_pbdecoder_frame *outer = outer_frame(d);
CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
if (len == 0) {
@@ -7173,7 +7731,7 @@
}
)
VMCASE(OP_STRING,
- uint32_t len = curbufleft(d);
+ uint32_t len = (uint32_t)curbufleft(d);
size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
if (n > len) {
if (n > delim_remaining(d)) {
@@ -7379,9 +7937,6 @@
upb_pbdecoder *upb_pbdecoder_create(upb_arena *a, const upb_pbdecodermethod *m,
upb_sink sink, upb_status *status) {
const size_t default_max_nesting = 64;
-#ifndef NDEBUG
- size_t size_before = upb_arena_bytesallocated(a);
-#endif
upb_pbdecoder *d = upb_arena_malloc(a, sizeof(upb_pbdecoder));
if (!d) return NULL;
@@ -7407,9 +7962,6 @@
}
d->top->sink = sink;
- /* If this fails, increase the value in decoder.h. */
- UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
- UPB_PB_DECODER_SIZE);
return d;
}
@@ -7708,7 +8260,7 @@
e->runbegin = e->ptr;
}
- *e->top = e->segptr - e->segbuf;
+ *e->top = (int)(e->segptr - e->segbuf);
e->segptr->seglen = 0;
e->segptr->msglen = 0;
@@ -7994,9 +8546,6 @@
const size_t initial_segbufsize = 16;
/* TODO(haberman): make this configurable. */
const size_t stack_size = 64;
-#ifndef NDEBUG
- const size_t size_before = upb_arena_bytesallocated(arena);
-#endif
upb_pb_encoder *e = upb_arena_malloc(arena, sizeof(upb_pb_encoder));
if (!e) return NULL;
@@ -8021,9 +8570,6 @@
e->subc = output.closure;
e->ptr = e->buf;
- /* If this fails, increase the value in encoder.h. */
- UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
- UPB_PB_ENCODER_SIZE);
return e;
}
@@ -8439,7 +8985,7 @@
return r;
}
-// #line 1 "upb/json/parser.rl"
+#line 1 "upb/json/parser.rl"
/*
** upb::json::Parser (upb_json_parser)
**
@@ -8828,7 +9374,7 @@
upb_handlertype_t type) {
upb_selector_t sel;
bool ok = upb_handlers_getselector(p->top->f, type, &sel);
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
return sel;
}
@@ -8853,7 +9399,7 @@
const upb_json_parsermethod *method;
ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
method = upb_value_getconstptr(v);
frame->name_table = &method->name_table;
@@ -9172,7 +9718,9 @@
/* Note: this invalidates the accumulate buffer! Call only after reading its
* contents. */
static void multipart_end(upb_json_parser *p) {
- UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
+ /* This is false sometimes. Probably a bug of some sort, but this code is
+ * intended for deletion soon. */
+ /* UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE); */
p->multipart_state = MULTIPART_INACTIVE;
accumulate_clear(p);
}
@@ -9407,7 +9955,7 @@
} else if (val > INT32_MAX || val < INT32_MIN) {
return false;
} else {
- upb_sink_putint32(p->top->sink, parser_getsel(p), val);
+ upb_sink_putint32(p->top->sink, parser_getsel(p), (int32_t)val);
return true;
}
}
@@ -9418,7 +9966,7 @@
} else if (val > UINT32_MAX || errno == ERANGE) {
return false;
} else {
- upb_sink_putuint32(p->top->sink, parser_getsel(p), val);
+ upb_sink_putuint32(p->top->sink, parser_getsel(p), (uint32_t)val);
return true;
}
}
@@ -9807,7 +10355,12 @@
upb_selector_t sel = parser_getsel(p);
upb_sink_putint32(p->top->sink, sel, int_val);
} else {
- upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
+ if (p->ignore_json_unknown) {
+ ok = true;
+ /* TODO(teboring): Should also clean this field. */
+ } else {
+ upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
+ }
}
break;
@@ -10458,7 +11011,7 @@
/* send ENDSUBMSG in repeated-field-of-mapentries frame. */
p->top--;
ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
}
@@ -11012,11 +11565,11 @@
* final state once, when the closing '"' is seen. */
-// #line 2780 "upb/json/parser.rl"
+#line 2787 "upb/json/parser.rl"
-// #line 2583 "upb/json/parser.c"
+#line 2590 "upb/json/parser.c"
static const char _json_actions[] = {
0, 1, 0, 1, 1, 1, 3, 1,
4, 1, 6, 1, 7, 1, 8, 1,
@@ -11271,7 +11824,7 @@
static const int json_en_main = 1;
-// #line 2783 "upb/json/parser.rl"
+#line 2790 "upb/json/parser.rl"
size_t parse(void *closure, const void *hd, const char *buf, size_t size,
const upb_bufhandle *handle) {
@@ -11294,7 +11847,7 @@
capture_resume(parser, buf);
-// #line 2861 "upb/json/parser.c"
+#line 2868 "upb/json/parser.c"
{
int _klen;
unsigned int _trans;
@@ -11369,147 +11922,147 @@
switch ( *_acts++ )
{
case 1:
-// #line 2588 "upb/json/parser.rl"
+#line 2595 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 2:
-// #line 2590 "upb/json/parser.rl"
+#line 2597 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 23;goto _again;} }
break;
case 3:
-// #line 2594 "upb/json/parser.rl"
+#line 2601 "upb/json/parser.rl"
{ start_text(parser, p); }
break;
case 4:
-// #line 2595 "upb/json/parser.rl"
+#line 2602 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_text(parser, p)); }
break;
case 5:
-// #line 2601 "upb/json/parser.rl"
+#line 2608 "upb/json/parser.rl"
{ start_hex(parser); }
break;
case 6:
-// #line 2602 "upb/json/parser.rl"
+#line 2609 "upb/json/parser.rl"
{ hexdigit(parser, p); }
break;
case 7:
-// #line 2603 "upb/json/parser.rl"
+#line 2610 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_hex(parser)); }
break;
case 8:
-// #line 2609 "upb/json/parser.rl"
+#line 2616 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(escape(parser, p)); }
break;
case 9:
-// #line 2615 "upb/json/parser.rl"
+#line 2622 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 10:
-// #line 2620 "upb/json/parser.rl"
+#line 2627 "upb/json/parser.rl"
{ start_year(parser, p); }
break;
case 11:
-// #line 2621 "upb/json/parser.rl"
+#line 2628 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_year(parser, p)); }
break;
case 12:
-// #line 2625 "upb/json/parser.rl"
+#line 2632 "upb/json/parser.rl"
{ start_month(parser, p); }
break;
case 13:
-// #line 2626 "upb/json/parser.rl"
+#line 2633 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_month(parser, p)); }
break;
case 14:
-// #line 2630 "upb/json/parser.rl"
+#line 2637 "upb/json/parser.rl"
{ start_day(parser, p); }
break;
case 15:
-// #line 2631 "upb/json/parser.rl"
+#line 2638 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_day(parser, p)); }
break;
case 16:
-// #line 2635 "upb/json/parser.rl"
+#line 2642 "upb/json/parser.rl"
{ start_hour(parser, p); }
break;
case 17:
-// #line 2636 "upb/json/parser.rl"
+#line 2643 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_hour(parser, p)); }
break;
case 18:
-// #line 2640 "upb/json/parser.rl"
+#line 2647 "upb/json/parser.rl"
{ start_minute(parser, p); }
break;
case 19:
-// #line 2641 "upb/json/parser.rl"
+#line 2648 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_minute(parser, p)); }
break;
case 20:
-// #line 2645 "upb/json/parser.rl"
+#line 2652 "upb/json/parser.rl"
{ start_second(parser, p); }
break;
case 21:
-// #line 2646 "upb/json/parser.rl"
+#line 2653 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_second(parser, p)); }
break;
case 22:
-// #line 2651 "upb/json/parser.rl"
+#line 2658 "upb/json/parser.rl"
{ start_duration_base(parser, p); }
break;
case 23:
-// #line 2652 "upb/json/parser.rl"
+#line 2659 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_duration_base(parser, p)); }
break;
case 24:
-// #line 2654 "upb/json/parser.rl"
+#line 2661 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 25:
-// #line 2659 "upb/json/parser.rl"
+#line 2666 "upb/json/parser.rl"
{ start_timestamp_base(parser); }
break;
case 26:
-// #line 2661 "upb/json/parser.rl"
+#line 2668 "upb/json/parser.rl"
{ start_timestamp_fraction(parser, p); }
break;
case 27:
-// #line 2662 "upb/json/parser.rl"
+#line 2669 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
break;
case 28:
-// #line 2664 "upb/json/parser.rl"
+#line 2671 "upb/json/parser.rl"
{ start_timestamp_zone(parser, p); }
break;
case 29:
-// #line 2665 "upb/json/parser.rl"
+#line 2672 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
break;
case 30:
-// #line 2667 "upb/json/parser.rl"
+#line 2674 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 31:
-// #line 2672 "upb/json/parser.rl"
+#line 2679 "upb/json/parser.rl"
{ start_fieldmask_path_text(parser, p); }
break;
case 32:
-// #line 2673 "upb/json/parser.rl"
+#line 2680 "upb/json/parser.rl"
{ end_fieldmask_path_text(parser, p); }
break;
case 33:
-// #line 2678 "upb/json/parser.rl"
+#line 2685 "upb/json/parser.rl"
{ start_fieldmask_path(parser); }
break;
case 34:
-// #line 2679 "upb/json/parser.rl"
+#line 2686 "upb/json/parser.rl"
{ end_fieldmask_path(parser); }
break;
case 35:
-// #line 2685 "upb/json/parser.rl"
+#line 2692 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 36:
-// #line 2690 "upb/json/parser.rl"
+#line 2697 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
{stack[top++] = cs; cs = 47;goto _again;}
@@ -11523,11 +12076,11 @@
}
break;
case 37:
-// #line 2703 "upb/json/parser.rl"
+#line 2710 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 78;goto _again;} }
break;
case 38:
-// #line 2708 "upb/json/parser.rl"
+#line 2715 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
start_any_member(parser, p);
@@ -11537,11 +12090,11 @@
}
break;
case 39:
-// #line 2715 "upb/json/parser.rl"
+#line 2722 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_membername(parser)); }
break;
case 40:
-// #line 2718 "upb/json/parser.rl"
+#line 2725 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
end_any_member(parser, p);
@@ -11551,7 +12104,7 @@
}
break;
case 41:
-// #line 2729 "upb/json/parser.rl"
+#line 2736 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
start_any_object(parser, p);
@@ -11561,7 +12114,7 @@
}
break;
case 42:
-// #line 2738 "upb/json/parser.rl"
+#line 2745 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
CHECK_RETURN_TOP(end_any_object(parser, p));
@@ -11571,54 +12124,54 @@
}
break;
case 43:
-// #line 2750 "upb/json/parser.rl"
+#line 2757 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_array(parser)); }
break;
case 44:
-// #line 2754 "upb/json/parser.rl"
+#line 2761 "upb/json/parser.rl"
{ end_array(parser); }
break;
case 45:
-// #line 2759 "upb/json/parser.rl"
+#line 2766 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_number(parser, p)); }
break;
case 46:
-// #line 2760 "upb/json/parser.rl"
+#line 2767 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 47:
-// #line 2762 "upb/json/parser.rl"
+#line 2769 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_stringval(parser)); }
break;
case 48:
-// #line 2763 "upb/json/parser.rl"
+#line 2770 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_stringval(parser)); }
break;
case 49:
-// #line 2765 "upb/json/parser.rl"
+#line 2772 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, true)); }
break;
case 50:
-// #line 2767 "upb/json/parser.rl"
+#line 2774 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, false)); }
break;
case 51:
-// #line 2769 "upb/json/parser.rl"
+#line 2776 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_null(parser)); }
break;
case 52:
-// #line 2771 "upb/json/parser.rl"
+#line 2778 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_subobject_full(parser)); }
break;
case 53:
-// #line 2772 "upb/json/parser.rl"
+#line 2779 "upb/json/parser.rl"
{ end_subobject_full(parser); }
break;
case 54:
-// #line 2777 "upb/json/parser.rl"
+#line 2784 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
-// #line 3185 "upb/json/parser.c"
+#line 3192 "upb/json/parser.c"
}
}
@@ -11635,32 +12188,32 @@
while ( __nacts-- > 0 ) {
switch ( *__acts++ ) {
case 0:
-// #line 2586 "upb/json/parser.rl"
+#line 2593 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; if ( p == pe )
goto _test_eof;
goto _again;} }
break;
case 46:
-// #line 2760 "upb/json/parser.rl"
+#line 2767 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 49:
-// #line 2765 "upb/json/parser.rl"
+#line 2772 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, true)); }
break;
case 50:
-// #line 2767 "upb/json/parser.rl"
+#line 2774 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, false)); }
break;
case 51:
-// #line 2769 "upb/json/parser.rl"
+#line 2776 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_null(parser)); }
break;
case 53:
-// #line 2772 "upb/json/parser.rl"
+#line 2779 "upb/json/parser.rl"
{ end_subobject_full(parser); }
break;
-// #line 3227 "upb/json/parser.c"
+#line 3234 "upb/json/parser.c"
}
}
}
@@ -11668,7 +12221,7 @@
_out: {}
}
-// #line 2805 "upb/json/parser.rl"
+#line 2812 "upb/json/parser.rl"
if (p != pe) {
upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
@@ -11711,13 +12264,13 @@
/* Emit Ragel initialization of the parser. */
-// #line 3278 "upb/json/parser.c"
+#line 3285 "upb/json/parser.c"
{
cs = json_start;
top = 0;
}
-// #line 2847 "upb/json/parser.rl"
+#line 2854 "upb/json/parser.rl"
p->current_state = cs;
p->parser_top = top;
accumulate_clear(p);
@@ -11748,15 +12301,13 @@
upb_msg_field_next(&i)) {
const upb_fielddef *f = upb_msg_iter_field(&i);
upb_value v = upb_value_constptr(f);
- char *buf;
+ const char *name;
/* Add an entry for the JSON name. */
- size_t len = upb_fielddef_getjsonname(f, NULL, 0);
- buf = upb_malloc(alloc, len);
- upb_fielddef_getjsonname(f, buf, len);
- upb_strtable_insert3(&m->name_table, buf, strlen(buf), v, alloc);
+ name = upb_fielddef_jsonname(f);
+ upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
- if (strcmp(buf, upb_fielddef_name(f)) != 0) {
+ if (strcmp(name, 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). */
@@ -11776,9 +12327,6 @@
upb_sink output,
upb_status *status,
bool ignore_json_unknown) {
-#ifndef NDEBUG
- const size_t size_before = upb_arena_bytesallocated(arena);
-#endif
upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
if (!p) return false;
@@ -11805,10 +12353,6 @@
p->ignore_json_unknown = ignore_json_unknown;
- /* If this fails, uncomment and increase the value in parser.h. */
- /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
- UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
- UPB_JSON_PARSER_SIZE);
return p;
}
@@ -11882,6 +12426,7 @@
#include <ctype.h>
+#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
@@ -11939,12 +12484,8 @@
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 */
+ ret->ptr = upb_gstrdup(upb_fielddef_jsonname(f));
+ ret->len = strlen(ret->ptr);
}
upb_handlers_addcleanup(h, ret, freestrpc);
@@ -11963,7 +12504,7 @@
/* ------------ JSON string printing: values, maps, arrays ------------------ */
static void print_data(
- upb_json_printer *p, const char *buf, unsigned int len) {
+ upb_json_printer *p, const char *buf, size_t 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(n == len);
@@ -12003,7 +12544,7 @@
/* Write a properly escaped string chunk. The surrounding quotes are *not*
* printed; this is so that the caller has the option of emitting the string
* content in chunks. */
-static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
+static void putstring(upb_json_printer *p, const char *buf, size_t len) {
const char* unescaped_run = NULL;
unsigned int i;
for (i = 0; i < len; i++) {
@@ -12083,28 +12624,26 @@
return n;
}
-static size_t fmt_int64_as_number(long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "%lld", val);
+static size_t fmt_int64_as_number(int64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "%" PRId64, val);
CHKLENGTH(n > 0 && n < length);
return n;
}
-static size_t fmt_uint64_as_number(
- unsigned long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "%llu", val);
+static size_t fmt_uint64_as_number(uint64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "%" PRIu64, val);
CHKLENGTH(n > 0 && n < length);
return n;
}
-static size_t fmt_int64_as_string(long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "\"%lld\"", val);
+static size_t fmt_int64_as_string(int64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "\"%" PRId64 "\"", val);
CHKLENGTH(n > 0 && n < length);
return n;
}
-static size_t fmt_uint64_as_string(
- unsigned long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "\"%llu\"", val);
+static size_t fmt_uint64_as_string(uint64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "\"%" PRIu64 "\"", val);
CHKLENGTH(n > 0 && n < length);
return n;
}
@@ -13247,10 +13786,6 @@
upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
upb_bytessink output) {
-#ifndef NDEBUG
- size_t size_before = upb_arena_bytesallocated(a);
-#endif
-
upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
if (!p) return NULL;
@@ -13260,9 +13795,6 @@
p->seconds = 0;
p->nanos = 0;
- /* If this fails, increase the value in printer.h. */
- UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
- UPB_JSON_PRINTER_SIZE);
return p;
}
@@ -13281,17 +13813,23 @@
}
/* See port_def.inc. This should #undef all macros #defined there. */
+#undef UPB_MAPTYPE_STRING
#undef UPB_SIZE
-#undef UPB_FIELD_AT
+#undef UPB_PTR_AT
#undef UPB_READ_ONEOF
#undef UPB_WRITE_ONEOF
#undef UPB_INLINE
+#undef UPB_ALIGN_UP
+#undef UPB_ALIGN_DOWN
+#undef UPB_ALIGN_MALLOC
+#undef UPB_ALIGN_OF
#undef UPB_FORCEINLINE
#undef UPB_NOINLINE
#undef UPB_NORETURN
#undef UPB_MAX
#undef UPB_MIN
#undef UPB_UNUSED
+#undef UPB_ASSUME
#undef UPB_ASSERT
#undef UPB_ASSERT_DEBUGVAR
#undef UPB_UNREACHABLE
diff --git a/php/ext/google/protobuf/upb.h b/php/ext/google/protobuf/upb.h
index 1b0075c..179e498 100644
--- a/php/ext/google/protobuf/upb.h
+++ b/php/ext/google/protobuf/upb.h
@@ -28,9 +28,8 @@
*
* This file is private and must not be included by users!
*/
-#ifndef UINTPTR_MAX
-#error must include stdint.h first
-#endif
+#include <stdint.h>
+#include <stddef.h>
#if UINTPTR_MAX == 0xffffffff
#define UPB_SIZE(size32, size64) size32
@@ -38,17 +37,21 @@
#define UPB_SIZE(size32, size64) size64
#endif
-#define UPB_FIELD_AT(msg, fieldtype, offset) \
- *(fieldtype*)((const char*)(msg) + offset)
+/* If we always read/write as a consistent type to each address, this shouldn't
+ * violate aliasing.
+ */
+#define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
#define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
- UPB_FIELD_AT(msg, int, case_offset) == case_val \
- ? UPB_FIELD_AT(msg, fieldtype, offset) \
+ *UPB_PTR_AT(msg, case_offset, int) == case_val \
+ ? *UPB_PTR_AT(msg, offset, fieldtype) \
: default
#define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
- UPB_FIELD_AT(msg, int, case_offset) = case_val; \
- UPB_FIELD_AT(msg, fieldtype, offset) = value;
+ *UPB_PTR_AT(msg, case_offset, int) = case_val; \
+ *UPB_PTR_AT(msg, offset, fieldtype) = value;
+
+#define UPB_MAPTYPE_STRING 0
/* UPB_INLINE: inline if possible, emit standalone code if required. */
#ifdef __cplusplus
@@ -59,6 +62,11 @@
#define UPB_INLINE static
#endif
+#define UPB_ALIGN_UP(size, align) (((size) + (align) - 1) / (align) * (align))
+#define UPB_ALIGN_DOWN(size, align) ((size) / (align) * (align))
+#define UPB_ALIGN_MALLOC(size) UPB_ALIGN_UP(size, 16)
+#define UPB_ALIGN_OF(type) offsetof (struct { char c; type member; }, member)
+
/* Hints to the compiler about likely/unlikely branches. */
#if defined (__GNUC__) || defined(__clang__)
#define UPB_LIKELY(x) __builtin_expect((x),1)
@@ -133,6 +141,18 @@
#define UPB_UNUSED(var) (void)var
+/* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
+ */
+#ifdef NDEBUG
+#ifdef __GNUC__
+#define UPB_ASSUME(expr) if (!(expr)) __builtin_unreachable()
+#else
+#define UPB_ASSUME(expr) do {} if (false && (expr))
+#endif
+#else
+#define UPB_ASSUME(expr) assert(expr)
+#endif
+
/* UPB_ASSERT(): in release mode, we use the expression without letting it be
* evaluated. This prevents "unused variable" warnings. */
#ifdef NDEBUG
@@ -159,10 +179,51 @@
#define UPB_INFINITY (1.0 / 0.0)
#endif
/*
-** This file contains shared definitions that are widely used across upb.
+** upb_decode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_DECODE_H_
+#define UPB_DECODE_H_
+
+/*
+** Our memory representation for parsing tables and messages themselves.
+** Functions in this file are used by generated code and possibly reflection.
**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
+** The definitions in this file are internal to upb.
+**/
+
+#ifndef UPB_MSG_H_
+#define UPB_MSG_H_
+
+#include <stdint.h>
+#include <string.h>
+
+/*
+** upb_table
+**
+** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
+** This file defines very fast int->upb_value (inttable) and string->upb_value
+** (strtable) hash tables.
+**
+** The table uses chained scatter with Brent's variation (inspired by the Lua
+** implementation of hash tables). The hash function for strings is Austin
+** Appleby's "MurmurHash."
+**
+** The inttable uses uintptr_t as its key, which guarantees it can be used to
+** store pointers or integers of at least 32 bits (upb isn't really useful on
+** systems where sizeof(void*) < 4).
+**
+** The table must be homogenous (all values of the same type). In debug
+** mode, we check this on insert and lookup.
+*/
+
+#ifndef UPB_TABLE_H_
+#define UPB_TABLE_H_
+
+#include <stdint.h>
+#include <string.h>
+/*
+** This file contains shared definitions that are widely used across upb.
*/
#ifndef UPB_H_
@@ -175,23 +236,13 @@
#include <stdint.h>
#include <string.h>
-#ifdef __cplusplus
-#include <memory>
-namespace upb {
-class Arena;
-class Status;
-template <int N> class InlinedArena;
-}
-#endif
+#ifdef __cplusplus
+extern "C" {
+#endif
/* upb_status *****************************************************************/
-/* 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. */
-
-/* The maximum length of an error message before it will get truncated. */
#define UPB_STATUS_MAX_MESSAGE 127
typedef struct {
@@ -199,59 +250,15 @@
char msg[UPB_STATUS_MAX_MESSAGE]; /* Error message; NULL-terminated. */
} upb_status;
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_status_errmsg(const upb_status *status);
bool upb_ok(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. */
+/* These are no-op if |status| is NULL. */
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);
-UPB_INLINE void upb_status_setoom(upb_status *status) {
- upb_status_seterrmsg(status, "out of memory");
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-
-class upb::Status {
- public:
- Status() { upb_status_clear(&status_); }
-
- upb_status* ptr() { return &status_; }
-
- /* Returns true if there is no error. */
- bool ok() const { return upb_ok(&status_); }
-
- /* Guaranteed to be NULL-terminated. */
- const char *error_message() const { return upb_status_errmsg(&status_); }
-
- /* The error message will be truncated if it is longer than
- * UPB_STATUS_MAX_MESSAGE-4. */
- void SetErrorMessage(const char *msg) { upb_status_seterrmsg(&status_, msg); }
- void SetFormattedErrorMessage(const char *fmt, ...) {
- va_list args;
- va_start(args, fmt);
- upb_status_vseterrf(&status_, fmt, args);
- va_end(args);
- }
-
- /* Resets the status to a successful state with no message. */
- void Clear() { upb_status_clear(&status_); }
-
- private:
- upb_status status_;
-};
-
-#endif /* __cplusplus */
-
/** upb_strview ************************************************************/
typedef struct {
@@ -318,16 +325,8 @@
/* The global allocator used by upb. Uses the standard malloc()/free(). */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
extern upb_alloc upb_alloc_global;
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
/* Functions that hard-code the global malloc.
*
* We still get benefit because we can put custom logic into our global
@@ -364,9 +363,14 @@
struct upb_arena;
typedef struct upb_arena upb_arena;
-#ifdef __cplusplus
-extern "C" {
-#endif
+typedef struct {
+ /* We implement the allocator interface.
+ * This must be the first member of upb_arena!
+ * TODO(haberman): remove once handlers are gone. */
+ upb_alloc alloc;
+
+ char *ptr, *end;
+} _upb_arena_head;
/* Creates an arena from the given initial block (if any -- n may be 0).
* Additional blocks will be allocated from |alloc|. If |alloc| is NULL, this
@@ -374,83 +378,40 @@
upb_arena *upb_arena_init(void *mem, size_t n, upb_alloc *alloc);
void upb_arena_free(upb_arena *a);
bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func);
-size_t upb_arena_bytesallocated(const upb_arena *a);
+void upb_arena_fuse(upb_arena *a, upb_arena *b);
+void *_upb_arena_slowmalloc(upb_arena *a, size_t size);
UPB_INLINE upb_alloc *upb_arena_alloc(upb_arena *a) { return (upb_alloc*)a; }
-/* Convenience wrappers around upb_alloc functions. */
-
UPB_INLINE void *upb_arena_malloc(upb_arena *a, size_t size) {
- return upb_malloc(upb_arena_alloc(a), size);
+ _upb_arena_head *h = (_upb_arena_head*)a;
+ void* ret;
+ size = UPB_ALIGN_MALLOC(size);
+
+ if (UPB_UNLIKELY((size_t)(h->end - h->ptr) < size)) {
+ return _upb_arena_slowmalloc(a, size);
+ }
+
+ ret = h->ptr;
+ h->ptr += size;
+ return ret;
}
UPB_INLINE void *upb_arena_realloc(upb_arena *a, void *ptr, size_t oldsize,
size_t size) {
- return upb_realloc(upb_arena_alloc(a), ptr, oldsize, size);
+ void *ret = upb_arena_malloc(a, size);
+
+ if (ret && oldsize > 0) {
+ memcpy(ret, ptr, oldsize);
+ }
+
+ return ret;
}
UPB_INLINE upb_arena *upb_arena_new(void) {
return upb_arena_init(NULL, 0, &upb_alloc_global);
}
-#ifdef __cplusplus
-} /* extern "C" */
-
-class upb::Arena {
- public:
- /* A simple arena with no initial memory block and the default allocator. */
- Arena() : ptr_(upb_arena_new(), upb_arena_free) {}
-
- upb_arena* ptr() { return ptr_.get(); }
-
- /* 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. */
- upb_alloc *allocator() { return upb_arena_alloc(ptr_.get()); }
-
- /* Add a cleanup function to run when the arena is destroyed.
- * Returns false on out-of-memory. */
- bool AddCleanup(void *ud, upb_cleanup_func* func) {
- return upb_arena_addcleanup(ptr_.get(), ud, func);
- }
-
- /* Total number of bytes that have been allocated. It is undefined what
- * Realloc() does to &arena_ counter. */
- size_t BytesAllocated() const { return upb_arena_bytesallocated(ptr_.get()); }
-
- private:
- std::unique_ptr<upb_arena, decltype(&upb_arena_free)> ptr_;
-};
-
-#endif
-
-/* upb::InlinedArena **********************************************************/
-
-/* upb::InlinedArena seeds the 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
-
-template <int N> class upb::InlinedArena : public upb::Arena {
- public:
- InlinedArena() : ptr_(upb_arena_new(&initial_block_, N, &upb_alloc_global)) {}
-
- upb_arena* ptr() { return ptr_.get(); }
-
- private:
- InlinedArena(const InlinedArena*) = delete;
- InlinedArena& operator=(const InlinedArena*) = delete;
-
- std::unique_ptr<upb_arena, decltype(&upb_arena_free)> ptr_;
- char initial_block_[N];
-};
-
-#endif /* __cplusplus */
-
/* Constants ******************************************************************/
/* Generic function type. */
@@ -470,21 +431,17 @@
* types defined in descriptor.proto, which gives INT32 and SINT32 separate
* types (we distinguish the two with the "integer encoding" enum below). */
typedef enum {
- /* Types stored in 1 byte. */
UPB_TYPE_BOOL = 1,
- /* Types stored in 4 bytes. */
UPB_TYPE_FLOAT = 2,
UPB_TYPE_INT32 = 3,
UPB_TYPE_UINT32 = 4,
UPB_TYPE_ENUM = 5, /* Enum values are int32. */
- /* Types stored as pointers (probably 4 or 8 bytes). */
- UPB_TYPE_STRING = 6,
- UPB_TYPE_BYTES = 7,
- UPB_TYPE_MESSAGE = 8,
- /* Types stored as 8 bytes. */
- UPB_TYPE_DOUBLE = 9,
- UPB_TYPE_INT64 = 10,
- UPB_TYPE_UINT64 = 11
+ UPB_TYPE_MESSAGE = 6,
+ UPB_TYPE_DOUBLE = 7,
+ UPB_TYPE_INT64 = 8,
+ UPB_TYPE_UINT64 = 9,
+ UPB_TYPE_STRING = 10,
+ UPB_TYPE_BYTES = 11
} upb_fieldtype_t;
/* The repeated-ness of each field; this matches descriptor.proto. */
@@ -496,6 +453,7 @@
/* Descriptor types, as defined in descriptor.proto. */
typedef enum {
+ /* Old (long) names. TODO(haberman): remove */
UPB_DESCRIPTOR_TYPE_DOUBLE = 1,
UPB_DESCRIPTOR_TYPE_FLOAT = 2,
UPB_DESCRIPTOR_TYPE_INT64 = 3,
@@ -513,145 +471,36 @@
UPB_DESCRIPTOR_TYPE_SFIXED32 = 15,
UPB_DESCRIPTOR_TYPE_SFIXED64 = 16,
UPB_DESCRIPTOR_TYPE_SINT32 = 17,
- UPB_DESCRIPTOR_TYPE_SINT64 = 18
+ UPB_DESCRIPTOR_TYPE_SINT64 = 18,
+
+ UPB_DTYPE_DOUBLE = 1,
+ UPB_DTYPE_FLOAT = 2,
+ UPB_DTYPE_INT64 = 3,
+ UPB_DTYPE_UINT64 = 4,
+ UPB_DTYPE_INT32 = 5,
+ UPB_DTYPE_FIXED64 = 6,
+ UPB_DTYPE_FIXED32 = 7,
+ UPB_DTYPE_BOOL = 8,
+ UPB_DTYPE_STRING = 9,
+ UPB_DTYPE_GROUP = 10,
+ UPB_DTYPE_MESSAGE = 11,
+ UPB_DTYPE_BYTES = 12,
+ UPB_DTYPE_UINT32 = 13,
+ UPB_DTYPE_ENUM = 14,
+ UPB_DTYPE_SFIXED32 = 15,
+ UPB_DTYPE_SFIXED64 = 16,
+ UPB_DTYPE_SINT32 = 17,
+ UPB_DTYPE_SINT64 = 18
} upb_descriptortype_t;
-extern const uint8_t upb_desctype_to_fieldtype[];
+#define UPB_MAP_BEGIN -1
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
#endif /* UPB_H_ */
-/*
-** upb_decode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_DECODE_H_
-#define UPB_DECODE_H_
-
-/*
-** Data structures for message tables, used for parsing and serialization.
-** This are much lighter-weight than full reflection, but they are do not
-** have enough information to convert to text format, JSON, etc.
-**
-** The definitions in this file are internal to upb.
-**/
-
-#ifndef UPB_MSG_H_
-#define UPB_MSG_H_
-
-#include <stdint.h>
-#include <string.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef void upb_msg;
-
-/** upb_msglayout *************************************************************/
-
-/* upb_msglayout represents the memory layout of a given upb_msgdef. The
- * members are public so generated code can initialize them, but users MUST NOT
- * read or write any of its members. */
-
-typedef struct {
- uint32_t number;
- uint16_t offset;
- int16_t presence; /* If >0, hasbit_index+1. If <0, oneof_index+1. */
- uint16_t submsg_index; /* undefined if descriptortype != MESSAGE or GROUP. */
- uint8_t descriptortype;
- uint8_t label;
-} upb_msglayout_field;
-
-typedef struct upb_msglayout {
- const struct upb_msglayout *const* submsgs;
- const upb_msglayout_field *fields;
- /* Must be aligned to sizeof(void*). Doesn't include internal members like
- * unknown fields, extension dict, pointer to msglayout, etc. */
- uint16_t size;
- uint16_t field_count;
- bool extendable;
-} upb_msglayout;
-
-/** Message internal representation *******************************************/
-
-/* Our internal representation for repeated fields. */
-typedef struct {
- void *data; /* Each element is element_size. */
- size_t len; /* Measured in elements. */
- size_t size; /* Measured in elements. */
-} upb_array;
-
-upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a);
-upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a);
-
-void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
- upb_arena *arena);
-const char *upb_msg_getunknown(const upb_msg *msg, size_t *len);
-
-upb_array *upb_array_new(upb_arena *a);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_MSG_H_ */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-bool upb_decode(const char *buf, size_t size, upb_msg *msg,
- const upb_msglayout *l, upb_arena *arena);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_DECODE_H_ */
-/*
-** upb_encode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_ENCODE_H_
-#define UPB_ENCODE_H_
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-char *upb_encode(const void *msg, const upb_msglayout *l, upb_arena *arena,
- size_t *size);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_ENCODE_H_ */
-/*
-** upb_table
-**
-** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
-** This file defines very fast int->upb_value (inttable) and string->upb_value
-** (strtable) hash tables.
-**
-** The table uses chained scatter with Brent's variation (inspired by the Lua
-** implementation of hash tables). The hash function for strings is Austin
-** Appleby's "MurmurHash."
-**
-** The inttable uses uintptr_t as its key, which guarantees it can be used to
-** store pointers or integers of at least 32 bits (upb isn't really useful on
-** systems where sizeof(void*) < 4).
-**
-** The table must be homogenous (all values of the same type). In debug
-** mode, we check this on insert and lookup.
-*/
-
-#ifndef UPB_TABLE_H_
-#define UPB_TABLE_H_
-
-#include <stdint.h>
-#include <string.h>
#ifdef __cplusplus
@@ -680,19 +529,8 @@
typedef struct {
uint64_t val;
-#ifndef NDEBUG
- /* In debug mode we carry the value type around also so we can check accesses
- * to be sure the right member is being read. */
- upb_ctype_t ctype;
-#endif
} upb_value;
-#ifdef NDEBUG
-#define SET_TYPE(dest, val) UPB_UNUSED(val)
-#else
-#define SET_TYPE(dest, val) dest = val
-#endif
-
/* Like strdup(), which isn't always available since it's not ANSI C. */
char *upb_strdup(const char *s, upb_alloc *a);
/* Variant that works with a length-delimited rather than NULL-delimited string,
@@ -703,15 +541,13 @@
return upb_strdup(s, &upb_alloc_global);
}
-UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val,
- upb_ctype_t ctype) {
+UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val) {
v->val = val;
- SET_TYPE(v->ctype, ctype);
}
-UPB_INLINE upb_value _upb_value_val(uint64_t val, upb_ctype_t ctype) {
+UPB_INLINE upb_value _upb_value_val(uint64_t val) {
upb_value ret;
- _upb_value_setval(&ret, val, ctype);
+ _upb_value_setval(&ret, val);
return ret;
}
@@ -726,7 +562,6 @@
#define FUNCS(name, membername, type_t, converter, proto_type) \
UPB_INLINE void upb_value_set ## name(upb_value *val, type_t cval) { \
val->val = (converter)cval; \
- SET_TYPE(val->ctype, proto_type); \
} \
UPB_INLINE upb_value upb_value_ ## name(type_t val) { \
upb_value ret; \
@@ -734,7 +569,6 @@
return ret; \
} \
UPB_INLINE type_t upb_value_get ## name(upb_value val) { \
- UPB_ASSERT_DEBUGVAR(val.ctype == proto_type); \
return (type_t)(converter)val.val; \
}
@@ -752,12 +586,10 @@
UPB_INLINE void upb_value_setfloat(upb_value *val, float cval) {
memcpy(&val->val, &cval, sizeof(cval));
- SET_TYPE(val->ctype, UPB_CTYPE_FLOAT);
}
UPB_INLINE void upb_value_setdouble(upb_value *val, double cval) {
memcpy(&val->val, &cval, sizeof(cval));
- SET_TYPE(val->ctype, UPB_CTYPE_DOUBLE);
}
UPB_INLINE upb_value upb_value_float(float cval) {
@@ -801,7 +633,6 @@
#define UPB_TABVALUE_EMPTY_INIT {-1}
-
/* upb_table ******************************************************************/
typedef struct _upb_tabent {
@@ -818,7 +649,6 @@
typedef struct {
size_t count; /* Number of entries in the hash part. */
size_t mask; /* Mask to turn hash value -> bucket. */
- upb_ctype_t ctype; /* Type of all values. */
uint8_t size_lg2; /* Size of the hashtable part is 2^size_lg2 entries. */
/* Hash table entries.
@@ -828,17 +658,6 @@
* 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;
typedef struct {
@@ -852,12 +671,6 @@
size_t array_count; /* Array part number of elements. */
} upb_inttable;
-#define UPB_INTTABLE_INIT(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)
-
#define UPB_ARRAY_EMPTYENT -1
UPB_INLINE size_t upb_table_size(const upb_table *t) {
@@ -926,6 +739,7 @@
size_t size);
upb_strtable *upb_strtable_pack(const upb_strtable *t, void *p, size_t *ofs,
size_t size);
+void upb_strtable_clear(upb_strtable *t);
/* Inserts the given key into the hashtable with the given value. The key must
* not already exist in the hash table. For string tables, the key must be
@@ -1027,7 +841,7 @@
if (key < t->array_size) {
upb_tabval arrval = t->array[key];
if (upb_arrhas(arrval)) {
- _upb_value_setval(v, arrval.val, t->t.ctype);
+ _upb_value_setval(v, arrval.val);
return true;
} else {
return false;
@@ -1037,7 +851,7 @@
if (t->t.entries == NULL) return false;
for (e = upb_getentry(&t->t, upb_inthash(key)); true; e = e->next) {
if ((uint32_t)e->key == key) {
- _upb_value_setval(v, e->val.val, t->t.ctype);
+ _upb_value_setval(v, e->val.val);
return true;
}
if (e->next == NULL) return false;
@@ -1091,8 +905,7 @@
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(const upb_strtable_iter *i);
-size_t upb_strtable_iter_keylength(const upb_strtable_iter *i);
+upb_strview upb_strtable_iter_key(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,
@@ -1116,6 +929,10 @@
bool array_part;
} upb_inttable_iter;
+UPB_INLINE const upb_tabent *str_tabent(const upb_strtable_iter *i) {
+ return &i->t->t.entries[i->index];
+}
+
void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t);
void upb_inttable_next(upb_inttable_iter *i);
bool upb_inttable_done(const upb_inttable_iter *i);
@@ -1132,98 +949,80 @@
#endif /* UPB_TABLE_H_ */
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/descriptor.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
-/*
-** Functions for use by generated code. These are not public and users must
-** not call them directly.
-*/
-
-#ifndef UPB_GENERATED_UTIL_H_
-#define UPB_GENERATED_UTIL_H_
-
-#include <stdint.h>
-
+#ifdef __cplusplus
+extern "C" {
+#endif
#define PTR_AT(msg, ofs, type) (type*)((const char*)msg + ofs)
-UPB_INLINE const void *_upb_array_accessor(const void *msg, size_t ofs,
- size_t *size) {
- const upb_array *arr = *PTR_AT(msg, ofs, const upb_array*);
- if (arr) {
- if (size) *size = arr->len;
- return arr->data;
- } else {
- if (size) *size = 0;
- return NULL;
- }
-}
+typedef void upb_msg;
-UPB_INLINE void *_upb_array_mutable_accessor(void *msg, size_t ofs,
- size_t *size) {
- upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
- if (arr) {
- if (size) *size = arr->len;
- return arr->data;
- } else {
- if (size) *size = 0;
- return NULL;
- }
-}
+/** upb_msglayout *************************************************************/
-/* TODO(haberman): this is a mess. It will improve when upb_array no longer
- * carries reflective state (type, elem_size). */
-UPB_INLINE void *_upb_array_resize_accessor(void *msg, size_t ofs, size_t size,
- size_t elem_size,
- upb_fieldtype_t type,
- upb_arena *arena) {
- upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
+/* upb_msglayout represents the memory layout of a given upb_msgdef. The
+ * members are public so generated code can initialize them, but users MUST NOT
+ * read or write any of its members. */
- if (!arr) {
- arr = upb_array_new(arena);
- if (!arr) return NULL;
- *PTR_AT(msg, ofs, upb_array*) = arr;
- }
+/* These aren't real labels according to descriptor.proto, but in the table we
+ * use these for map/packed fields instead of UPB_LABEL_REPEATED. */
+enum {
+ _UPB_LABEL_MAP = 4,
+ _UPB_LABEL_PACKED = 7 /* Low 3 bits are common with UPB_LABEL_REPEATED. */
+};
- if (size > arr->size) {
- size_t new_size = UPB_MAX(arr->size, 4);
- size_t old_bytes = arr->size * elem_size;
- size_t new_bytes;
- while (new_size < size) new_size *= 2;
- new_bytes = new_size * elem_size;
- arr->data = upb_arena_realloc(arena, arr->data, old_bytes, new_bytes);
- if (!arr->data) {
- return NULL;
- }
- arr->size = new_size;
- }
+typedef struct {
+ uint32_t number;
+ uint16_t offset;
+ int16_t presence; /* If >0, hasbit_index. If <0, -oneof_index. */
+ uint16_t submsg_index; /* undefined if descriptortype != MESSAGE or GROUP. */
+ uint8_t descriptortype;
+ uint8_t label;
+} upb_msglayout_field;
- arr->len = size;
- return arr->data;
-}
+typedef struct upb_msglayout {
+ const struct upb_msglayout *const* submsgs;
+ const upb_msglayout_field *fields;
+ /* Must be aligned to sizeof(void*). Doesn't include internal members like
+ * unknown fields, extension dict, pointer to msglayout, etc. */
+ uint16_t size;
+ uint16_t field_count;
+ bool extendable;
+} upb_msglayout;
-UPB_INLINE bool _upb_array_append_accessor(void *msg, size_t ofs,
- size_t elem_size,
- upb_fieldtype_t type,
- const void *value,
- upb_arena *arena) {
- upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
- size_t i = arr ? arr->len : 0;
- void *data =
- _upb_array_resize_accessor(msg, ofs, i + 1, elem_size, type, arena);
- if (!data) return false;
- memcpy(PTR_AT(data, i * elem_size, char), value, elem_size);
- return true;
-}
+/** upb_msg *******************************************************************/
+
+/* Internal members of a upb_msg. We can change this without breaking binary
+ * compatibility. We put these before the user's data. The user's upb_msg*
+ * points after the upb_msg_internal. */
+
+/* Used when a message is not extendable. */
+typedef struct {
+ char *unknown;
+ size_t unknown_len;
+ size_t unknown_size;
+} upb_msg_internal;
+
+/* Used when a message is extendable. */
+typedef struct {
+ upb_inttable *extdict;
+ upb_msg_internal base;
+} upb_msg_internal_withext;
+
+/* Maps upb_fieldtype_t -> memory size. */
+extern char _upb_fieldtype_to_size[12];
+
+/* Creates a new messages with the given layout on the given arena. */
+upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a);
+
+/* Adds unknown data (serialized protobuf data) to the given message. The data
+ * is copied into the message instance. */
+bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
+ upb_arena *arena);
+
+/* Returns a reference to the message's unknown data. */
+const char *upb_msg_getunknown(const upb_msg *msg, size_t *len);
UPB_INLINE bool _upb_has_field(const void *msg, size_t idx) {
return (*PTR_AT(msg, idx / 8, const char) & (1 << (idx % 8))) != 0;
@@ -1241,10 +1040,349 @@
return *PTR_AT(msg, case_ofs, int32_t) == num;
}
+UPB_INLINE bool _upb_has_submsg_nohasbit(const void *msg, size_t ofs) {
+ return *PTR_AT(msg, ofs, const void*) != NULL;
+}
+
+UPB_INLINE bool _upb_isrepeated(const upb_msglayout_field *field) {
+ return (field->label & 3) == UPB_LABEL_REPEATED;
+}
+
+/** upb_array *****************************************************************/
+
+/* Our internal representation for repeated fields. */
+typedef struct {
+ uintptr_t data; /* Tagged ptr: low 3 bits of ptr are lg2(elem size). */
+ size_t len; /* Measured in elements. */
+ size_t size; /* Measured in elements. */
+} upb_array;
+
+UPB_INLINE const void *_upb_array_constptr(const upb_array *arr) {
+ return (void*)(arr->data & ~(uintptr_t)7);
+}
+
+UPB_INLINE void *_upb_array_ptr(upb_array *arr) {
+ return (void*)_upb_array_constptr(arr);
+}
+
+/* Creates a new array on the given arena. */
+upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type);
+
+/* Resizes the capacity of the array to be at least min_size. */
+bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena);
+
+/* Fallback functions for when the accessors require a resize. */
+void *_upb_array_resize_fallback(upb_array **arr_ptr, size_t size,
+ upb_fieldtype_t type, upb_arena *arena);
+bool _upb_array_append_fallback(upb_array **arr_ptr, const void *value,
+ upb_fieldtype_t type, upb_arena *arena);
+
+UPB_INLINE const void *_upb_array_accessor(const void *msg, size_t ofs,
+ size_t *size) {
+ const upb_array *arr = *PTR_AT(msg, ofs, const upb_array*);
+ if (arr) {
+ if (size) *size = arr->len;
+ return _upb_array_constptr(arr);
+ } else {
+ if (size) *size = 0;
+ return NULL;
+ }
+}
+
+UPB_INLINE void *_upb_array_mutable_accessor(void *msg, size_t ofs,
+ size_t *size) {
+ upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
+ if (arr) {
+ if (size) *size = arr->len;
+ return _upb_array_ptr(arr);
+ } else {
+ if (size) *size = 0;
+ return NULL;
+ }
+}
+
+UPB_INLINE void *_upb_array_resize_accessor(void *msg, size_t ofs, size_t size,
+ upb_fieldtype_t type,
+ upb_arena *arena) {
+ upb_array **arr_ptr = PTR_AT(msg, ofs, upb_array*);
+ upb_array *arr = *arr_ptr;
+ if (!arr || arr->size < size) {
+ return _upb_array_resize_fallback(arr_ptr, size, type, arena);
+ }
+ arr->len = size;
+ return _upb_array_ptr(arr);
+}
+
+
+UPB_INLINE bool _upb_array_append_accessor(void *msg, size_t ofs,
+ size_t elem_size,
+ upb_fieldtype_t type,
+ const void *value,
+ upb_arena *arena) {
+ upb_array **arr_ptr = PTR_AT(msg, ofs, upb_array*);
+ upb_array *arr = *arr_ptr;
+ void* ptr;
+ if (!arr || arr->len == arr->size) {
+ return _upb_array_append_fallback(arr_ptr, value, type, arena);
+ }
+ ptr = _upb_array_ptr(arr);
+ memcpy(PTR_AT(ptr, arr->len * elem_size, char), value, elem_size);
+ arr->len++;
+ return true;
+}
+
+/** upb_map *******************************************************************/
+
+/* Right now we use strmaps for everything. We'll likely want to use
+ * integer-specific maps for integer-keyed maps.*/
+typedef struct {
+ /* Size of key and val, based on the map type. Strings are represented as '0'
+ * because they must be handled specially. */
+ char key_size;
+ char val_size;
+
+ upb_strtable table;
+} upb_map;
+
+/* Map entries aren't actually stored, they are only used during parsing. For
+ * parsing, it helps a lot if all map entry messages have the same layout.
+ * The compiler and def.c must ensure that all map entries have this layout. */
+typedef struct {
+ upb_msg_internal internal;
+ union {
+ upb_strview str; /* For str/bytes. */
+ upb_value val; /* For all other types. */
+ } k;
+ union {
+ upb_strview str; /* For str/bytes. */
+ upb_value val; /* For all other types. */
+ } v;
+} upb_map_entry;
+
+/* Creates a new map on the given arena with this key/value type. */
+upb_map *_upb_map_new(upb_arena *a, size_t key_size, size_t value_size);
+
+/* Converting between internal table representation and user values.
+ *
+ * _upb_map_tokey() and _upb_map_fromkey() are inverses.
+ * _upb_map_tovalue() and _upb_map_fromvalue() are inverses.
+ *
+ * These functions account for the fact that strings are treated differently
+ * from other types when stored in a map.
+ */
+
+UPB_INLINE upb_strview _upb_map_tokey(const void *key, size_t size) {
+ if (size == UPB_MAPTYPE_STRING) {
+ return *(upb_strview*)key;
+ } else {
+ return upb_strview_make((const char*)key, size);
+ }
+}
+
+UPB_INLINE void _upb_map_fromkey(upb_strview key, void* out, size_t size) {
+ if (size == UPB_MAPTYPE_STRING) {
+ memcpy(out, &key, sizeof(key));
+ } else {
+ memcpy(out, key.data, size);
+ }
+}
+
+UPB_INLINE upb_value _upb_map_tovalue(const void *val, size_t size,
+ upb_arena *a) {
+ upb_value ret = {0};
+ if (size == UPB_MAPTYPE_STRING) {
+ upb_strview *strp = (upb_strview*)upb_arena_malloc(a, sizeof(*strp));
+ *strp = *(upb_strview*)val;
+ memcpy(&ret, &strp, sizeof(strp));
+ } else {
+ memcpy(&ret, val, size);
+ }
+ return ret;
+}
+
+UPB_INLINE void _upb_map_fromvalue(upb_value val, void* out, size_t size) {
+ if (size == UPB_MAPTYPE_STRING) {
+ const upb_strview *strp = (const upb_strview*)upb_value_getptr(val);
+ memcpy(out, strp, sizeof(upb_strview));
+ } else {
+ memcpy(out, &val, size);
+ }
+}
+
+/* Map operations, shared by reflection and generated code. */
+
+UPB_INLINE size_t _upb_map_size(const upb_map *map) {
+ return map->table.t.count;
+}
+
+UPB_INLINE bool _upb_map_get(const upb_map *map, const void *key,
+ size_t key_size, void *val, size_t val_size) {
+ upb_value tabval;
+ upb_strview k = _upb_map_tokey(key, key_size);
+ bool ret = upb_strtable_lookup2(&map->table, k.data, k.size, &tabval);
+ if (ret) {
+ _upb_map_fromvalue(tabval, val, val_size);
+ }
+ return ret;
+}
+
+UPB_INLINE void* _upb_map_next(const upb_map *map, size_t *iter) {
+ upb_strtable_iter it;
+ it.t = &map->table;
+ it.index = *iter;
+ upb_strtable_next(&it);
+ if (upb_strtable_done(&it)) return NULL;
+ *iter = it.index;
+ return (void*)str_tabent(&it);
+}
+
+UPB_INLINE bool _upb_map_set(upb_map *map, const void *key, size_t key_size,
+ void *val, size_t val_size, upb_arena *arena) {
+ upb_strview strkey = _upb_map_tokey(key, key_size);
+ upb_value tabval = _upb_map_tovalue(val, val_size, arena);
+ upb_alloc *a = upb_arena_alloc(arena);
+
+ /* TODO(haberman): add overwrite operation to minimize number of lookups. */
+ upb_strtable_remove3(&map->table, strkey.data, strkey.size, NULL, a);
+ return upb_strtable_insert3(&map->table, strkey.data, strkey.size, tabval, a);
+}
+
+UPB_INLINE bool _upb_map_delete(upb_map *map, const void *key, size_t key_size) {
+ upb_strview k = _upb_map_tokey(key, key_size);
+ return upb_strtable_remove3(&map->table, k.data, k.size, NULL, NULL);
+}
+
+UPB_INLINE void _upb_map_clear(upb_map *map) {
+ upb_strtable_clear(&map->table);
+}
+
+/* Message map operations, these get the map from the message first. */
+
+UPB_INLINE size_t _upb_msg_map_size(const upb_msg *msg, size_t ofs) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ return map ? _upb_map_size(map) : 0;
+}
+
+UPB_INLINE bool _upb_msg_map_get(const upb_msg *msg, size_t ofs,
+ const void *key, size_t key_size, void *val,
+ size_t val_size) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return false;
+ return _upb_map_get(map, key, key_size, val, val_size);
+}
+
+UPB_INLINE void *_upb_msg_map_next(const upb_msg *msg, size_t ofs,
+ size_t *iter) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return NULL;
+ return _upb_map_next(map, iter);
+}
+
+UPB_INLINE bool _upb_msg_map_set(upb_msg *msg, size_t ofs, const void *key,
+ size_t key_size, void *val, size_t val_size,
+ upb_arena *arena) {
+ upb_map **map = PTR_AT(msg, ofs, upb_map *);
+ if (!*map) {
+ *map = _upb_map_new(arena, key_size, val_size);
+ }
+ return _upb_map_set(*map, key, key_size, val, val_size, arena);
+}
+
+UPB_INLINE bool _upb_msg_map_delete(upb_msg *msg, size_t ofs, const void *key,
+ size_t key_size) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return false;
+ return _upb_map_delete(map, key, key_size);
+}
+
+UPB_INLINE void _upb_msg_map_clear(upb_msg *msg, size_t ofs) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return;
+ _upb_map_clear(map);
+}
+
+/* Accessing map key/value from a pointer, used by generated code only. */
+
+UPB_INLINE void _upb_msg_map_key(const void* msg, void* key, size_t size) {
+ const upb_tabent *ent = (const upb_tabent*)msg;
+ uint32_t u32len;
+ upb_strview k;
+ k.data = upb_tabstr(ent->key, &u32len);
+ k.size = u32len;
+ _upb_map_fromkey(k, key, size);
+}
+
+UPB_INLINE void _upb_msg_map_value(const void* msg, void* val, size_t size) {
+ const upb_tabent *ent = (const upb_tabent*)msg;
+ upb_value v;
+ _upb_value_setval(&v, ent->val.val);
+ _upb_map_fromvalue(v, val, size);
+}
+
+UPB_INLINE void _upb_msg_map_set_value(void* msg, const void* val, size_t size) {
+ upb_tabent *ent = (upb_tabent*)msg;
+ /* This is like _upb_map_tovalue() except the entry already exists so we can
+ * reuse the allocated upb_strview for string fields. */
+ if (size == UPB_MAPTYPE_STRING) {
+ upb_strview *strp = (upb_strview*)ent->val.val;
+ memcpy(strp, val, sizeof(*strp));
+ } else {
+ memcpy(&ent->val.val, val, size);
+ }
+}
+
#undef PTR_AT
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
-#endif /* UPB_GENERATED_UTIL_H_ */
+
+#endif /* UPB_MSG_H_ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+bool upb_decode(const char *buf, size_t size, upb_msg *msg,
+ const upb_msglayout *l, upb_arena *arena);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* UPB_DECODE_H_ */
+/*
+** upb_encode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_ENCODE_H_
+#define UPB_ENCODE_H_
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+char *upb_encode(const void *msg, const upb_msglayout *l, upb_arena *arena,
+ size_t *size);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* UPB_ENCODE_H_ */
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/descriptor.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+
#ifdef __cplusplus
@@ -1388,7 +1526,7 @@
/* google.protobuf.FileDescriptorSet */
UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_new(upb_arena *arena) {
- return (google_protobuf_FileDescriptorSet *)upb_msg_new(&google_protobuf_FileDescriptorSet_msginit, arena);
+ return (google_protobuf_FileDescriptorSet *)_upb_msg_new(&google_protobuf_FileDescriptorSet_msginit, arena);
}
UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1399,16 +1537,17 @@
return upb_encode(msg, &google_protobuf_FileDescriptorSet_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_FileDescriptorSet_has_file(const google_protobuf_FileDescriptorSet *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_FileDescriptorProto* const* google_protobuf_FileDescriptorSet_file(const google_protobuf_FileDescriptorSet *msg, size_t *len) { return (const google_protobuf_FileDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_mutable_file(google_protobuf_FileDescriptorSet *msg, size_t *len) {
return (google_protobuf_FileDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_resize_file(google_protobuf_FileDescriptorSet *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FileDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FileDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FileDescriptorProto* google_protobuf_FileDescriptorSet_add_file(google_protobuf_FileDescriptorSet *msg, upb_arena *arena) {
- struct google_protobuf_FileDescriptorProto* sub = (struct google_protobuf_FileDescriptorProto*)upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
+ struct google_protobuf_FileDescriptorProto* sub = (struct google_protobuf_FileDescriptorProto*)_upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1418,7 +1557,7 @@
/* google.protobuf.FileDescriptorProto */
UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_FileDescriptorProto *)upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
+ return (google_protobuf_FileDescriptorProto *)_upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1430,49 +1569,53 @@
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_name(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_name(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_name(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_package(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_package(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)); }
+UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_package(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
UPB_INLINE upb_strview const* google_protobuf_FileDescriptorProto_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_message_type(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(40, 80)); }
UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_FileDescriptorProto_message_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_enum_type(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(44, 88)); }
UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_FileDescriptorProto_enum_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_service(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(48, 96)); }
UPB_INLINE const google_protobuf_ServiceDescriptorProto* const* google_protobuf_FileDescriptorProto_service(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_ServiceDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(48, 96), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_extension(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(52, 104)); }
UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_FileDescriptorProto_extension(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(52, 104), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_options(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE const google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_options(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_FileOptions*, UPB_SIZE(28, 56)); }
+UPB_INLINE const google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_options(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 56), const google_protobuf_FileOptions*); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE const google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_SourceCodeInfo*, UPB_SIZE(32, 64)); }
+UPB_INLINE const google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 64), const google_protobuf_SourceCodeInfo*); }
UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_public_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(56, 112), len); }
UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_weak_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(60, 120), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_syntax(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_syntax(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)); }
+UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_syntax(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview); }
UPB_INLINE void google_protobuf_FileDescriptorProto_set_name(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_package(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
}
UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_mutable_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
}
UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_resize_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_add_dependency(google_protobuf_FileDescriptorProto *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(36, 72), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(36, 72), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_mutable_message_type(google_protobuf_FileDescriptorProto *msg, size_t *len) {
return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
}
UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_resize_message_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_FileDescriptorProto_add_message_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
+ struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1482,10 +1625,10 @@
return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
}
UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_FileDescriptorProto_resize_enum_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_FileDescriptorProto_add_enum_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
+ struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(44, 88), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1495,10 +1638,10 @@
return (google_protobuf_ServiceDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 96), len);
}
UPB_INLINE google_protobuf_ServiceDescriptorProto** google_protobuf_FileDescriptorProto_resize_service(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_ServiceDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(48, 96), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_ServiceDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(48, 96), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_ServiceDescriptorProto* google_protobuf_FileDescriptorProto_add_service(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_ServiceDescriptorProto* sub = (struct google_protobuf_ServiceDescriptorProto*)upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
+ struct google_protobuf_ServiceDescriptorProto* sub = (struct google_protobuf_ServiceDescriptorProto*)_upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(48, 96), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1508,10 +1651,10 @@
return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 104), len);
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_FileDescriptorProto_resize_extension(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(52, 104), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(52, 104), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_FileDescriptorProto_add_extension(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(52, 104), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1519,12 +1662,12 @@
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_options(google_protobuf_FileDescriptorProto *msg, google_protobuf_FileOptions* value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, google_protobuf_FileOptions*, UPB_SIZE(28, 56)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 56), google_protobuf_FileOptions*) = value;
}
UPB_INLINE struct google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_mutable_options(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_FileOptions* sub = (struct google_protobuf_FileOptions*)google_protobuf_FileDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_FileOptions*)upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
+ sub = (struct google_protobuf_FileOptions*)_upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_FileDescriptorProto_set_options(msg, sub);
}
@@ -1532,12 +1675,12 @@
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_source_code_info(google_protobuf_FileDescriptorProto *msg, google_protobuf_SourceCodeInfo* value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, google_protobuf_SourceCodeInfo*, UPB_SIZE(32, 64)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(32, 64), google_protobuf_SourceCodeInfo*) = value;
}
UPB_INLINE struct google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_mutable_source_code_info(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_SourceCodeInfo* sub = (struct google_protobuf_SourceCodeInfo*)google_protobuf_FileDescriptorProto_source_code_info(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_SourceCodeInfo*)upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
+ sub = (struct google_protobuf_SourceCodeInfo*)_upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
if (!sub) return NULL;
google_protobuf_FileDescriptorProto_set_source_code_info(msg, sub);
}
@@ -1547,31 +1690,31 @@
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 112), len);
}
UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_public_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(56, 112), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(56, 112), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_add_public_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(56, 112), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(56, 112), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_mutable_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(60, 120), len);
}
UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(60, 120), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(60, 120), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_add_weak_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(60, 120), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(60, 120), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_syntax(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview) = value;
}
/* google.protobuf.DescriptorProto */
UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_DescriptorProto *)upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
+ return (google_protobuf_DescriptorProto *)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1583,30 +1726,37 @@
}
UPB_INLINE bool google_protobuf_DescriptorProto_has_name(const google_protobuf_DescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_DescriptorProto_name(const google_protobuf_DescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_DescriptorProto_name(const google_protobuf_DescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_field(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_field(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_nested_type(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40)); }
UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_DescriptorProto_nested_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_enum_type(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(24, 48)); }
UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_DescriptorProto_enum_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_extension_range(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 56)); }
UPB_INLINE const google_protobuf_DescriptorProto_ExtensionRange* const* google_protobuf_DescriptorProto_extension_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ExtensionRange* const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_extension(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(32, 64)); }
UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_extension(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(32, 64), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_options(const google_protobuf_DescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_MessageOptions* google_protobuf_DescriptorProto_options(const google_protobuf_DescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_MessageOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_MessageOptions* google_protobuf_DescriptorProto_options(const google_protobuf_DescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_MessageOptions*); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_oneof_decl(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(36, 72)); }
UPB_INLINE const google_protobuf_OneofDescriptorProto* const* google_protobuf_DescriptorProto_oneof_decl(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_OneofDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_reserved_range(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(40, 80)); }
UPB_INLINE const google_protobuf_DescriptorProto_ReservedRange* const* google_protobuf_DescriptorProto_reserved_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
UPB_INLINE upb_strview const* google_protobuf_DescriptorProto_reserved_name(const google_protobuf_DescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
UPB_INLINE void google_protobuf_DescriptorProto_set_name(google_protobuf_DescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_mutable_field(google_protobuf_DescriptorProto *msg, size_t *len) {
return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_field(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_field(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1616,10 +1766,10 @@
return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_DescriptorProto_resize_nested_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_DescriptorProto_add_nested_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
+ struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1629,10 +1779,10 @@
return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_DescriptorProto_resize_enum_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_DescriptorProto_add_enum_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
+ struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1642,10 +1792,10 @@
return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
}
UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange** google_protobuf_DescriptorProto_resize_extension_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto_ExtensionRange* google_protobuf_DescriptorProto_add_extension_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto_ExtensionRange* sub = (struct google_protobuf_DescriptorProto_ExtensionRange*)upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
+ struct google_protobuf_DescriptorProto_ExtensionRange* sub = (struct google_protobuf_DescriptorProto_ExtensionRange*)_upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(28, 56), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1655,10 +1805,10 @@
return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(32, 64), len);
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_extension(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(32, 64), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(32, 64), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_extension(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(32, 64), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1666,12 +1816,12 @@
}
UPB_INLINE void google_protobuf_DescriptorProto_set_options(google_protobuf_DescriptorProto *msg, google_protobuf_MessageOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_MessageOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_MessageOptions*) = value;
}
UPB_INLINE struct google_protobuf_MessageOptions* google_protobuf_DescriptorProto_mutable_options(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_MessageOptions* sub = (struct google_protobuf_MessageOptions*)google_protobuf_DescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_MessageOptions*)upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
+ sub = (struct google_protobuf_MessageOptions*)_upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_DescriptorProto_set_options(msg, sub);
}
@@ -1681,10 +1831,10 @@
return (google_protobuf_OneofDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
}
UPB_INLINE google_protobuf_OneofDescriptorProto** google_protobuf_DescriptorProto_resize_oneof_decl(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_OneofDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_OneofDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_OneofDescriptorProto* google_protobuf_DescriptorProto_add_oneof_decl(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_OneofDescriptorProto* sub = (struct google_protobuf_OneofDescriptorProto*)upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
+ struct google_protobuf_OneofDescriptorProto* sub = (struct google_protobuf_OneofDescriptorProto*)_upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(36, 72), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1694,10 +1844,10 @@
return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
}
UPB_INLINE google_protobuf_DescriptorProto_ReservedRange** google_protobuf_DescriptorProto_resize_reserved_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto_ReservedRange* google_protobuf_DescriptorProto_add_reserved_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto_ReservedRange* sub = (struct google_protobuf_DescriptorProto_ReservedRange*)upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
+ struct google_protobuf_DescriptorProto_ReservedRange* sub = (struct google_protobuf_DescriptorProto_ReservedRange*)_upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1707,17 +1857,17 @@
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
}
UPB_INLINE upb_strview* google_protobuf_DescriptorProto_resize_reserved_name(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_DescriptorProto_add_reserved_name(google_protobuf_DescriptorProto *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(44, 88), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(44, 88), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
/* google.protobuf.DescriptorProto.ExtensionRange */
UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_new(upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ExtensionRange *)upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
+ return (google_protobuf_DescriptorProto_ExtensionRange *)_upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
}
UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1729,28 +1879,28 @@
}
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE const google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return UPB_FIELD_AT(msg, const google_protobuf_ExtensionRangeOptions*, UPB_SIZE(12, 16)); }
+UPB_INLINE const google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 16), const google_protobuf_ExtensionRangeOptions*); }
UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_start(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_end(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_options(google_protobuf_DescriptorProto_ExtensionRange *msg, google_protobuf_ExtensionRangeOptions* value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, google_protobuf_ExtensionRangeOptions*, UPB_SIZE(12, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 16), google_protobuf_ExtensionRangeOptions*) = value;
}
UPB_INLINE struct google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_mutable_options(google_protobuf_DescriptorProto_ExtensionRange *msg, upb_arena *arena) {
struct google_protobuf_ExtensionRangeOptions* sub = (struct google_protobuf_ExtensionRangeOptions*)google_protobuf_DescriptorProto_ExtensionRange_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_ExtensionRangeOptions*)upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
+ sub = (struct google_protobuf_ExtensionRangeOptions*)_upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_DescriptorProto_ExtensionRange_set_options(msg, sub);
}
@@ -1760,7 +1910,7 @@
/* google.protobuf.DescriptorProto.ReservedRange */
UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_new(upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ReservedRange *)upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
+ return (google_protobuf_DescriptorProto_ReservedRange *)_upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
}
UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1772,23 +1922,23 @@
}
UPB_INLINE bool google_protobuf_DescriptorProto_ReservedRange_has_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ReservedRange_has_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_start(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_end(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
/* google.protobuf.ExtensionRangeOptions */
UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_new(upb_arena *arena) {
- return (google_protobuf_ExtensionRangeOptions *)upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
+ return (google_protobuf_ExtensionRangeOptions *)_upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
}
UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1799,16 +1949,17 @@
return upb_encode(msg, &google_protobuf_ExtensionRangeOptions_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_ExtensionRangeOptions_has_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ExtensionRangeOptions_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_mutable_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_resize_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ExtensionRangeOptions_add_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1818,7 +1969,7 @@
/* google.protobuf.FieldDescriptorProto */
UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto *)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ return (google_protobuf_FieldDescriptorProto *)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1829,63 +1980,65 @@
return upb_encode(msg, &google_protobuf_FieldDescriptorProto_msginit, arena, len);
}
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_name(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_extendee(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_extendee(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 6); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(36, 40), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_extendee(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 7); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_extendee(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(44, 56), upb_strview); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_number(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_number(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(24, 24)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_number(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), int32_t); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_label(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_label(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_label(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_type(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_type(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_type_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 7); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_type_name(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_default_value(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 8); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_default_value(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(56, 80)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_options(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 10); }
-UPB_INLINE const google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_options(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_FieldOptions*, UPB_SIZE(72, 112)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_type(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_type_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 8); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_type_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(52, 72), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_default_value(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 9); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_default_value(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(60, 88), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_options(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 11); }
+UPB_INLINE const google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_options(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(76, 120), const google_protobuf_FieldOptions*); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_oneof_index(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_oneof_index(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(28, 28)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_json_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 9); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_json_name(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(64, 96)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_oneof_index(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 28), int32_t); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_json_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 10); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_json_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(68, 104), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_proto3_optional(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 5); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_proto3_optional(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), bool); }
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)) = value;
+ _upb_sethas(msg, 6);
+ *UPB_PTR_AT(msg, UPB_SIZE(36, 40), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_extendee(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)) = value;
+ _upb_sethas(msg, 7);
+ *UPB_PTR_AT(msg, UPB_SIZE(44, 56), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_number(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_label(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 7);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)) = value;
+ _upb_sethas(msg, 8);
+ *UPB_PTR_AT(msg, UPB_SIZE(52, 72), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_default_value(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 8);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(56, 80)) = value;
+ _upb_sethas(msg, 9);
+ *UPB_PTR_AT(msg, UPB_SIZE(60, 88), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_options(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldOptions* value) {
- _upb_sethas(msg, 10);
- UPB_FIELD_AT(msg, google_protobuf_FieldOptions*, UPB_SIZE(72, 112)) = value;
+ _upb_sethas(msg, 11);
+ *UPB_PTR_AT(msg, UPB_SIZE(76, 120), google_protobuf_FieldOptions*) = value;
}
UPB_INLINE struct google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_mutable_options(google_protobuf_FieldDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_FieldOptions* sub = (struct google_protobuf_FieldOptions*)google_protobuf_FieldDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_FieldOptions*)upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
+ sub = (struct google_protobuf_FieldOptions*)_upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_FieldDescriptorProto_set_options(msg, sub);
}
@@ -1893,17 +2046,21 @@
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_oneof_index(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(28, 28)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 28), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_json_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 9);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(64, 96)) = value;
+ _upb_sethas(msg, 10);
+ *UPB_PTR_AT(msg, UPB_SIZE(68, 104), upb_strview) = value;
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_proto3_optional(google_protobuf_FieldDescriptorProto *msg, bool value) {
+ _upb_sethas(msg, 5);
+ *UPB_PTR_AT(msg, UPB_SIZE(32, 32), bool) = value;
}
/* google.protobuf.OneofDescriptorProto */
UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_OneofDescriptorProto *)upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
+ return (google_protobuf_OneofDescriptorProto *)_upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1915,22 +2072,22 @@
}
UPB_INLINE bool google_protobuf_OneofDescriptorProto_has_name(const google_protobuf_OneofDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_OneofDescriptorProto_name(const google_protobuf_OneofDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_OneofDescriptorProto_name(const google_protobuf_OneofDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_OneofDescriptorProto_has_options(const google_protobuf_OneofDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_options(const google_protobuf_OneofDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_OneofOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_options(const google_protobuf_OneofDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_OneofOptions*); }
UPB_INLINE void google_protobuf_OneofDescriptorProto_set_name(google_protobuf_OneofDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_OneofDescriptorProto_set_options(google_protobuf_OneofDescriptorProto *msg, google_protobuf_OneofOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_OneofOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_OneofOptions*) = value;
}
UPB_INLINE struct google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_mutable_options(google_protobuf_OneofDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_OneofOptions* sub = (struct google_protobuf_OneofOptions*)google_protobuf_OneofDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_OneofOptions*)upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
+ sub = (struct google_protobuf_OneofOptions*)_upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_OneofDescriptorProto_set_options(msg, sub);
}
@@ -1940,7 +2097,7 @@
/* google.protobuf.EnumDescriptorProto */
UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto *)upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
+ return (google_protobuf_EnumDescriptorProto *)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1952,25 +2109,27 @@
}
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_name(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_EnumDescriptorProto_name(const google_protobuf_EnumDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_EnumDescriptorProto_name(const google_protobuf_EnumDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
+UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_value(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
UPB_INLINE const google_protobuf_EnumValueDescriptorProto* const* google_protobuf_EnumDescriptorProto_value(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumValueDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_options(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_options(const google_protobuf_EnumDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_EnumOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_options(const google_protobuf_EnumDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_EnumOptions*); }
+UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_reserved_range(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40)); }
UPB_INLINE const google_protobuf_EnumDescriptorProto_EnumReservedRange* const* google_protobuf_EnumDescriptorProto_reserved_range(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto_EnumReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
UPB_INLINE upb_strview const* google_protobuf_EnumDescriptorProto_reserved_name(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE void google_protobuf_EnumDescriptorProto_set_name(google_protobuf_EnumDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_mutable_value(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
return (google_protobuf_EnumValueDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
}
UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_resize_value(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumValueDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumValueDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumValueDescriptorProto* google_protobuf_EnumDescriptorProto_add_value(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumValueDescriptorProto* sub = (struct google_protobuf_EnumValueDescriptorProto*)upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
+ struct google_protobuf_EnumValueDescriptorProto* sub = (struct google_protobuf_EnumValueDescriptorProto*)_upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1978,12 +2137,12 @@
}
UPB_INLINE void google_protobuf_EnumDescriptorProto_set_options(google_protobuf_EnumDescriptorProto *msg, google_protobuf_EnumOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_EnumOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_EnumOptions*) = value;
}
UPB_INLINE struct google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_mutable_options(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumOptions* sub = (struct google_protobuf_EnumOptions*)google_protobuf_EnumDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_EnumOptions*)upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
+ sub = (struct google_protobuf_EnumOptions*)_upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_EnumDescriptorProto_set_options(msg, sub);
}
@@ -1993,10 +2152,10 @@
return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange** google_protobuf_EnumDescriptorProto_resize_reserved_range(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumDescriptorProto_EnumReservedRange* google_protobuf_EnumDescriptorProto_add_reserved_range(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumDescriptorProto_EnumReservedRange* sub = (struct google_protobuf_EnumDescriptorProto_EnumReservedRange*)upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
+ struct google_protobuf_EnumDescriptorProto_EnumReservedRange* sub = (struct google_protobuf_EnumDescriptorProto_EnumReservedRange*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2006,17 +2165,17 @@
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE upb_strview* google_protobuf_EnumDescriptorProto_resize_reserved_name(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_EnumDescriptorProto_add_reserved_name(google_protobuf_EnumDescriptorProto *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(24, 48), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(24, 48), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
/* google.protobuf.EnumDescriptorProto.EnumReservedRange */
UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_new(upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto_EnumReservedRange *)upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
+ return (google_protobuf_EnumDescriptorProto_EnumReservedRange *)_upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
}
UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2028,23 +2187,23 @@
}
UPB_INLINE bool google_protobuf_EnumDescriptorProto_EnumReservedRange_has_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_EnumReservedRange_has_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_start(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_end(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
/* google.protobuf.EnumValueDescriptorProto */
UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_EnumValueDescriptorProto *)upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
+ return (google_protobuf_EnumValueDescriptorProto *)_upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2056,28 +2215,28 @@
}
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_name(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_EnumValueDescriptorProto_name(const google_protobuf_EnumValueDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(8, 8)); }
+UPB_INLINE upb_strview google_protobuf_EnumValueDescriptorProto_name(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview); }
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_number(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_EnumValueDescriptorProto_number(const google_protobuf_EnumValueDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_EnumValueDescriptorProto_number(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_options(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE const google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_options(const google_protobuf_EnumValueDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_EnumValueOptions*, UPB_SIZE(16, 24)); }
+UPB_INLINE const google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_options(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 24), const google_protobuf_EnumValueOptions*); }
UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_name(google_protobuf_EnumValueDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_number(google_protobuf_EnumValueDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_options(google_protobuf_EnumValueDescriptorProto *msg, google_protobuf_EnumValueOptions* value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, google_protobuf_EnumValueOptions*, UPB_SIZE(16, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 24), google_protobuf_EnumValueOptions*) = value;
}
UPB_INLINE struct google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_mutable_options(google_protobuf_EnumValueDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumValueOptions* sub = (struct google_protobuf_EnumValueOptions*)google_protobuf_EnumValueDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_EnumValueOptions*)upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
+ sub = (struct google_protobuf_EnumValueOptions*)_upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_EnumValueDescriptorProto_set_options(msg, sub);
}
@@ -2087,7 +2246,7 @@
/* google.protobuf.ServiceDescriptorProto */
UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_ServiceDescriptorProto *)upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
+ return (google_protobuf_ServiceDescriptorProto *)_upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2099,23 +2258,24 @@
}
UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_name(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_ServiceDescriptorProto_name(const google_protobuf_ServiceDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_ServiceDescriptorProto_name(const google_protobuf_ServiceDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
+UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_method(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
UPB_INLINE const google_protobuf_MethodDescriptorProto* const* google_protobuf_ServiceDescriptorProto_method(const google_protobuf_ServiceDescriptorProto *msg, size_t *len) { return (const google_protobuf_MethodDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_options(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_options(const google_protobuf_ServiceDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_ServiceOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_options(const google_protobuf_ServiceDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_ServiceOptions*); }
UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_name(google_protobuf_ServiceDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_mutable_method(google_protobuf_ServiceDescriptorProto *msg, size_t *len) {
return (google_protobuf_MethodDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
}
UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_resize_method(google_protobuf_ServiceDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_MethodDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_MethodDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_MethodDescriptorProto* google_protobuf_ServiceDescriptorProto_add_method(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_MethodDescriptorProto* sub = (struct google_protobuf_MethodDescriptorProto*)upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
+ struct google_protobuf_MethodDescriptorProto* sub = (struct google_protobuf_MethodDescriptorProto*)_upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2123,12 +2283,12 @@
}
UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_options(google_protobuf_ServiceDescriptorProto *msg, google_protobuf_ServiceOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_ServiceOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_ServiceOptions*) = value;
}
UPB_INLINE struct google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_mutable_options(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_ServiceOptions* sub = (struct google_protobuf_ServiceOptions*)google_protobuf_ServiceDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_ServiceOptions*)upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
+ sub = (struct google_protobuf_ServiceOptions*)_upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_ServiceDescriptorProto_set_options(msg, sub);
}
@@ -2138,7 +2298,7 @@
/* google.protobuf.MethodDescriptorProto */
UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_MethodDescriptorProto *)upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
+ return (google_protobuf_MethodDescriptorProto *)_upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2150,38 +2310,38 @@
}
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_name(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_name(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_name(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_input_type(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_input_type(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)); }
+UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_input_type(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_output_type(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_output_type(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)); }
+UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_output_type(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_options(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE const google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_options(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_MethodOptions*, UPB_SIZE(28, 56)); }
+UPB_INLINE const google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_options(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 56), const google_protobuf_MethodOptions*); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_client_streaming(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_MethodDescriptorProto_client_streaming(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_MethodDescriptorProto_client_streaming(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_MethodDescriptorProto_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)); }
+UPB_INLINE bool google_protobuf_MethodDescriptorProto_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_name(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_input_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_output_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_options(google_protobuf_MethodDescriptorProto *msg, google_protobuf_MethodOptions* value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, google_protobuf_MethodOptions*, UPB_SIZE(28, 56)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 56), google_protobuf_MethodOptions*) = value;
}
UPB_INLINE struct google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_mutable_options(google_protobuf_MethodDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_MethodOptions* sub = (struct google_protobuf_MethodOptions*)google_protobuf_MethodDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_MethodOptions*)upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
+ sub = (struct google_protobuf_MethodOptions*)_upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_MethodDescriptorProto_set_options(msg, sub);
}
@@ -2189,17 +2349,17 @@
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_client_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_server_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
}
/* google.protobuf.FileOptions */
UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_new(upb_arena *arena) {
- return (google_protobuf_FileOptions *)upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
+ return (google_protobuf_FileOptions *)_upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
}
UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2211,135 +2371,136 @@
}
UPB_INLINE bool google_protobuf_FileOptions_has_java_package(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 11); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_java_package(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(28, 32)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_java_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 32), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_outer_classname(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 12); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_java_outer_classname(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(36, 48)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_java_outer_classname(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(36, 48), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_optimize_for(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_FileOptions_optimize_for(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_FileOptions_optimize_for(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_multiple_files(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_FileOptions_java_multiple_files(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_multiple_files(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_go_package(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 13); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_go_package(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(44, 64)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_go_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(44, 64), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_cc_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE bool google_protobuf_FileOptions_cc_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(17, 17)); }
+UPB_INLINE bool google_protobuf_FileOptions_cc_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(17, 17), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE bool google_protobuf_FileOptions_java_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(18, 18)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(18, 18), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_py_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE bool google_protobuf_FileOptions_py_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(19, 19)); }
+UPB_INLINE bool google_protobuf_FileOptions_py_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(19, 19), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE bool google_protobuf_FileOptions_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(20, 20)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_deprecated(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 7); }
-UPB_INLINE bool google_protobuf_FileOptions_deprecated(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(21, 21)); }
+UPB_INLINE bool google_protobuf_FileOptions_deprecated(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(21, 21), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_string_check_utf8(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 8); }
-UPB_INLINE bool google_protobuf_FileOptions_java_string_check_utf8(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(22, 22)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_string_check_utf8(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(22, 22), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_cc_enable_arenas(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 9); }
-UPB_INLINE bool google_protobuf_FileOptions_cc_enable_arenas(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(23, 23)); }
+UPB_INLINE bool google_protobuf_FileOptions_cc_enable_arenas(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(23, 23), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_objc_class_prefix(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 14); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_objc_class_prefix(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(52, 80)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_objc_class_prefix(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(52, 80), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_csharp_namespace(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 15); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_csharp_namespace(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(60, 96)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_csharp_namespace(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(60, 96), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_swift_prefix(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 16); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_swift_prefix(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(68, 112)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_swift_prefix(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(68, 112), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_class_prefix(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 17); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_php_class_prefix(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(76, 128)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_php_class_prefix(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(76, 128), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_namespace(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 18); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_php_namespace(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(84, 144)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_php_namespace(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(84, 144), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 10); }
-UPB_INLINE bool google_protobuf_FileOptions_php_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)); }
+UPB_INLINE bool google_protobuf_FileOptions_php_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_metadata_namespace(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 19); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_php_metadata_namespace(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(92, 160)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_php_metadata_namespace(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(92, 160), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_ruby_package(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 20); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_ruby_package(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(100, 176)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_ruby_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(100, 176), upb_strview); }
+UPB_INLINE bool google_protobuf_FileOptions_has_uninterpreted_option(const google_protobuf_FileOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(108, 192)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FileOptions_uninterpreted_option(const google_protobuf_FileOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(108, 192), len); }
UPB_INLINE void google_protobuf_FileOptions_set_java_package(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 11);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(28, 32)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 32), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_outer_classname(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 12);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(36, 48)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(36, 48), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_optimize_for(google_protobuf_FileOptions *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_multiple_files(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_go_package(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 13);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(44, 64)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(44, 64), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_cc_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(17, 17)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(17, 17), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(18, 18)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(18, 18), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_py_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(19, 19)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(19, 19), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_generate_equals_and_hash(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(20, 20)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(20, 20), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_deprecated(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 7);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(21, 21)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(21, 21), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_string_check_utf8(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 8);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(22, 22)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(22, 22), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_cc_enable_arenas(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 9);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(23, 23)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(23, 23), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_objc_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 14);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(52, 80)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(52, 80), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_csharp_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 15);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(60, 96)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(60, 96), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_swift_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 16);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(68, 112)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(68, 112), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 17);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(76, 128)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(76, 128), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 18);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(84, 144)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(84, 144), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 10);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_metadata_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 19);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(92, 160)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(92, 160), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_ruby_package(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 20);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(100, 176)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(100, 176), upb_strview) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_mutable_uninterpreted_option(google_protobuf_FileOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(108, 192), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_resize_uninterpreted_option(google_protobuf_FileOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(108, 192), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(108, 192), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FileOptions_add_uninterpreted_option(google_protobuf_FileOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(108, 192), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2349,7 +2510,7 @@
/* google.protobuf.MessageOptions */
UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_new(upb_arena *arena) {
- return (google_protobuf_MessageOptions *)upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
+ return (google_protobuf_MessageOptions *)_upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
}
UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2361,39 +2522,40 @@
}
UPB_INLINE bool google_protobuf_MessageOptions_has_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_MessageOptions_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_MessageOptions_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_MessageOptions_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)); }
+UPB_INLINE bool google_protobuf_MessageOptions_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_deprecated(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE bool google_protobuf_MessageOptions_deprecated(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(3, 3)); }
+UPB_INLINE bool google_protobuf_MessageOptions_deprecated(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(3, 3), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_map_entry(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE bool google_protobuf_MessageOptions_map_entry(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(4, 4)); }
+UPB_INLINE bool google_protobuf_MessageOptions_map_entry(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool); }
+UPB_INLINE bool google_protobuf_MessageOptions_has_uninterpreted_option(const google_protobuf_MessageOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(8, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MessageOptions_uninterpreted_option(const google_protobuf_MessageOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(8, 8), len); }
UPB_INLINE void google_protobuf_MessageOptions_set_message_set_wire_format(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE void google_protobuf_MessageOptions_set_no_standard_descriptor_accessor(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
}
UPB_INLINE void google_protobuf_MessageOptions_set_deprecated(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(3, 3)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(3, 3), bool) = value;
}
UPB_INLINE void google_protobuf_MessageOptions_set_map_entry(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_mutable_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(8, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_resize_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(8, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(8, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MessageOptions_add_uninterpreted_option(google_protobuf_MessageOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(8, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2403,7 +2565,7 @@
/* google.protobuf.FieldOptions */
UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_new(upb_arena *arena) {
- return (google_protobuf_FieldOptions *)upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
+ return (google_protobuf_FieldOptions *)_upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
}
UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2415,51 +2577,52 @@
}
UPB_INLINE bool google_protobuf_FieldOptions_has_ctype(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_FieldOptions_ctype(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_FieldOptions_ctype(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_FieldOptions_has_packed(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE bool google_protobuf_FieldOptions_packed(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)); }
+UPB_INLINE bool google_protobuf_FieldOptions_packed(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool); }
UPB_INLINE bool google_protobuf_FieldOptions_has_deprecated(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE bool google_protobuf_FieldOptions_deprecated(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(25, 25)); }
+UPB_INLINE bool google_protobuf_FieldOptions_deprecated(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(25, 25), bool); }
UPB_INLINE bool google_protobuf_FieldOptions_has_lazy(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE bool google_protobuf_FieldOptions_lazy(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(26, 26)); }
+UPB_INLINE bool google_protobuf_FieldOptions_lazy(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(26, 26), bool); }
UPB_INLINE bool google_protobuf_FieldOptions_has_jstype(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_FieldOptions_jstype(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)); }
+UPB_INLINE int32_t google_protobuf_FieldOptions_jstype(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t); }
UPB_INLINE bool google_protobuf_FieldOptions_has_weak(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE bool google_protobuf_FieldOptions_weak(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(27, 27)); }
+UPB_INLINE bool google_protobuf_FieldOptions_weak(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(27, 27), bool); }
+UPB_INLINE bool google_protobuf_FieldOptions_has_uninterpreted_option(const google_protobuf_FieldOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 32)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FieldOptions_uninterpreted_option(const google_protobuf_FieldOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
UPB_INLINE void google_protobuf_FieldOptions_set_ctype(google_protobuf_FieldOptions *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_packed(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_deprecated(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(25, 25)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(25, 25), bool) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_lazy(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(26, 26)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(26, 26), bool) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_jstype(google_protobuf_FieldOptions *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_weak(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(27, 27)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(27, 27), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_mutable_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_resize_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FieldOptions_add_uninterpreted_option(google_protobuf_FieldOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(28, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2469,7 +2632,7 @@
/* google.protobuf.OneofOptions */
UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_new(upb_arena *arena) {
- return (google_protobuf_OneofOptions *)upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
+ return (google_protobuf_OneofOptions *)_upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
}
UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2480,16 +2643,17 @@
return upb_encode(msg, &google_protobuf_OneofOptions_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_OneofOptions_has_uninterpreted_option(const google_protobuf_OneofOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_OneofOptions_uninterpreted_option(const google_protobuf_OneofOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_mutable_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_resize_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_OneofOptions_add_uninterpreted_option(google_protobuf_OneofOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2499,7 +2663,7 @@
/* google.protobuf.EnumOptions */
UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_new(upb_arena *arena) {
- return (google_protobuf_EnumOptions *)upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
+ return (google_protobuf_EnumOptions *)_upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
}
UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2511,27 +2675,28 @@
}
UPB_INLINE bool google_protobuf_EnumOptions_has_allow_alias(const google_protobuf_EnumOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_EnumOptions_allow_alias(const google_protobuf_EnumOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_EnumOptions_allow_alias(const google_protobuf_EnumOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_EnumOptions_has_deprecated(const google_protobuf_EnumOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_EnumOptions_deprecated(const google_protobuf_EnumOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)); }
+UPB_INLINE bool google_protobuf_EnumOptions_deprecated(const google_protobuf_EnumOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
+UPB_INLINE bool google_protobuf_EnumOptions_has_uninterpreted_option(const google_protobuf_EnumOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumOptions_uninterpreted_option(const google_protobuf_EnumOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
UPB_INLINE void google_protobuf_EnumOptions_set_allow_alias(google_protobuf_EnumOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE void google_protobuf_EnumOptions_set_deprecated(google_protobuf_EnumOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_mutable_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_resize_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumOptions_add_uninterpreted_option(google_protobuf_EnumOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2541,7 +2706,7 @@
/* google.protobuf.EnumValueOptions */
UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_new(upb_arena *arena) {
- return (google_protobuf_EnumValueOptions *)upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
+ return (google_protobuf_EnumValueOptions *)_upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
}
UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2553,21 +2718,22 @@
}
UPB_INLINE bool google_protobuf_EnumValueOptions_has_deprecated(const google_protobuf_EnumValueOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_EnumValueOptions_deprecated(const google_protobuf_EnumValueOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_EnumValueOptions_deprecated(const google_protobuf_EnumValueOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
+UPB_INLINE bool google_protobuf_EnumValueOptions_has_uninterpreted_option(const google_protobuf_EnumValueOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumValueOptions_uninterpreted_option(const google_protobuf_EnumValueOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
UPB_INLINE void google_protobuf_EnumValueOptions_set_deprecated(google_protobuf_EnumValueOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_mutable_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_resize_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumValueOptions_add_uninterpreted_option(google_protobuf_EnumValueOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2577,7 +2743,7 @@
/* google.protobuf.ServiceOptions */
UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_new(upb_arena *arena) {
- return (google_protobuf_ServiceOptions *)upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
+ return (google_protobuf_ServiceOptions *)_upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
}
UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2589,21 +2755,22 @@
}
UPB_INLINE bool google_protobuf_ServiceOptions_has_deprecated(const google_protobuf_ServiceOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_ServiceOptions_deprecated(const google_protobuf_ServiceOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_ServiceOptions_deprecated(const google_protobuf_ServiceOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
+UPB_INLINE bool google_protobuf_ServiceOptions_has_uninterpreted_option(const google_protobuf_ServiceOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ServiceOptions_uninterpreted_option(const google_protobuf_ServiceOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
UPB_INLINE void google_protobuf_ServiceOptions_set_deprecated(google_protobuf_ServiceOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_mutable_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_resize_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ServiceOptions_add_uninterpreted_option(google_protobuf_ServiceOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2613,7 +2780,7 @@
/* google.protobuf.MethodOptions */
UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_new(upb_arena *arena) {
- return (google_protobuf_MethodOptions *)upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
+ return (google_protobuf_MethodOptions *)_upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
}
UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2625,27 +2792,28 @@
}
UPB_INLINE bool google_protobuf_MethodOptions_has_deprecated(const google_protobuf_MethodOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_MethodOptions_deprecated(const google_protobuf_MethodOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)); }
+UPB_INLINE bool google_protobuf_MethodOptions_deprecated(const google_protobuf_MethodOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool); }
UPB_INLINE bool google_protobuf_MethodOptions_has_idempotency_level(const google_protobuf_MethodOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_MethodOptions_idempotency_level(const google_protobuf_MethodOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_MethodOptions_idempotency_level(const google_protobuf_MethodOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
+UPB_INLINE bool google_protobuf_MethodOptions_has_uninterpreted_option(const google_protobuf_MethodOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 24)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MethodOptions_uninterpreted_option(const google_protobuf_MethodOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(20, 24), len); }
UPB_INLINE void google_protobuf_MethodOptions_set_deprecated(google_protobuf_MethodOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool) = value;
}
UPB_INLINE void google_protobuf_MethodOptions_set_idempotency_level(google_protobuf_MethodOptions *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_mutable_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 24), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_resize_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 24), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 24), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MethodOptions_add_uninterpreted_option(google_protobuf_MethodOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(20, 24), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2655,7 +2823,7 @@
/* google.protobuf.UninterpretedOption */
UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_new(upb_arena *arena) {
- return (google_protobuf_UninterpretedOption *)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ return (google_protobuf_UninterpretedOption *)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
}
UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2666,28 +2834,29 @@
return upb_encode(msg, &google_protobuf_UninterpretedOption_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_UninterpretedOption_has_name(const google_protobuf_UninterpretedOption *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(56, 80)); }
UPB_INLINE const google_protobuf_UninterpretedOption_NamePart* const* google_protobuf_UninterpretedOption_name(const google_protobuf_UninterpretedOption *msg, size_t *len) { return (const google_protobuf_UninterpretedOption_NamePart* const*)_upb_array_accessor(msg, UPB_SIZE(56, 80), len); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_identifier_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_identifier_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_identifier_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_positive_int_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE uint64_t google_protobuf_UninterpretedOption_positive_int_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, uint64_t, UPB_SIZE(8, 8)); }
+UPB_INLINE uint64_t google_protobuf_UninterpretedOption_positive_int_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_negative_int_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int64_t google_protobuf_UninterpretedOption_negative_int_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, int64_t, UPB_SIZE(16, 16)); }
+UPB_INLINE int64_t google_protobuf_UninterpretedOption_negative_int_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_double_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE double google_protobuf_UninterpretedOption_double_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, double, UPB_SIZE(24, 24)); }
+UPB_INLINE double google_protobuf_UninterpretedOption_double_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), double); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_string_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_string_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_string_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 48), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(48, 64), upb_strview); }
UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_mutable_name(google_protobuf_UninterpretedOption *msg, size_t *len) {
return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 80), len);
}
UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_resize_name(google_protobuf_UninterpretedOption *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_resize_accessor(msg, UPB_SIZE(56, 80), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_resize_accessor(msg, UPB_SIZE(56, 80), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption_NamePart* google_protobuf_UninterpretedOption_add_name(google_protobuf_UninterpretedOption *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption_NamePart* sub = (struct google_protobuf_UninterpretedOption_NamePart*)upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
+ struct google_protobuf_UninterpretedOption_NamePart* sub = (struct google_protobuf_UninterpretedOption_NamePart*)_upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(56, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2695,33 +2864,33 @@
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_identifier_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_positive_int_value(google_protobuf_UninterpretedOption *msg, uint64_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, uint64_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_negative_int_value(google_protobuf_UninterpretedOption *msg, int64_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int64_t, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_double_value(google_protobuf_UninterpretedOption *msg, double value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, double, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), double) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_string_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(40, 48), upb_strview) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_aggregate_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(48, 64), upb_strview) = value;
}
/* google.protobuf.UninterpretedOption.NamePart */
UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_new(upb_arena *arena) {
- return (google_protobuf_UninterpretedOption_NamePart *)upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
+ return (google_protobuf_UninterpretedOption_NamePart *)_upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
}
UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2733,23 +2902,23 @@
}
UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_has_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_NamePart_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_NamePart_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_has_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_name_part(google_protobuf_UninterpretedOption_NamePart *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_is_extension(google_protobuf_UninterpretedOption_NamePart *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
/* google.protobuf.SourceCodeInfo */
UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_new(upb_arena *arena) {
- return (google_protobuf_SourceCodeInfo *)upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
+ return (google_protobuf_SourceCodeInfo *)_upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
}
UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2760,16 +2929,17 @@
return upb_encode(msg, &google_protobuf_SourceCodeInfo_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_SourceCodeInfo_has_location(const google_protobuf_SourceCodeInfo *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_SourceCodeInfo_Location* const* google_protobuf_SourceCodeInfo_location(const google_protobuf_SourceCodeInfo *msg, size_t *len) { return (const google_protobuf_SourceCodeInfo_Location* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_mutable_location(google_protobuf_SourceCodeInfo *msg, size_t *len) {
return (google_protobuf_SourceCodeInfo_Location**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_resize_location(google_protobuf_SourceCodeInfo *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_SourceCodeInfo_Location**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_SourceCodeInfo_Location**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_SourceCodeInfo_Location* google_protobuf_SourceCodeInfo_add_location(google_protobuf_SourceCodeInfo *msg, upb_arena *arena) {
- struct google_protobuf_SourceCodeInfo_Location* sub = (struct google_protobuf_SourceCodeInfo_Location*)upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
+ struct google_protobuf_SourceCodeInfo_Location* sub = (struct google_protobuf_SourceCodeInfo_Location*)_upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2779,7 +2949,7 @@
/* google.protobuf.SourceCodeInfo.Location */
UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_new(upb_arena *arena) {
- return (google_protobuf_SourceCodeInfo_Location *)upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
+ return (google_protobuf_SourceCodeInfo_Location *)_upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
}
UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2793,54 +2963,54 @@
UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_path(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_span(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_has_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_has_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)); }
+UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
UPB_INLINE upb_strview const* google_protobuf_SourceCodeInfo_Location_leading_detached_comments(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_path(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_path(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_path(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(20, 40), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(20, 40), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_span(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_span(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_span(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(24, 48), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(24, 48), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_leading_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_trailing_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
}
UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_mutable_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
}
UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_resize_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(28, 56), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(28, 56), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
/* google.protobuf.GeneratedCodeInfo */
UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_new(upb_arena *arena) {
- return (google_protobuf_GeneratedCodeInfo *)upb_msg_new(&google_protobuf_GeneratedCodeInfo_msginit, arena);
+ return (google_protobuf_GeneratedCodeInfo *)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_msginit, arena);
}
UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2851,16 +3021,17 @@
return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_GeneratedCodeInfo_has_annotation(const google_protobuf_GeneratedCodeInfo *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_GeneratedCodeInfo_Annotation* const* google_protobuf_GeneratedCodeInfo_annotation(const google_protobuf_GeneratedCodeInfo *msg, size_t *len) { return (const google_protobuf_GeneratedCodeInfo_Annotation* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_mutable_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t *len) {
return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_resize_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_GeneratedCodeInfo_Annotation* google_protobuf_GeneratedCodeInfo_add_annotation(google_protobuf_GeneratedCodeInfo *msg, upb_arena *arena) {
- struct google_protobuf_GeneratedCodeInfo_Annotation* sub = (struct google_protobuf_GeneratedCodeInfo_Annotation*)upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
+ struct google_protobuf_GeneratedCodeInfo_Annotation* sub = (struct google_protobuf_GeneratedCodeInfo_Annotation*)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2870,7 +3041,7 @@
/* google.protobuf.GeneratedCodeInfo.Annotation */
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_new(upb_arena *arena) {
- return (google_protobuf_GeneratedCodeInfo_Annotation *)upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
+ return (google_protobuf_GeneratedCodeInfo_Annotation *)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
}
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2883,33 +3054,33 @@
UPB_INLINE int32_t const* google_protobuf_GeneratedCodeInfo_Annotation_path(const google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 32), len); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE upb_strview google_protobuf_GeneratedCodeInfo_Annotation_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 16)); }
+UPB_INLINE upb_strview google_protobuf_GeneratedCodeInfo_Annotation_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_mutable_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 32), len);
}
UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_resize_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 32), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 32), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_add_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(20, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(20, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_source_file(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_strview value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview) = value;
}
UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_begin(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_end(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
#ifdef __cplusplus
@@ -2922,38 +3093,23 @@
** Defs are upb's internal representation of the constructs that can appear
** in a .proto file:
**
-** - upb::MessageDefPtr (upb_msgdef): describes a "message" construct.
-** - upb::FieldDefPtr (upb_fielddef): describes a message field.
-** - upb::FileDefPtr (upb_filedef): describes a .proto file and its defs.
-** - upb::EnumDefPtr (upb_enumdef): describes an enum.
-** - upb::OneofDefPtr (upb_oneofdef): describes a oneof.
+** - upb_msgdef: describes a "message" construct.
+** - upb_fielddef: describes a message field.
+** - upb_filedef: describes a .proto file and its defs.
+** - upb_enumdef: describes an enum.
+** - upb_oneofdef: describes a oneof.
**
** TODO: definitions of services.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
*/
#ifndef UPB_DEF_H_
#define UPB_DEF_H_
+
#ifdef __cplusplus
-#include <cstring>
-#include <memory>
-#include <string>
-#include <vector>
-
-namespace upb {
-class EnumDefPtr;
-class FieldDefPtr;
-class FileDefPtr;
-class MessageDefPtr;
-class OneofDefPtr;
-class SymbolTable;
-}
-#endif
-
+extern "C" {
+#endif /* __cplusplus */
struct upb_enumdef;
typedef struct upb_enumdef upb_enumdef;
@@ -3005,22 +3161,20 @@
* protobuf wire format. */
#define UPB_MAX_FIELDNUMBER ((1 << 29) - 1)
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_fielddef_fullname(const upb_fielddef *f);
upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f);
upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f);
upb_label_t upb_fielddef_label(const upb_fielddef *f);
uint32_t upb_fielddef_number(const upb_fielddef *f);
const char *upb_fielddef_name(const upb_fielddef *f);
+const char *upb_fielddef_jsonname(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_filedef *upb_fielddef_file(const upb_fielddef *f);
const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f);
const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f);
+const upb_oneofdef *upb_fielddef_realcontainingoneof(const upb_fielddef *f);
uint32_t upb_fielddef_index(const upb_fielddef *f);
bool upb_fielddef_issubmsg(const upb_fielddef *f);
bool upb_fielddef_isstring(const upb_fielddef *f);
@@ -3039,155 +3193,20 @@
bool upb_fielddef_haspresence(const upb_fielddef *f);
const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f);
const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f);
+const upb_msglayout_field *upb_fielddef_layout(const upb_fielddef *f);
/* Internal only. */
uint32_t upb_fielddef_selectorbase(const upb_fielddef *f);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* A upb_fielddef describes a single field in a message. It is most often
- * found as a part of a upb_msgdef, but can also stand alone to represent
- * an extension. */
-class upb::FieldDefPtr {
- public:
- FieldDefPtr() : ptr_(nullptr) {}
- explicit FieldDefPtr(const upb_fielddef *ptr) : ptr_(ptr) {}
-
- const upb_fielddef* ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- typedef upb_fieldtype_t Type;
- typedef upb_label_t Label;
- typedef upb_descriptortype_t DescriptorType;
-
- const char* full_name() const { return upb_fielddef_fullname(ptr_); }
-
- Type type() const { return upb_fielddef_type(ptr_); }
- Label label() const { return upb_fielddef_label(ptr_); }
- const char* name() const { return upb_fielddef_name(ptr_); }
- uint32_t number() const { return upb_fielddef_number(ptr_); }
- bool is_extension() const { return upb_fielddef_isextension(ptr_); }
-
- /* 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 {
- return upb_fielddef_getjsonname(ptr_, buf, len);
- }
-
- /* 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.
- *
- * TODO(haberman): I think we want to move this into a FieldOptions container
- * when we add support for custom options (the FieldOptions struct will
- * contain both regular FieldOptions like "lazy" *and* custom options). */
- bool lazy() const { return upb_fielddef_lazy(ptr_); }
-
- /* For non-string, non-submessage fields, this indicates whether binary
- * protobufs are encoded in packed or non-packed format.
- *
- * TODO(haberman): see note above about putting options like this into a
- * FieldOptions container. */
- bool packed() const { return upb_fielddef_packed(ptr_); }
-
- /* An integer that can be used as an index into an array of fields for
- * 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. */
- uint32_t index() const { return upb_fielddef_index(ptr_); }
-
- /* The MessageDef to which this field belongs.
- *
- * If this field has been added to a MessageDef, that message can be retrieved
- * directly (this is always the case for frozen FieldDefs).
- *
- * If the field has not yet been added to a MessageDef, you can set the name
- * of the containing type symbolically instead. This is mostly useful for
- * extensions, where the extension is declared separately from the message. */
- MessageDefPtr containing_type() const;
-
- /* The OneofDef to which this field belongs, or NULL if this field is not part
- * of a oneof. */
- OneofDefPtr containing_oneof() const;
-
- /* The field's type according to the enum in descriptor.proto. This is not
- * the same as UPB_TYPE_*, because it distinguishes between (for example)
- * INT32 and SINT32, whereas our "type" enum does not. This return of
- * descriptor_type() is a function of type(), integer_format(), and
- * is_tag_delimited(). */
- DescriptorType descriptor_type() const {
- return upb_fielddef_descriptortype(ptr_);
- }
-
- /* Convenient field type tests. */
- bool IsSubMessage() const { return upb_fielddef_issubmsg(ptr_); }
- bool IsString() const { return upb_fielddef_isstring(ptr_); }
- bool IsSequence() const { return upb_fielddef_isseq(ptr_); }
- bool IsPrimitive() const { return upb_fielddef_isprimitive(ptr_); }
- bool IsMap() const { return upb_fielddef_ismap(ptr_); }
-
- /* Returns the non-string default value for this fielddef, which may either
- * be something the client set explicitly or the "default default" (0 for
- * numbers, empty for strings). The field's type indicates the type of the
- * returned value, except for enum fields that are still mutable.
- *
- * Requires that the given function matches the field's current type. */
- int64_t default_int64() const { return upb_fielddef_defaultint64(ptr_); }
- int32_t default_int32() const { return upb_fielddef_defaultint32(ptr_); }
- uint64_t default_uint64() const { return upb_fielddef_defaultuint64(ptr_); }
- uint32_t default_uint32() const { return upb_fielddef_defaultuint32(ptr_); }
- bool default_bool() const { return upb_fielddef_defaultbool(ptr_); }
- float default_float() const { return upb_fielddef_defaultfloat(ptr_); }
- double default_double() const { return upb_fielddef_defaultdouble(ptr_); }
-
- /* The resulting string is always NULL-terminated. If non-NULL, the length
- * will be stored in *len. */
- const char *default_string(size_t * len) const {
- return upb_fielddef_defaultstr(ptr_, len);
- }
-
- /* Returns the enum or submessage def for this field, if any. The field's
- * type must match (ie. you may only call enum_subdef() for fields where
- * type() == UPB_TYPE_ENUM). */
- EnumDefPtr enum_subdef() const;
- MessageDefPtr message_subdef() const;
-
- private:
- const upb_fielddef *ptr_;
-};
-
-#endif /* __cplusplus */
-
/* upb_oneofdef ***************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
typedef upb_inttable_iter upb_oneof_iter;
const char *upb_oneofdef_name(const upb_oneofdef *o);
const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o);
int upb_oneofdef_numfields(const upb_oneofdef *o);
uint32_t upb_oneofdef_index(const upb_oneofdef *o);
+bool upb_oneofdef_issynthetic(const upb_oneofdef *o);
/* Oneof lookups:
* - ntof: look up a field by name.
@@ -3214,92 +3233,6 @@
bool upb_oneof_iter_isequal(const upb_oneof_iter *iter1,
const upb_oneof_iter *iter2);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* Class that represents a oneof. */
-class upb::OneofDefPtr {
- public:
- OneofDefPtr() : ptr_(nullptr) {}
- explicit OneofDefPtr(const upb_oneofdef *ptr) : ptr_(ptr) {}
-
- const upb_oneofdef* ptr() const { return ptr_; }
- explicit operator bool() { return ptr_ != nullptr; }
-
- /* Returns the MessageDef that owns this OneofDef. */
- MessageDefPtr containing_type() const;
-
- /* Returns the name of this oneof. This is the name used to look up the oneof
- * by name once added to a message def. */
- const char* name() const { return upb_oneofdef_name(ptr_); }
-
- /* Returns the number of fields currently defined in the oneof. */
- int field_count() const { return upb_oneofdef_numfields(ptr_); }
-
- /* Looks up by name. */
- FieldDefPtr FindFieldByName(const char *name, size_t len) const {
- return FieldDefPtr(upb_oneofdef_ntof(ptr_, name, len));
- }
- FieldDefPtr FindFieldByName(const char* name) const {
- return FieldDefPtr(upb_oneofdef_ntofz(ptr_, name));
- }
-
- template <class T>
- FieldDefPtr FindFieldByName(const T& str) const {
- return FindFieldByName(str.c_str(), str.size());
- }
-
- /* Looks up by tag number. */
- FieldDefPtr FindFieldByNumber(uint32_t num) const {
- return FieldDefPtr(upb_oneofdef_itof(ptr_, num));
- }
-
- class const_iterator
- : public std::iterator<std::forward_iterator_tag, FieldDefPtr> {
- public:
- void operator++() { upb_oneof_next(&iter_); }
-
- FieldDefPtr operator*() const {
- return FieldDefPtr(upb_oneof_iter_field(&iter_));
- }
-
- bool operator!=(const const_iterator& other) const {
- return !upb_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- bool operator==(const const_iterator& other) const {
- return upb_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- private:
- friend class OneofDefPtr;
-
- const_iterator() {}
- explicit const_iterator(OneofDefPtr o) {
- upb_oneof_begin(&iter_, o.ptr());
- }
- static const_iterator end() {
- const_iterator iter;
- upb_oneof_iter_setdone(&iter.iter_);
- return iter;
- }
-
- upb_oneof_iter iter_;
- };
-
- const_iterator begin() const { return const_iterator(*this); }
- const_iterator end() const { return const_iterator::end(); }
-
- private:
- const upb_oneofdef *ptr_;
-};
-
-inline upb::OneofDefPtr upb::FieldDefPtr::containing_oneof() const {
- return OneofDefPtr(upb_fielddef_containingoneof(ptr_));
-}
-
-#endif /* __cplusplus */
-
/* upb_msgdef *****************************************************************/
typedef upb_inttable_iter upb_msg_field_iter;
@@ -3321,26 +3254,23 @@
#define UPB_TIMESTAMP_SECONDS 1
#define UPB_TIMESTAMP_NANOS 2
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_msgdef_fullname(const upb_msgdef *m);
const upb_filedef *upb_msgdef_file(const upb_msgdef *m);
const char *upb_msgdef_name(const upb_msgdef *m);
+int upb_msgdef_numfields(const upb_msgdef *m);
int upb_msgdef_numoneofs(const upb_msgdef *m);
+int upb_msgdef_numrealoneofs(const upb_msgdef *m);
upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m);
bool upb_msgdef_mapentry(const upb_msgdef *m);
upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m);
bool upb_msgdef_isnumberwrapper(const upb_msgdef *m);
-bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax);
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);
const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
size_t len);
-int upb_msgdef_numfields(const upb_msgdef *m);
-int upb_msgdef_numoneofs(const upb_msgdef *m);
+const upb_msglayout *upb_msgdef_layout(const upb_msgdef *m);
+const upb_fielddef *_upb_msgdef_field(const upb_msgdef *m, int i);
UPB_INLINE const upb_oneofdef *upb_msgdef_ntooz(const upb_msgdef *m,
const char *name) {
@@ -3368,6 +3298,10 @@
return upb_msgdef_lookupname(m, name, strlen(name), f, o);
}
+/* Returns a field by either JSON name or regular proto name. */
+const upb_fielddef *upb_msgdef_lookupjsonname(const upb_msgdef *m,
+ const char *name, size_t len);
+
/* Iteration over fields and oneofs. For example:
*
* upb_msg_field_iter i;
@@ -3399,194 +3333,6 @@
bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
const upb_msg_oneof_iter *iter2);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* Structure that describes a single .proto message type. */
-class upb::MessageDefPtr {
- public:
- MessageDefPtr() : ptr_(nullptr) {}
- explicit MessageDefPtr(const upb_msgdef *ptr) : ptr_(ptr) {}
-
- const upb_msgdef *ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- const char* full_name() const { return upb_msgdef_fullname(ptr_); }
- const char* name() const { return upb_msgdef_name(ptr_); }
-
- /* The number of fields that belong to the MessageDef. */
- int field_count() const { return upb_msgdef_numfields(ptr_); }
-
- /* The number of oneofs that belong to the MessageDef. */
- int oneof_count() const { return upb_msgdef_numoneofs(ptr_); }
-
- upb_syntax_t syntax() const { return upb_msgdef_syntax(ptr_); }
-
- /* These return null pointers if the field is not found. */
- FieldDefPtr FindFieldByNumber(uint32_t number) const {
- return FieldDefPtr(upb_msgdef_itof(ptr_, number));
- }
- FieldDefPtr FindFieldByName(const char* name, size_t len) const {
- return FieldDefPtr(upb_msgdef_ntof(ptr_, name, len));
- }
- FieldDefPtr FindFieldByName(const char *name) const {
- return FieldDefPtr(upb_msgdef_ntofz(ptr_, name));
- }
-
- template <class T>
- FieldDefPtr FindFieldByName(const T& str) const {
- return FindFieldByName(str.c_str(), str.size());
- }
-
- OneofDefPtr FindOneofByName(const char* name, size_t len) const {
- return OneofDefPtr(upb_msgdef_ntoo(ptr_, name, len));
- }
-
- OneofDefPtr FindOneofByName(const char *name) const {
- return OneofDefPtr(upb_msgdef_ntooz(ptr_, name));
- }
-
- template <class T>
- OneofDefPtr FindOneofByName(const T &str) const {
- return FindOneofByName(str.c_str(), str.size());
- }
-
- /* Is this message a map entry? */
- bool mapentry() const { return upb_msgdef_mapentry(ptr_); }
-
- /* Return the type of well known type message. UPB_WELLKNOWN_UNSPECIFIED for
- * non-well-known message. */
- upb_wellknowntype_t wellknowntype() const {
- return upb_msgdef_wellknowntype(ptr_);
- }
-
- /* Whether is a number wrapper. */
- bool isnumberwrapper() const { return upb_msgdef_isnumberwrapper(ptr_); }
-
- /* Iteration over fields. The order is undefined. */
- class const_field_iterator
- : public std::iterator<std::forward_iterator_tag, FieldDefPtr> {
- public:
- void operator++() { upb_msg_field_next(&iter_); }
-
- FieldDefPtr operator*() const {
- return FieldDefPtr(upb_msg_iter_field(&iter_));
- }
-
- bool operator!=(const const_field_iterator &other) const {
- return !upb_msg_field_iter_isequal(&iter_, &other.iter_);
- }
-
- bool operator==(const const_field_iterator &other) const {
- return upb_msg_field_iter_isequal(&iter_, &other.iter_);
- }
-
- private:
- friend class MessageDefPtr;
-
- explicit const_field_iterator() {}
-
- explicit const_field_iterator(MessageDefPtr msg) {
- upb_msg_field_begin(&iter_, msg.ptr());
- }
-
- static const_field_iterator end() {
- const_field_iterator iter;
- upb_msg_field_iter_setdone(&iter.iter_);
- return iter;
- }
-
- upb_msg_field_iter iter_;
- };
-
- /* Iteration over oneofs. The order is undefined. */
- class const_oneof_iterator
- : public std::iterator<std::forward_iterator_tag, OneofDefPtr> {
- public:
-
- void operator++() { upb_msg_oneof_next(&iter_); }
-
- OneofDefPtr operator*() const {
- return OneofDefPtr(upb_msg_iter_oneof(&iter_));
- }
-
- bool operator!=(const const_oneof_iterator& other) const {
- return !upb_msg_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- bool operator==(const const_oneof_iterator &other) const {
- return upb_msg_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- private:
- friend class MessageDefPtr;
-
- const_oneof_iterator() {}
-
- explicit const_oneof_iterator(MessageDefPtr msg) {
- upb_msg_oneof_begin(&iter_, msg.ptr());
- }
-
- static const_oneof_iterator end() {
- const_oneof_iterator iter;
- upb_msg_oneof_iter_setdone(&iter.iter_);
- return iter;
- }
-
- upb_msg_oneof_iter iter_;
- };
-
- class ConstFieldAccessor {
- public:
- explicit ConstFieldAccessor(const upb_msgdef* md) : md_(md) {}
- const_field_iterator begin() { return MessageDefPtr(md_).field_begin(); }
- const_field_iterator end() { return MessageDefPtr(md_).field_end(); }
- private:
- const upb_msgdef* md_;
- };
-
- class ConstOneofAccessor {
- public:
- explicit ConstOneofAccessor(const upb_msgdef* md) : md_(md) {}
- const_oneof_iterator begin() { return MessageDefPtr(md_).oneof_begin(); }
- const_oneof_iterator end() { return MessageDefPtr(md_).oneof_end(); }
- private:
- const upb_msgdef* md_;
- };
-
- const_field_iterator field_begin() const {
- return const_field_iterator(*this);
- }
-
- const_field_iterator field_end() const { return const_field_iterator::end(); }
-
- const_oneof_iterator oneof_begin() const {
- return const_oneof_iterator(*this);
- }
-
- const_oneof_iterator oneof_end() const { return const_oneof_iterator::end(); }
-
- ConstFieldAccessor fields() const { return ConstFieldAccessor(ptr()); }
- ConstOneofAccessor oneofs() const { return ConstOneofAccessor(ptr()); }
-
- private:
- const upb_msgdef* ptr_;
-};
-
-inline upb::MessageDefPtr upb::FieldDefPtr::message_subdef() const {
- return MessageDefPtr(upb_fielddef_msgsubdef(ptr_));
-}
-
-inline upb::MessageDefPtr upb::FieldDefPtr::containing_type() const {
- return MessageDefPtr(upb_fielddef_containingtype(ptr_));
-}
-
-inline upb::MessageDefPtr upb::OneofDefPtr::containing_type() const {
- return MessageDefPtr(upb_oneofdef_containingtype(ptr_));
-}
-
-#endif /* __cplusplus */
-
/* upb_enumdef ****************************************************************/
typedef upb_strtable_iter upb_enum_iter;
@@ -3621,75 +3367,8 @@
const char *upb_enum_iter_name(upb_enum_iter *iter);
int32_t upb_enum_iter_number(upb_enum_iter *iter);
-#ifdef __cplusplus
-
-class upb::EnumDefPtr {
- public:
- EnumDefPtr() : ptr_(nullptr) {}
- explicit EnumDefPtr(const upb_enumdef* ptr) : ptr_(ptr) {}
-
- const upb_enumdef* ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- const char* full_name() const { return upb_enumdef_fullname(ptr_); }
- const char* name() const { return upb_enumdef_name(ptr_); }
-
- /* The value that is used as the default when no field default is specified.
- * If not set explicitly, the first value that was added will be used.
- * The default value must be a member of the enum.
- * Requires that value_count() > 0. */
- int32_t default_value() const { return upb_enumdef_default(ptr_); }
-
- /* Returns the number of values currently defined in the enum. Note that
- * multiple names can refer to the same number, so this may be greater than
- * the total number of unique numbers. */
- int value_count() const { return upb_enumdef_numvals(ptr_); }
-
- /* Lookups from name to integer, returning true if found. */
- bool FindValueByName(const char *name, int32_t *num) const {
- return upb_enumdef_ntoiz(ptr_, name, num);
- }
-
- /* Finds the name corresponding to the given number, or NULL if none was
- * found. If more than one name corresponds to this number, returns the
- * first one that was added. */
- const char *FindValueByNumber(int32_t num) const {
- return upb_enumdef_iton(ptr_, num);
- }
-
- /* Iteration over name/value pairs. The order is undefined.
- * Adding an enum val invalidates any iterators.
- *
- * TODO: make compatible with range-for, with elements as pairs? */
- class Iterator {
- public:
- explicit Iterator(EnumDefPtr e) { upb_enum_begin(&iter_, e.ptr()); }
-
- int32_t number() { return upb_enum_iter_number(&iter_); }
- const char *name() { return upb_enum_iter_name(&iter_); }
- bool Done() { return upb_enum_done(&iter_); }
- void Next() { return upb_enum_next(&iter_); }
-
- private:
- upb_enum_iter iter_;
- };
-
- private:
- const upb_enumdef *ptr_;
-};
-
-inline upb::EnumDefPtr upb::FieldDefPtr::enum_subdef() const {
- return EnumDefPtr(upb_fielddef_enumsubdef(ptr_));
-}
-
-#endif /* __cplusplus */
-
/* upb_filedef ****************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_filedef_name(const upb_filedef *f);
const char *upb_filedef_package(const upb_filedef *f);
const char *upb_filedef_phpprefix(const upb_filedef *f);
@@ -3702,57 +3381,8 @@
const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i);
const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* 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::FileDefPtr {
- public:
- explicit FileDefPtr(const upb_filedef *ptr) : ptr_(ptr) {}
-
- const upb_filedef* ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- /* Get/set name of the file (eg. "foo/bar.proto"). */
- const char* name() const { return upb_filedef_name(ptr_); }
-
- /* Package name for definitions inside the file (eg. "foo.bar"). */
- const char* package() const { return upb_filedef_package(ptr_); }
-
- /* Sets the php class prefix which is prepended to all php generated classes
- * from this .proto. Default is empty. */
- const char* phpprefix() const { return upb_filedef_phpprefix(ptr_); }
-
- /* Use this option to change the namespace of php generated classes. Default
- * is empty. When this option is empty, the package name will be used for
- * determining the namespace. */
- const char* phpnamespace() const { return upb_filedef_phpnamespace(ptr_); }
-
- /* Syntax for the file. Defaults to proto2. */
- upb_syntax_t syntax() const { return upb_filedef_syntax(ptr_); }
-
- /* Get the list of dependencies from the file. These are returned in the
- * order that they were added to the FileDefPtr. */
- int dependency_count() const { return upb_filedef_depcount(ptr_); }
- const FileDefPtr dependency(int index) const {
- return FileDefPtr(upb_filedef_dep(ptr_, index));
- }
-
- private:
- const upb_filedef* ptr_;
-};
-
-#endif /* __cplusplus */
-
/* upb_symtab *****************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
upb_symtab *upb_symtab_new(void);
void upb_symtab_free(upb_symtab* s);
const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
@@ -3769,107 +3399,171 @@
/* For generated code only: loads a generated descriptor. */
typedef struct upb_def_init {
- struct upb_def_init **deps;
+ struct upb_def_init **deps; /* Dependencies of this file. */
+ const upb_msglayout **layouts; /* Pre-order layouts of all messages. */
const char *filename;
- upb_strview descriptor;
+ upb_strview descriptor; /* Serialized descriptor. */
} upb_def_init;
bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init);
+
#ifdef __cplusplus
} /* extern "C" */
-
-/* Non-const methods in upb::SymbolTable are NOT thread-safe. */
-class upb::SymbolTable {
- public:
- SymbolTable() : ptr_(upb_symtab_new(), upb_symtab_free) {}
- explicit SymbolTable(upb_symtab* s) : ptr_(s, upb_symtab_free) {}
-
- const upb_symtab* ptr() const { return ptr_.get(); }
- upb_symtab* ptr() { return ptr_.get(); }
-
- /* Finds an entry in the symbol table with this exact name. If not found,
- * returns NULL. */
- MessageDefPtr LookupMessage(const char *sym) const {
- return MessageDefPtr(upb_symtab_lookupmsg(ptr_.get(), sym));
- }
-
- EnumDefPtr LookupEnum(const char *sym) const {
- return EnumDefPtr(upb_symtab_lookupenum(ptr_.get(), sym));
- }
-
- FileDefPtr LookupFile(const char *name) const {
- return FileDefPtr(upb_symtab_lookupfile(ptr_.get(), name));
- }
-
- /* TODO: iteration? */
-
- /* Adds the given serialized FileDescriptorProto to the pool. */
- FileDefPtr AddFile(const google_protobuf_FileDescriptorProto *file_proto,
- Status *status) {
- return FileDefPtr(
- upb_symtab_addfile(ptr_.get(), file_proto, status->ptr()));
- }
-
- private:
- std::unique_ptr<upb_symtab, decltype(&upb_symtab_free)> ptr_;
-};
-
-UPB_INLINE const char* upb_safecstr(const std::string& str) {
- UPB_ASSERT(str.size() == std::strlen(str.c_str()));
- return str.c_str();
-}
-
#endif /* __cplusplus */
-
#endif /* UPB_DEF_H_ */
+#ifndef UPB_REFLECTION_H_
+#define UPB_REFLECTION_H_
-#ifndef UPB_MSGFACTORY_H_
-#define UPB_MSGFACTORY_H_
-/** upb_msgfactory ************************************************************/
-struct upb_msgfactory;
-typedef struct upb_msgfactory upb_msgfactory;
+typedef union {
+ bool bool_val;
+ float float_val;
+ double double_val;
+ int32_t int32_val;
+ int64_t int64_val;
+ uint32_t uint32_val;
+ uint64_t uint64_val;
+ const upb_map* map_val;
+ const upb_msg* msg_val;
+ const upb_array* array_val;
+ upb_strview str_val;
+} upb_msgval;
-#ifdef __cplusplus
-extern "C" {
-#endif
+typedef union {
+ upb_map* map;
+ upb_msg* msg;
+ upb_array* array;
+} upb_mutmsgval;
-/* A upb_msgfactory contains a cache of upb_msglayout, upb_handlers, and
- * upb_visitorplan objects. These are the objects necessary to represent,
- * populate, and and visit upb_msg objects.
+/** upb_msg *******************************************************************/
+
+/* Creates a new message of the given type in the given arena. */
+upb_msg *upb_msg_new(const upb_msgdef *m, upb_arena *a);
+
+/* Returns the value associated with this field. */
+upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f);
+
+/* Returns a mutable pointer to a map, array, or submessage value. If the given
+ * arena is non-NULL this will construct a new object if it was not previously
+ * present. May not be called for primitive fields. */
+upb_mutmsgval upb_msg_mutable(upb_msg *msg, const upb_fielddef *f, upb_arena *a);
+
+/* May only be called for fields where upb_fielddef_haspresence(f) == true. */
+bool upb_msg_has(const upb_msg *msg, const upb_fielddef *f);
+
+/* Returns whether any field is set in the oneof. */
+bool upb_msg_hasoneof(const upb_msg *msg, const upb_oneofdef *o);
+
+/* Sets the given field to the given value. For a msg/array/map/string, the
+ * value must be in the same arena. */
+void upb_msg_set(upb_msg *msg, const upb_fielddef *f, upb_msgval val,
+ upb_arena *a);
+
+/* Clears any field presence and sets the value back to its default. */
+void upb_msg_clearfield(upb_msg *msg, const upb_fielddef *f);
+
+/* Iterate over present fields.
*
- * These caches are all populated by upb_msgdef, and lazily created on demand.
+ * size_t iter = UPB_MSG_BEGIN;
+ * const upb_fielddef *f;
+ * upb_msgval val;
+ * while (upb_msg_next(msg, m, ext_pool, &f, &val, &iter)) {
+ * process_field(f, val);
+ * }
+ *
+ * If ext_pool is NULL, no extensions will be returned. If the given symtab
+ * returns extensions that don't match what is in this message, those extensions
+ * will be skipped.
*/
-/* Creates and destroys a msgfactory, respectively. The messages for this
- * msgfactory must come from |symtab| (which should outlive the msgfactory). */
-upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab);
-void upb_msgfactory_free(upb_msgfactory *f);
+#define UPB_MSG_BEGIN -1
+bool upb_msg_next(const upb_msg *msg, const upb_msgdef *m,
+ const upb_symtab *ext_pool, const upb_fielddef **f,
+ upb_msgval *val, size_t *iter);
-const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f);
+/* Adds unknown data (serialized protobuf data) to the given message. The data
+ * is copied into the message instance. */
+void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
+ upb_arena *arena);
-/* The functions to get cached objects, lazily creating them on demand. These
- * all require:
+/* Returns a reference to the message's unknown data. */
+const char *upb_msg_getunknown(const upb_msg *msg, size_t *len);
+
+/** upb_array *****************************************************************/
+
+/* Creates a new array on the given arena that holds elements of this type. */
+upb_array *upb_array_new(upb_arena *a, upb_fieldtype_t type);
+
+/* Returns the size of the array. */
+size_t upb_array_size(const upb_array *arr);
+
+/* Returns the given element, which must be within the array's current size. */
+upb_msgval upb_array_get(const upb_array *arr, size_t i);
+
+/* Sets the given element, which must be within the array's current size. */
+void upb_array_set(upb_array *arr, size_t i, upb_msgval val);
+
+/* Appends an element to the array. Returns false on allocation failure. */
+bool upb_array_append(upb_array *array, upb_msgval val, upb_arena *arena);
+
+/* Changes the size of a vector. New elements are initialized to empty/0.
+ * Returns false on allocation failure. */
+bool upb_array_resize(upb_array *array, size_t size, upb_arena *arena);
+
+/** upb_map *******************************************************************/
+
+/* Creates a new map on the given arena with the given key/value size. */
+upb_map *upb_map_new(upb_arena *a, upb_fieldtype_t key_type,
+ upb_fieldtype_t value_type);
+
+/* Returns the number of entries in the map. */
+size_t upb_map_size(const upb_map *map);
+
+/* Stores a value for the given key into |*val| (or the zero value if the key is
+ * not present). Returns whether the key was present. The |val| pointer may be
+ * NULL, in which case the function tests whether the given key is present. */
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val);
+
+/* Removes all entries in the map. */
+void upb_map_clear(upb_map *map);
+
+/* Sets the given key to the given value. Returns true if this was a new key in
+ * the map, or false if an existing key was replaced. */
+bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
+ upb_arena *arena);
+
+/* Deletes this key from the table. Returns true if the key was present. */
+bool upb_map_delete(upb_map *map, upb_msgval key);
+
+/* Map iteration:
*
- * - m is in upb_msgfactory_symtab(f)
- * - upb_msgdef_mapentry(m) == false (since map messages can't have layouts).
+ * size_t iter = UPB_MAP_BEGIN;
+ * while (upb_mapiter_next(map, &iter)) {
+ * upb_msgval key = upb_mapiter_key(map, iter);
+ * upb_msgval val = upb_mapiter_value(map, iter);
*
- * The returned objects will live for as long as the msgfactory does.
- *
- * TODO(haberman): consider making this thread-safe and take a const
- * upb_msgfactory. */
-const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
- const upb_msgdef *m);
+ * // If mutating is desired.
+ * upb_mapiter_setvalue(map, iter, value2);
+ * }
+ */
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
+/* Advances to the next entry. Returns false if no more entries are present. */
+bool upb_mapiter_next(const upb_map *map, size_t *iter);
-#endif /* UPB_MSGFACTORY_H_ */
+/* Returns the key and value for this entry of the map. */
+upb_msgval upb_mapiter_key(const upb_map *map, size_t iter);
+upb_msgval upb_mapiter_value(const upb_map *map, size_t iter);
+
+/* Sets the value for this entry. The iterator must not be done, and the
+ * iterator must not have been initialized const. */
+void upb_mapiter_setvalue(upb_map *map, size_t iter, upb_msgval value);
+
+
+#endif /* UPB_REFLECTION_H_ */
/*
** upb::Handlers (upb_handlers)
**
@@ -6577,21 +6271,22 @@
* descriptor type (upb_descriptortype_t). */
extern const uint8_t upb_pb_native_wire_types[];
-UPB_INLINE uint64_t byteswap64(uint64_t val)
-{
- return ((((val) & 0xff00000000000000ull) >> 56)
- | (((val) & 0x00ff000000000000ull) >> 40)
- | (((val) & 0x0000ff0000000000ull) >> 24)
- | (((val) & 0x000000ff00000000ull) >> 8)
- | (((val) & 0x00000000ff000000ull) << 8)
- | (((val) & 0x0000000000ff0000ull) << 24)
- | (((val) & 0x000000000000ff00ull) << 40)
- | (((val) & 0x00000000000000ffull) << 56));
+UPB_INLINE uint64_t byteswap64(uint64_t val) {
+ uint64_t byte = 0xff;
+ return (val & (byte << 56) >> 56)
+ | (val & (byte << 48) >> 40)
+ | (val & (byte << 40) >> 24)
+ | (val & (byte << 32) >> 8)
+ | (val & (byte << 24) << 8)
+ | (val & (byte << 16) << 24)
+ | (val & (byte << 8) << 40)
+ | (val & (byte << 0) << 56);
}
/* Zig-zag encoding/decoding **************************************************/
-UPB_INLINE int32_t upb_zzdec_32(uint32_t n) {
+UPB_INLINE int32_t upb_zzdec_32(uint64_t _n) {
+ uint32_t n = (uint32_t)_n;
return (n >> 1) ^ -(int32_t)(n & 1);
}
UPB_INLINE int64_t upb_zzdec_64(uint64_t n) {
@@ -7074,17 +6769,23 @@
#endif /* UPB_JSON_TYPED_PRINTER_H_ */
/* See port_def.inc. This should #undef all macros #defined there. */
+#undef UPB_MAPTYPE_STRING
#undef UPB_SIZE
-#undef UPB_FIELD_AT
+#undef UPB_PTR_AT
#undef UPB_READ_ONEOF
#undef UPB_WRITE_ONEOF
#undef UPB_INLINE
+#undef UPB_ALIGN_UP
+#undef UPB_ALIGN_DOWN
+#undef UPB_ALIGN_MALLOC
+#undef UPB_ALIGN_OF
#undef UPB_FORCEINLINE
#undef UPB_NOINLINE
#undef UPB_NORETURN
#undef UPB_MAX
#undef UPB_MIN
#undef UPB_UNUSED
+#undef UPB_ASSUME
#undef UPB_ASSERT
#undef UPB_ASSERT_DEBUGVAR
#undef UPB_UNREACHABLE
diff --git a/php/generate_descriptor_protos.sh b/php/generate_descriptor_protos.sh
index 372ad69..f636cc0 100755
--- a/php/generate_descriptor_protos.sh
+++ b/php/generate_descriptor_protos.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
-# Run this script to regenerate desriptor protos after the protocol compiler
+# Run this script to regenerate descriptor protos after the protocol compiler
# changes.
if test ! -e src/google/protobuf/stubs/common.h; then
diff --git a/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php b/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
index e6362f2..ea0edc5 100644
--- a/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
+++ b/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php
@@ -72,6 +72,7 @@
->optional('oneof_index', \Google\Protobuf\Internal\GPBType::INT32, 9)
->optional('json_name', \Google\Protobuf\Internal\GPBType::STRING, 10)
->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 8, 'google.protobuf.internal.FieldOptions')
+ ->optional('proto3_optional', \Google\Protobuf\Internal\GPBType::BOOL, 17)
->finalizeToPool();
$pool->addEnum('google.protobuf.internal.FieldDescriptorProto.Type', \Google\Protobuf\Internal\Type::class)
diff --git a/php/src/Google/Protobuf/Any.php b/php/src/Google/Protobuf/Any.php
index cdbaa25..166c66a 100644
--- a/php/src/Google/Protobuf/Any.php
+++ b/php/src/Google/Protobuf/Any.php
@@ -251,14 +251,14 @@
* targeted message type. If failed, an error will be thrown. Otherwise,
* the method will create a message of the targeted type and fill it with
* the decoded value in Any.
- * @return unpacked message
- * @throws \Exception Type url needs to be type.googleapis.com/fully-qulified.
+ * @return Message unpacked message
+ * @throws \Exception Type url needs to be type.googleapis.com/fully-qualified.
* @throws \Exception Class hasn't been added to descriptor pool.
* @throws \Exception cannot decode data in value field.
*/
public function unpack()
{
- // Get fully qualifed name from type url.
+ // Get fully qualified name from type url.
$url_prifix_len = strlen(GPBUtil::TYPE_URL_PREFIX);
if (substr($this->type_url, 0, $url_prifix_len) !=
GPBUtil::TYPE_URL_PREFIX) {
@@ -296,7 +296,7 @@
return;
}
- // Set value using serialzed message.
+ // Set value using serialized message.
$this->value = $msg->serializeToString();
// Set type url.
diff --git a/php/src/Google/Protobuf/Internal/CodedInputStream.php b/php/src/Google/Protobuf/Internal/CodedInputStream.php
index 33b1f5a..2ed2dfd 100644
--- a/php/src/Google/Protobuf/Internal/CodedInputStream.php
+++ b/php/src/Google/Protobuf/Internal/CodedInputStream.php
@@ -220,7 +220,7 @@
}
/**
- * Read 32-bit unsiged integer to $var. If the buffer has less than 4 bytes,
+ * Read 32-bit unsigned integer to $var. If the buffer has less than 4 bytes,
* return false. Advance buffer with consumed bytes.
* @param $var.
*/
@@ -236,7 +236,7 @@
}
/**
- * Read 64-bit unsiged integer to $var. If the buffer has less than 8 bytes,
+ * Read 64-bit unsigned integer to $var. If the buffer has less than 8 bytes,
* return false. Advance buffer with consumed bytes.
* @param $var.
*/
@@ -283,7 +283,7 @@
}
$result = 0;
- // The larget tag is 2^29 - 1, which can be represented by int32.
+ // The largest tag is 2^29 - 1, which can be represented by int32.
$success = $this->readVarint32($result);
if ($success) {
return $result;
diff --git a/php/src/Google/Protobuf/Internal/DescriptorPool.php b/php/src/Google/Protobuf/Internal/DescriptorPool.php
index 419bbf4..f96b0fb 100644
--- a/php/src/Google/Protobuf/Internal/DescriptorPool.php
+++ b/php/src/Google/Protobuf/Internal/DescriptorPool.php
@@ -59,22 +59,25 @@
{
$files = new FileDescriptorSet();
$files->mergeFromString($data);
- $file = FileDescriptor::buildFromProto($files->getFile()[0]);
- foreach ($file->getMessageType() as $desc) {
- $this->addDescriptor($desc);
- }
- unset($desc);
+ foreach($files->getFile() as $file_proto) {
+ $file = FileDescriptor::buildFromProto($file_proto);
- foreach ($file->getEnumType() as $desc) {
- $this->addEnumDescriptor($desc);
- }
- unset($desc);
+ foreach ($file->getMessageType() as $desc) {
+ $this->addDescriptor($desc);
+ }
+ unset($desc);
- foreach ($file->getMessageType() as $desc) {
- $this->crossLink($desc);
+ foreach ($file->getEnumType() as $desc) {
+ $this->addEnumDescriptor($desc);
+ }
+ unset($desc);
+
+ foreach ($file->getMessageType() as $desc) {
+ $this->crossLink($desc);
+ }
+ unset($desc);
}
- unset($desc);
}
public function addMessage($name, $klass)
@@ -149,8 +152,13 @@
switch ($field->getType()) {
case GPBType::MESSAGE:
$proto = $field->getMessageType();
- $field->setMessageType(
- $this->getDescriptorByProtoName($proto));
+ $subdesc = $this->getDescriptorByProtoName($proto);
+ if (is_null($subdesc)) {
+ trigger_error(
+ 'proto not added: ' . $proto
+ . " for " . $desc->getFullName(), E_ERROR);
+ }
+ $field->setMessageType($subdesc);
break;
case GPBType::ENUM:
$proto = $field->getEnumType();
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
index b231c9e..b43d988 100644
--- a/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto.php
@@ -93,6 +93,30 @@
*/
protected $options = null;
private $has_options = false;
+ /**
+ * If true, this is a proto3 "optional". When a proto3 field is optional, it
+ * tracks presence regardless of field type.
+ * When proto3_optional is true, this field must be belong to a oneof to
+ * signal to old proto3 clients that presence is tracked for this field. This
+ * oneof is known as a "synthetic" oneof, and this field must be its sole
+ * member (each proto3 optional field gets its own synthetic oneof). Synthetic
+ * oneofs exist in the descriptor only, and do not generate any API. Synthetic
+ * oneofs must be ordered after all "real" oneofs.
+ * For message fields, proto3_optional doesn't create any semantic change,
+ * since non-repeated message fields always track presence. However it still
+ * indicates the semantic detail of whether the user wrote "optional" or not.
+ * This can be useful for round-tripping the .proto file. For consistency we
+ * give message fields a synthetic oneof also, even though it is not required
+ * to track presence. This is especially important because the parser can't
+ * tell if a field is a message or an enum, so it must always create a
+ * synthetic oneof.
+ * Proto2 optional fields do not set this flag, because they already indicate
+ * optional with `LABEL_OPTIONAL`.
+ *
+ * Generated from protobuf field <code>optional bool proto3_optional = 17;</code>
+ */
+ protected $proto3_optional = false;
+ private $has_proto3_optional = false;
/**
* Constructor.
@@ -130,6 +154,25 @@
* will be used. Otherwise, it's deduced from the field's name by converting
* it to camelCase.
* @type \Google\Protobuf\Internal\FieldOptions $options
+ * @type bool $proto3_optional
+ * If true, this is a proto3 "optional". When a proto3 field is optional, it
+ * tracks presence regardless of field type.
+ * When proto3_optional is true, this field must be belong to a oneof to
+ * signal to old proto3 clients that presence is tracked for this field. This
+ * oneof is known as a "synthetic" oneof, and this field must be its sole
+ * member (each proto3 optional field gets its own synthetic oneof). Synthetic
+ * oneofs exist in the descriptor only, and do not generate any API. Synthetic
+ * oneofs must be ordered after all "real" oneofs.
+ * For message fields, proto3_optional doesn't create any semantic change,
+ * since non-repeated message fields always track presence. However it still
+ * indicates the semantic detail of whether the user wrote "optional" or not.
+ * This can be useful for round-tripping the .proto file. For consistency we
+ * give message fields a synthetic oneof also, even though it is not required
+ * to track presence. This is especially important because the parser can't
+ * tell if a field is a message or an enum, so it must always create a
+ * synthetic oneof.
+ * Proto2 optional fields do not set this flag, because they already indicate
+ * optional with `LABEL_OPTIONAL`.
* }
*/
public function __construct($data = NULL) {
@@ -469,5 +512,71 @@
return $this->has_options;
}
+ /**
+ * If true, this is a proto3 "optional". When a proto3 field is optional, it
+ * tracks presence regardless of field type.
+ * When proto3_optional is true, this field must be belong to a oneof to
+ * signal to old proto3 clients that presence is tracked for this field. This
+ * oneof is known as a "synthetic" oneof, and this field must be its sole
+ * member (each proto3 optional field gets its own synthetic oneof). Synthetic
+ * oneofs exist in the descriptor only, and do not generate any API. Synthetic
+ * oneofs must be ordered after all "real" oneofs.
+ * For message fields, proto3_optional doesn't create any semantic change,
+ * since non-repeated message fields always track presence. However it still
+ * indicates the semantic detail of whether the user wrote "optional" or not.
+ * This can be useful for round-tripping the .proto file. For consistency we
+ * give message fields a synthetic oneof also, even though it is not required
+ * to track presence. This is especially important because the parser can't
+ * tell if a field is a message or an enum, so it must always create a
+ * synthetic oneof.
+ * Proto2 optional fields do not set this flag, because they already indicate
+ * optional with `LABEL_OPTIONAL`.
+ *
+ * Generated from protobuf field <code>optional bool proto3_optional = 17;</code>
+ * @return bool
+ */
+ public function getProto3Optional()
+ {
+ return $this->proto3_optional;
+ }
+
+ /**
+ * If true, this is a proto3 "optional". When a proto3 field is optional, it
+ * tracks presence regardless of field type.
+ * When proto3_optional is true, this field must be belong to a oneof to
+ * signal to old proto3 clients that presence is tracked for this field. This
+ * oneof is known as a "synthetic" oneof, and this field must be its sole
+ * member (each proto3 optional field gets its own synthetic oneof). Synthetic
+ * oneofs exist in the descriptor only, and do not generate any API. Synthetic
+ * oneofs must be ordered after all "real" oneofs.
+ * For message fields, proto3_optional doesn't create any semantic change,
+ * since non-repeated message fields always track presence. However it still
+ * indicates the semantic detail of whether the user wrote "optional" or not.
+ * This can be useful for round-tripping the .proto file. For consistency we
+ * give message fields a synthetic oneof also, even though it is not required
+ * to track presence. This is especially important because the parser can't
+ * tell if a field is a message or an enum, so it must always create a
+ * synthetic oneof.
+ * Proto2 optional fields do not set this flag, because they already indicate
+ * optional with `LABEL_OPTIONAL`.
+ *
+ * Generated from protobuf field <code>optional bool proto3_optional = 17;</code>
+ * @param bool $var
+ * @return $this
+ */
+ public function setProto3Optional($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->proto3_optional = $var;
+ $this->has_proto3_optional = true;
+
+ return $this;
+ }
+
+ public function hasProto3Optional()
+ {
+ return $this->has_proto3_optional;
+ }
+
}
diff --git a/php/src/Google/Protobuf/Internal/FileOptions.php b/php/src/Google/Protobuf/Internal/FileOptions.php
index 605d92b..892a6a8 100644
--- a/php/src/Google/Protobuf/Internal/FileOptions.php
+++ b/php/src/Google/Protobuf/Internal/FileOptions.php
@@ -127,7 +127,7 @@
* Enables the use of arenas for the proto messages in this file. This applies
* only to generated classes for C++.
*
- * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = true];</code>
*/
protected $cc_enable_arenas = false;
private $has_cc_enable_arenas = false;
@@ -732,7 +732,7 @@
* Enables the use of arenas for the proto messages in this file. This applies
* only to generated classes for C++.
*
- * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = true];</code>
* @return bool
*/
public function getCcEnableArenas()
@@ -744,7 +744,7 @@
* Enables the use of arenas for the proto messages in this file. This applies
* only to generated classes for C++.
*
- * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = false];</code>
+ * Generated from protobuf field <code>optional bool cc_enable_arenas = 31 [default = true];</code>
* @param bool $var
* @return $this
*/
diff --git a/php/src/Google/Protobuf/Internal/GPBUtil.php b/php/src/Google/Protobuf/Internal/GPBUtil.php
index 7ec3ca2..c091fc6 100644
--- a/php/src/Google/Protobuf/Internal/GPBUtil.php
+++ b/php/src/Google/Protobuf/Internal/GPBUtil.php
@@ -405,7 +405,7 @@
public static function parseTimestamp($timestamp)
{
- // prevent parsing timestamps containing with the non-existant year "0000"
+ // prevent parsing timestamps containing with the non-existent year "0000"
// DateTime::createFromFormat parses without failing but as a nonsensical date
if (substr($timestamp, 0, 4) === "0000") {
throw new \Exception("Year cannot be zero.");
diff --git a/php/src/Google/Protobuf/Internal/Message.php b/php/src/Google/Protobuf/Internal/Message.php
index 1ffb245..77614bc 100644
--- a/php/src/Google/Protobuf/Internal/Message.php
+++ b/php/src/Google/Protobuf/Internal/Message.php
@@ -94,6 +94,7 @@
$this->desc = $pool->getDescriptorByClassName(get_class($this));
if (is_null($this->desc)) {
user_error(get_class($this) . " is not found in descriptor pool.");
+ return;
}
foreach ($this->desc->getField() as $field) {
$setter = $field->getSetter();
@@ -679,8 +680,8 @@
* This method merges the contents of the specified message into the
* current message. Singular fields that are set in the specified message
* overwrite the corresponding fields in the current message. Repeated
- * fields are appended. Map fields key-value pairs are overritten.
- * Singular/Oneof sub-messages are recursively merged. All overritten
+ * fields are appended. Map fields key-value pairs are overwritten.
+ * Singular/Oneof sub-messages are recursively merged. All overwritten
* sub-messages are deep-copied.
*
* @param object $msg Protobuf message to be merged from.
@@ -772,10 +773,10 @@
* @return null.
* @throws \Exception Invalid data.
*/
- public function mergeFromJsonString($data)
+ public function mergeFromJsonString($data, $ignore_unknown = false)
{
$input = new RawInputStream($data);
- $this->parseFromJsonStream($input);
+ $this->parseFromJsonStream($input, $ignore_unknown);
}
/**
@@ -800,6 +801,7 @@
private function convertJsonValueToProtoValue(
$value,
$field,
+ $ignore_unknown,
$is_map_key = false)
{
switch ($field->getType()) {
@@ -848,7 +850,7 @@
} elseif (!is_object($value) && !is_array($value)) {
throw new GPBDecodeException("Expect message.");
}
- $submsg->mergeFromJsonArray($value);
+ $submsg->mergeFromJsonArray($value, $ignore_unknown);
}
return $submsg;
case GPBType::ENUM:
@@ -861,9 +863,12 @@
$enum_value = $field->getEnumType()->getValueByName($value);
if (!is_null($enum_value)) {
return $enum_value->getNumber();
+ } else if ($ignore_unknown) {
+ return $this->defaultValue($field);
+ } else {
+ throw new GPBDecodeException(
+ "Enum field only accepts integer or enum value name");
}
- throw new GPBDecodeException(
- "Enum field only accepts integer or enum value name");
case GPBType::STRING:
if (is_null($value)) {
return $this->defaultValue($field);
@@ -933,6 +938,10 @@
throw new GPBDecodeException(
"Invalid data type for int32 field");
}
+ if (is_string($value) && trim($value) !== $value) {
+ throw new GPBDecodeException(
+ "Invalid data type for int32 field");
+ }
if (bccomp($value, "2147483647") > 0) {
throw new GPBDecodeException(
"Int32 too large");
@@ -951,6 +960,10 @@
throw new GPBDecodeException(
"Invalid data type for uint32 field");
}
+ if (is_string($value) && trim($value) !== $value) {
+ throw new GPBDecodeException(
+ "Invalid data type for int32 field");
+ }
if (bccomp($value, 4294967295) > 0) {
throw new GPBDecodeException(
"Uint32 too large");
@@ -966,6 +979,10 @@
throw new GPBDecodeException(
"Invalid data type for int64 field");
}
+ if (is_string($value) && trim($value) !== $value) {
+ throw new GPBDecodeException(
+ "Invalid data type for int64 field");
+ }
if (bccomp($value, "9223372036854775807") > 0) {
throw new GPBDecodeException(
"Int64 too large");
@@ -984,6 +1001,10 @@
throw new GPBDecodeException(
"Invalid data type for int64 field");
}
+ if (is_string($value) && trim($value) !== $value) {
+ throw new GPBDecodeException(
+ "Invalid data type for int64 field");
+ }
if (bccomp($value, "18446744073709551615") > 0) {
throw new GPBDecodeException(
"Uint64 too large");
@@ -1108,17 +1129,17 @@
}
}
- protected function mergeFromJsonArray($array)
+ protected function mergeFromJsonArray($array, $ignore_unknown)
{
if (is_a($this, "Google\Protobuf\Any")) {
$this->clear();
$this->setTypeUrl($array["@type"]);
$msg = $this->unpack();
if (GPBUtil::hasSpecialJsonMapping($msg)) {
- $msg->mergeFromJsonArray($array["value"]);
+ $msg->mergeFromJsonArray($array["value"], $ignore_unknown);
} else {
unset($array["@type"]);
- $msg->mergeFromJsonArray($array);
+ $msg->mergeFromJsonArray($array, $ignore_unknown);
}
$this->setValue($msg->serializeToString());
return;
@@ -1154,7 +1175,7 @@
$fields = $this->getFields();
foreach($array as $key => $value) {
$v = new Value();
- $v->mergeFromJsonArray($value);
+ $v->mergeFromJsonArray($value, $ignore_unknown);
$fields[$key] = $v;
}
}
@@ -1177,7 +1198,7 @@
}
foreach ($array as $key => $v) {
$value = new Value();
- $value->mergeFromJsonArray($v);
+ $value->mergeFromJsonArray($v, $ignore_unknown);
$values = $struct_value->getFields();
$values[$key]= $value;
}
@@ -1190,7 +1211,7 @@
}
foreach ($array as $v) {
$value = new Value();
- $value->mergeFromJsonArray($v);
+ $value->mergeFromJsonArray($v, $ignore_unknown);
$values = $list_value->getValues();
$values[]= $value;
}
@@ -1200,10 +1221,10 @@
}
return;
}
- $this->mergeFromArrayJsonImpl($array);
+ $this->mergeFromArrayJsonImpl($array, $ignore_unknown);
}
- private function mergeFromArrayJsonImpl($array)
+ private function mergeFromArrayJsonImpl($array, $ignore_unknown)
{
foreach ($array as $key => $value) {
$field = $this->desc->getFieldByJsonName($key);
@@ -1227,10 +1248,12 @@
$proto_key = $this->convertJsonValueToProtoValue(
$tmp_key,
$key_field,
+ $ignore_unknown,
true);
$proto_value = $this->convertJsonValueToProtoValue(
$tmp_value,
- $value_field);
+ $value_field,
+ $ignore_unknown);
self::kvUpdateHelper($field, $proto_key, $proto_value);
}
} else if ($field->isRepeated()) {
@@ -1244,14 +1267,16 @@
}
$proto_value = $this->convertJsonValueToProtoValue(
$tmp,
- $field);
+ $field,
+ $ignore_unknown);
self::appendHelper($field, $proto_value);
}
} else {
$setter = $field->getSetter();
$proto_value = $this->convertJsonValueToProtoValue(
$value,
- $field);
+ $field,
+ $ignore_unknown);
if ($field->getType() === GPBType::MESSAGE) {
if (is_null($proto_value)) {
continue;
@@ -1271,7 +1296,7 @@
/**
* @ignore
*/
- public function parseFromJsonStream($input)
+ public function parseFromJsonStream($input, $ignore_unknown)
{
$array = json_decode($input->getData(), true, 512, JSON_BIGINT_AS_STRING);
if ($this instanceof \Google\Protobuf\ListValue) {
@@ -1287,7 +1312,7 @@
}
}
try {
- $this->mergeFromJsonArray($array);
+ $this->mergeFromJsonArray($array, $ignore_unknown);
} catch (\Exception $e) {
throw new GPBDecodeException($e->getMessage());
}
diff --git a/php/tests/autoload.php b/php/tests/autoload.php
old mode 100755
new mode 100644
diff --git a/php/tests/compatibility_test.sh b/php/tests/compatibility_test.sh
index 8e1a750..2b5c6ab 100755
--- a/php/tests/compatibility_test.sh
+++ b/php/tests/compatibility_test.sh
@@ -71,7 +71,7 @@
cd $(dirname $0)
OLD_VERSION=$1
-OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
+OLD_VERSION_PROTOC=https://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
# Extract the latest protobuf version number.
VERSION_NUMBER=`grep "PHP_PROTOBUF_VERSION" ../ext/google/protobuf/protobuf.h | sed "s|#define PHP_PROTOBUF_VERSION \"\(.*\)\"|\1|"`
diff --git a/php/tests/compile_extension.sh b/php/tests/compile_extension.sh
index bbd6696..2ffc51f 100755
--- a/php/tests/compile_extension.sh
+++ b/php/tests/compile_extension.sh
@@ -1,10 +1,14 @@
#!/bin/bash
-EXTENSION_PATH=$1
+VERSION=$2
-pushd $EXTENSION_PATH
+export PATH=/usr/local/php-$VERSION/bin:$PATH
+export C_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$C_INCLUDE_PATH
+export CPLUS_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$CPLUS_INCLUDE_PATH
+
+pushd ../ext/google/protobuf
make clean || true
set -e
# Add following in configure for debug: --enable-debug CFLAGS='-g -O0'
-phpize && ./configure CFLAGS='-g -O0' && make
+phpize && ./configure CFLAGS='-g -O0 -Wall' && make
popd
diff --git a/php/tests/descriptors_test.php b/php/tests/descriptors_test.php
index 93683b8..60a6292 100644
--- a/php/tests/descriptors_test.php
+++ b/php/tests/descriptors_test.php
@@ -11,6 +11,8 @@
use Descriptors\TestDescriptorsEnum;
use Descriptors\TestDescriptorsMessage;
use Descriptors\TestDescriptorsMessage\Sub;
+use Foo\TestMessage;
+use Bar\TestInclude;
class DescriptorsTest extends TestBase
{
@@ -89,6 +91,17 @@
$this->assertSame(1, $desc->getOneofDeclCount());
}
+ public function testDescriptorForIncludedMessage()
+ {
+ $pool = DescriptorPool::getGeneratedPool();
+ $class = get_class(new TestMessage());
+ $this->assertSame('Foo\TestMessage', $class);
+ $desc = $pool->getDescriptorByClassName($class);
+ $fielddesc = $desc->getField(17);
+ $subdesc = $fielddesc->getMessageType();
+ $this->assertSame('Bar\TestInclude', $subdesc->getClass());
+ }
+
#########################################################
# Test enum descriptor.
#########################################################
diff --git a/php/tests/encode_decode_test.php b/php/tests/encode_decode_test.php
index 53cd526..5442f50 100644
--- a/php/tests/encode_decode_test.php
+++ b/php/tests/encode_decode_test.php
@@ -884,6 +884,11 @@
$m->mergeFromJsonString("{\"unknown\":{\"a\":1, \"b\":1},
\"optionalInt32\":1}", true);
$this->assertSame(1, $m->getOptionalInt32());
+
+ // Test unknown enum value
+ $m = new TestMessage();
+ $m->mergeFromJsonString("{\"optionalEnum\":\"UNKNOWN\"}", true);
+ $this->assertSame(0, $m->getOptionalEnum());
}
public function testJsonEncode()
@@ -1164,6 +1169,18 @@
$m->serializeToJsonString());
}
+ public function testEncodeAnyWithDefaultWrapperMessagePacked()
+ {
+ $any = new Any();
+ $any->pack(new TestInt32Value([
+ 'field' => new Int32Value(['value' => 0]),
+ ]));
+ $this->assertSame(
+ "{\"@type\":\"type.googleapis.com/foo.TestInt32Value\"," .
+ "\"field\":0}",
+ $any->serializeToJsonString());
+ }
+
public function testDecodeTopLevelFieldMask()
{
$m = new TestMessage();
diff --git a/php/tests/multirequest.php b/php/tests/multirequest.php
new file mode 100644
index 0000000..bbe8d77
--- /dev/null
+++ b/php/tests/multirequest.php
@@ -0,0 +1,8 @@
+<?php
+
+if (extension_loaded("protobuf")) {
+ require_once('memory_leak_test.php');
+ echo "<p>protobuf loaded</p>";
+} else {
+ echo "<p>protobuf not loaded</p>";
+}
diff --git a/php/tests/multirequest.sh b/php/tests/multirequest.sh
new file mode 100755
index 0000000..97535ea
--- /dev/null
+++ b/php/tests/multirequest.sh
@@ -0,0 +1,34 @@
+#!/bin/bash
+set -e
+
+# Compile c extension
+VERSION=7.4
+PORT=12345
+
+export PATH=/usr/local/php-$VERSION/bin:$PATH
+export C_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$C_INCLUDE_PATH
+export CPLUS_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$CPLUS_INCLUDE_PATH
+/bin/bash ./compile_extension.sh $VERSION
+
+nohup php -d protobuf.keep_descriptor_pool_after_request=1 -dextension=../ext/google/protobuf/modules/protobuf.so -S localhost:$PORT multirequest.php 2>&1 &
+
+sleep 1
+
+wget http://localhost:$PORT/multirequest.result -O multirequest.result
+wget http://localhost:$PORT/multirequest.result -O multirequest.result
+
+pushd ../ext/google/protobuf
+phpize --clean
+popd
+
+PID=`ps | grep "php" | awk '{print $1}'`
+echo $PID
+
+if [[ -z "$PID" ]]
+then
+ echo "Failed"
+ exit 1
+else
+ kill $PID
+ echo "Succeeded"
+fi
diff --git a/php/tests/proto/test_import_descriptor_proto.proto b/php/tests/proto/test_import_descriptor_proto.proto
index 2a19940..b061601 100644
--- a/php/tests/proto/test_import_descriptor_proto.proto
+++ b/php/tests/proto/test_import_descriptor_proto.proto
@@ -1,5 +1,7 @@
syntax = "proto3";
+package foo;
+
import "google/protobuf/descriptor.proto";
message TestImportDescriptorProto {
diff --git a/php/tests/test.sh b/php/tests/test.sh
index 9ef565c..3c5e30d 100755
--- a/php/tests/test.sh
+++ b/php/tests/test.sh
@@ -7,7 +7,7 @@
export CPLUS_INCLUDE_PATH=/usr/local/php-$VERSION/include/php/main:/usr/local/php-$VERSION/include/php:$CPLUS_INCLUDE_PATH
# Compile c extension
-/bin/bash ./compile_extension.sh ../ext/google/protobuf
+/bin/bash ./compile_extension.sh $VERSION
tests=( array_test.php encode_decode_test.php generated_class_test.php map_field_test.php well_known_test.php descriptors_test.php wrapper_type_setters_test.php)
diff --git a/php/tests/well_known_test.php b/php/tests/well_known_test.php
index a16e070..a148fa4 100644
--- a/php/tests/well_known_test.php
+++ b/php/tests/well_known_test.php
@@ -4,6 +4,7 @@
require_once('test_util.php');
use Foo\TestMessage;
+use Foo\TestImportDescriptorProto;
use Google\Protobuf\Any;
use Google\Protobuf\Api;
use Google\Protobuf\BoolValue;
diff --git a/protobuf.bzl b/protobuf.bzl
index 829464d..8d67620 100644
--- a/protobuf.bzl
+++ b/protobuf.bzl
@@ -1,5 +1,6 @@
load("@bazel_skylib//lib:versions.bzl", "versions")
load("@rules_cc//cc:defs.bzl", "cc_library")
+load("@rules_proto//proto:defs.bzl", "ProtoInfo")
load("@rules_python//python:defs.bzl", "py_library", "py_test")
def _GetPath(ctx, path):
@@ -224,6 +225,29 @@
outs: a list of labels of the expected outputs from the protocol compiler.
"""
+def _adapt_proto_library_impl(ctx):
+ deps = [dep[ProtoInfo] for dep in ctx.attr.deps]
+
+ srcs = [src for dep in deps for src in dep.direct_sources]
+ return struct(
+ proto = struct(
+ srcs = srcs,
+ import_flags = ["-I{}".format(path) for dep in deps for path in dep.transitive_proto_path.to_list()],
+ deps = srcs,
+ ),
+ )
+
+adapt_proto_library = rule(
+ implementation = _adapt_proto_library_impl,
+ attrs = {
+ "deps": attr.label_list(
+ mandatory = True,
+ providers = [ProtoInfo],
+ ),
+ },
+ doc = "Adapts `proto_library` from `@rules_proto` to be used with `{cc,py}_proto_library` from this file.",
+)
+
def cc_proto_library(
name,
srcs = [],
@@ -231,7 +255,6 @@
cc_libs = [],
include = None,
protoc = "@com_google_protobuf//:protoc",
- internal_bootstrap_hack = False,
use_grpc_plugin = False,
default_runtime = "@com_google_protobuf//:protobuf",
**kargs):
@@ -249,41 +272,17 @@
cc_library.
include: a string indicating the include path of the .proto files.
protoc: the label of the protocol compiler to generate the sources.
- internal_bootstrap_hack: a flag indicate the cc_proto_library is used only
- for bootstraping. When it is set to True, no files will be generated.
- The rule will simply be a provider for .proto files, so that other
- cc_proto_library can depend on it.
use_grpc_plugin: a flag to indicate whether to call the grpc C++ plugin
when processing the proto files.
default_runtime: the implicitly default runtime which will be depended on by
the generated cc_library target.
**kargs: other keyword arguments that are passed to cc_library.
-
"""
includes = []
if include != None:
includes = [include]
- if internal_bootstrap_hack:
- # For pre-checked-in generated files, we add the internal_bootstrap_hack
- # which will skip the codegen action.
- proto_gen(
- name = name + "_genproto",
- srcs = srcs,
- deps = [s + "_genproto" for s in deps],
- includes = includes,
- protoc = protoc,
- visibility = ["//visibility:public"],
- )
-
- # An empty cc_library to make rule dependency consistent.
- cc_library(
- name = name,
- **kargs
- )
- return
-
grpc_cpp_plugin = None
if use_grpc_plugin:
grpc_cpp_plugin = "//external:grpc_cpp_plugin"
@@ -318,29 +317,58 @@
**kargs
)
-def internal_gen_well_known_protos_java(srcs):
- """Bazel rule to generate the gen_well_known_protos_java genrule
+def _internal_gen_well_known_protos_java_impl(ctx):
+ args = ctx.actions.args()
- Args:
- srcs: the well known protos
- """
- root = Label("%s//protobuf_java" % (native.repository_name())).workspace_root
- pkg = native.package_name() + "/" if native.package_name() else ""
- if root == "":
- include = " -I%ssrc " % pkg
- else:
- include = " -I%s/%ssrc " % (root, pkg)
- native.genrule(
- name = "gen_well_known_protos_java",
- srcs = srcs,
- outs = [
- "wellknown.srcjar",
- ],
- cmd = "$(location :protoc) --java_out=$(@D)/wellknown.jar" +
- " %s $(SRCS) " % include +
- " && mv $(@D)/wellknown.jar $(@D)/wellknown.srcjar",
- tools = [":protoc"],
+ deps = [d[ProtoInfo] for d in ctx.attr.deps]
+
+ srcjar = ctx.actions.declare_file("{}.srcjar".format(ctx.attr.name))
+ args.add("--java_out", srcjar)
+
+ descriptors = depset(
+ transitive = [dep.transitive_descriptor_sets for dep in deps],
)
+ args.add_joined(
+ "--descriptor_set_in",
+ descriptors,
+ join_with = ctx.configuration.host_path_separator,
+ )
+
+ for dep in deps:
+ if "." == dep.proto_source_root:
+ args.add_all([src.path for src in dep.direct_sources])
+ else:
+ source_root = dep.proto_source_root
+ offset = len(source_root) + 1 # + '/'.
+ args.add_all([src.path[offset:] for src in dep.direct_sources])
+
+ ctx.actions.run(
+ executable = ctx.executable._protoc,
+ inputs = descriptors,
+ outputs = [srcjar],
+ arguments = [args],
+ )
+
+ return [
+ DefaultInfo(
+ files = depset([srcjar]),
+ ),
+ ]
+
+internal_gen_well_known_protos_java = rule(
+ implementation = _internal_gen_well_known_protos_java_impl,
+ attrs = {
+ "deps": attr.label_list(
+ mandatory = True,
+ providers = [ProtoInfo],
+ ),
+ "_protoc": attr.label(
+ executable = True,
+ cfg = "host",
+ default = "@com_google_protobuf//:protoc",
+ ),
+ },
+)
def internal_copied_filegroup(name, srcs, strip_prefix, dest, **kwargs):
"""Macro to copy files to a different directory and then create a filegroup.
@@ -404,7 +432,7 @@
protoc: the label of the protocol compiler to generate the sources.
use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin
when processing the proto files.
- **kargs: other keyword arguments that are passed to cc_library.
+ **kargs: other keyword arguments that are passed to py_library.
"""
outs = _PyOuts(srcs, use_grpc_plugin)
diff --git a/protobuf_deps.bzl b/protobuf_deps.bzl
index 9209b1c..fb0c477 100644
--- a/protobuf_deps.bzl
+++ b/protobuf_deps.bzl
@@ -8,9 +8,11 @@
if not native.existing_rule("bazel_skylib"):
http_archive(
name = "bazel_skylib",
- sha256 = "bbccf674aa441c266df9894182d80de104cabd19be98be002f6d478aaa31574d",
- strip_prefix = "bazel-skylib-2169ae1c374aab4a09aa90e65efe1a3aad4e279b",
- urls = ["https://github.com/bazelbuild/bazel-skylib/archive/2169ae1c374aab4a09aa90e65efe1a3aad4e279b.tar.gz"],
+ sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44",
+ urls = [
+ "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz",
+ "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz",
+ ],
)
if not native.existing_rule("zlib"):
diff --git a/protoc-artifacts/README.md b/protoc-artifacts/README.md
index 70da44c..2c45fef 100644
--- a/protoc-artifacts/README.md
+++ b/protoc-artifacts/README.md
@@ -123,7 +123,7 @@
protoc.exe
+ ppcle_64
protoc.exe
- + s390x_64
+ + s390x
protoc.exe
+ osx
+ x86_64
@@ -151,31 +151,6 @@
in the name like ``comgoogle-123``. Verify that the staging repository has all
the binaries, close and release this repository.
-## Upload zip packages to github release page.
-After uploading protoc artifacts to Maven Central repository, run the
-build-zip.sh script to bulid zip packages for these protoc binaries
-and upload these zip packages to the download section of the github
-release. For example:
-
-```
-$ ./build-zip.sh protoc 3.6.0
-```
-
-The above command will create 7 zip files:
-
-```
-dist/protoc-3.6.0-win32.zip
-dist/protoc-3.6.0-osx-x86_32.zip
-dist/protoc-3.6.0-osx-x86_64.zip
-dist/protoc-3.6.0-linux-x86_32.zip
-dist/protoc-3.6.0-linux-x86_64.zip
-dist/protoc-3.6.0-linux-aarch_64.zip
-dist/protoc-3.6.0-linux-ppcle_64.zip
-dist/protoc-3.6.0-linux-s390x_64.zip
-```
-
-Before running the script, make sure the artifacts are accessible from:
-http://repo1.maven.org/maven2/com/google/protobuf/protoc/
## Tested build environments
We have successfully built artifacts on the following environments:
diff --git a/protoc-artifacts/build-protoc.sh b/protoc-artifacts/build-protoc.sh
index 6ad2ea1..7f65d37 100755
--- a/protoc-artifacts/build-protoc.sh
+++ b/protoc-artifacts/build-protoc.sh
@@ -93,7 +93,7 @@
assertEq $format "elf64-x86-64" $LINENO
elif [[ "$ARCH" == aarch_64 ]]; then
assertEq $format "elf64-little" $LINENO
- elif [[ "$ARCH" == s390x_64 ]]; then
+ elif [[ "$ARCH" == s390x ]]; then
if [[ $host_machine == s390x ]];then
assertEq $format "elf64-s390" $LINENO
else
@@ -149,7 +149,7 @@
white_list="linux-gate\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|ld-linux\.so\.2"
elif [[ "$ARCH" == x86_64 ]]; then
white_list="linux-vdso\.so\.1\|libpthread\.so\.0\|libm\.so\.6\|libc\.so\.6\|ld-linux-x86-64\.so\.2"
- elif [[ "$ARCH" == s390x_64 ]]; then
+ elif [[ "$ARCH" == s390x ]]; then
if [[ $host_machine != s390x ]];then
dump_cmd='objdump -p '"$1"' | grep NEEDED'
fi
@@ -226,7 +226,7 @@
elif [[ "$ARCH" == ppcle_64 ]]; then
CXXFLAGS="$CXXFLAGS -m64"
CONFIGURE_ARGS="$CONFIGURE_ARGS --host=powerpc64le-linux-gnu"
- elif [[ "$ARCH" == s390x_64 ]]; then
+ elif [[ "$ARCH" == s390x ]]; then
CXXFLAGS="$CXXFLAGS -m64"
CONFIGURE_ARGS="$CONFIGURE_ARGS --host=s390x-linux-gnu"
else
diff --git a/protoc-artifacts/build-zip.sh b/protoc-artifacts/build-zip.sh
index 392bc14..2a25d3c 100755
--- a/protoc-artifacts/build-zip.sh
+++ b/protoc-artifacts/build-zip.sh
@@ -13,16 +13,15 @@
This script will download pre-built protoc or protoc plugin binaries from maven
repository and create .zip packages suitable to be included in the github
release page. If the target is protoc, well-known type .proto files will also be
-included. Each invocation will create 9 zip packages:
+included. Each invocation will create 8 zip packages:
dist/<TARGET>-<VERSION_NUMBER>-win32.zip
dist/<TARGET>-<VERSION_NUMBER>-win64.zip
- dist/<TARGET>-<VERSION_NUMBER>-osx-x86_32.zip
dist/<TARGET>-<VERSION_NUMBER>-osx-x86_64.zip
dist/<TARGET>-<VERSION_NUMBER>-linux-x86_32.zip
dist/<TARGET>-<VERSION_NUMBER>-linux-x86_64.zip
dist/<TARGET>-<VERSION_NUMBER>-linux-aarch_64.zip
dist/<TARGET>-<VERSION_NUMBER>-linux-ppcle_64.zip
- dist/<TARGET>-<VERSION_NUMBER>-linux-s390x_64.zip
+ dist/<TARGET>-<VERSION_NUMBER>-linux-s390x.zip
EOF
exit 1
fi
@@ -34,13 +33,12 @@
declare -a FILE_NAMES=( \
win32.zip windows-x86_32.exe \
win64.zip windows-x86_64.exe \
- osx-x86_32.zip osx-x86_32.exe \
osx-x86_64.zip osx-x86_64.exe \
linux-x86_32.zip linux-x86_32.exe \
linux-x86_64.zip linux-x86_64.exe \
linux-aarch_64.zip linux-aarch_64.exe \
linux-ppcle_64.zip linux-ppcle_64.exe \
- linux-s390x_64.zip linux-s390x_64.exe \
+ linux-s390x.zip linux-s390x.exe \
)
# List of all well-known types to be included.
@@ -100,7 +98,7 @@
BINARY="$TARGET"
fi
BINARY_NAME=${FILE_NAMES[$(($i+1))]}
- BINARY_URL=http://repo1.maven.org/maven2/com/google/protobuf/$TARGET/${VERSION_NUMBER}/$TARGET-${VERSION_NUMBER}-${BINARY_NAME}
+ BINARY_URL=https://repo1.maven.org/maven2/com/google/protobuf/$TARGET/${VERSION_NUMBER}/$TARGET-${VERSION_NUMBER}-${BINARY_NAME}
if ! wget ${BINARY_URL} -O ${DIR}/bin/$BINARY &> /dev/null; then
echo "[ERROR] Failed to download ${BINARY_URL}" >&2
echo "[ERROR] Skipped $TARGET-${VERSION_NAME}-${ZIP_NAME}" >&2
diff --git a/protoc-artifacts/pom.xml b/protoc-artifacts/pom.xml
index ab52097..ae72dbb 100644
--- a/protoc-artifacts/pom.xml
+++ b/protoc-artifacts/pom.xml
@@ -8,7 +8,7 @@
</parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protoc</artifactId>
- <version>3.11.0-rc-1</version>
+ <version>3.12.0-rc-2</version>
<packaging>pom</packaging>
<name>Protobuf Compiler</name>
<description>
@@ -71,11 +71,6 @@
<type>exe</type>
</artifact>
<artifact>
- <file>${basedir}/target/osx/x86_32/protoc.exe</file>
- <classifier>osx-x86_32</classifier>
- <type>exe</type>
- </artifact>
- <artifact>
<file>${basedir}/target/linux/aarch_64/protoc.exe</file>
<classifier>linux-aarch_64</classifier>
<type>exe</type>
@@ -86,8 +81,8 @@
<type>exe</type>
</artifact>
<artifact>
- <file>${basedir}/target/linux/s390x_64/protoc.exe</file>
- <classifier>linux-s390x_64</classifier>
+ <file>${basedir}/target/linux/s390x/protoc.exe</file>
+ <classifier>linux-s390x</classifier>
<type>exe</type>
</artifact>
</artifacts>
diff --git a/python/.repo-metadata.json b/python/.repo-metadata.json
new file mode 100644
index 0000000..c8d71a8
--- /dev/null
+++ b/python/.repo-metadata.json
@@ -0,0 +1,11 @@
+{
+ "name": "protobuf",
+ "name_pretty": "Protocol Buffers",
+ "product_documentation": "https://developers.google.com/protocol-buffers ",
+ "client_documentation": "https://developers.google.com/protocol-buffers/docs/pythontutorial",
+ "issue_tracker": "https://github.com/protocolbuffers/protobuf/issues",
+ "release_level": "ga",
+ "language": "python",
+ "repo": "protocolbuffers/protobuf ",
+ "distribution_name": "protobuf"
+}
diff --git a/python/README.md b/python/README.md
index 8f7e031..a987c2d 100644
--- a/python/README.md
+++ b/python/README.md
@@ -22,10 +22,8 @@
Development Warning
===================
-The Python implementation of Protocol Buffers is not as mature as the C++
-and Java implementations. It may be more buggy, and it is known to be
-pretty slow at this time. If you would like to help fix these issues,
-join the Protocol Buffers discussion list and let us know!
+The pure python performance is slow. For better preformance please
+use python c++ implementation.
Installation
============
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
index a785f79..031433e 100644
--- a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/descriptor.proto
@@ -228,7 +228,7 @@
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
-// Object-C plugin) and your porject website (if available) -- there's no need
+// Object-C plugin) and your project website (if available) -- there's no need
// to explain how you intend to use them. Usually you only need one extension
// number. You can declare multiple options with only one extension number by
// putting them in a sub-message. See the Custom Options section of the docs
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
index e591d29..2f4e3fd 100644
--- a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_custom_options.proto
@@ -321,7 +321,7 @@
}
// Allow Aggregate to be used as an option at all possible locations
-// in the .proto grammer.
+// in the .proto grammar.
extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
diff --git a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
index c115b11..ec36cca 100644
--- a/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
+++ b/python/compatibility_tests/v2.5.0/protos/src/proto/google/protobuf/unittest_import.proto
@@ -43,7 +43,7 @@
option optimize_for = SPEED;
-// Excercise the java_package option.
+// Exercise the java_package option.
option java_package = "com.google.protobuf.test";
// Do not set a java_outer_classname here to verify that Proto2 works without
diff --git a/python/compatibility_tests/v2.5.0/test.sh b/python/compatibility_tests/v2.5.0/test.sh
index fb3e545..740c132 100755
--- a/python/compatibility_tests/v2.5.0/test.sh
+++ b/python/compatibility_tests/v2.5.0/test.sh
@@ -12,10 +12,10 @@
# The old version of protobuf that we are testing compatibility against. This
# is usually the same as TEST_VERSION (i.e., we use the tests extracted from
# that version to test compatibility of the newest runtime against it), but it
-# is also possible to use this same test set to test the compatibiilty of the
+# is also possible to use this same test set to test the compatibility of the
# latest version against other versions.
OLD_VERSION=$1
-OLD_VERSION_PROTOC=http://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
+OLD_VERSION_PROTOC=https://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe
# Extract the latest protobuf version number.
VERSION_NUMBER=`grep "^__version__ = '.*'" ../../google/protobuf/__init__.py | sed "s|__version__ = '\(.*\)'|\1|"`
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py
index 8343aba..feb7752 100755
--- a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/generator_test.py
@@ -148,7 +148,7 @@
proto = unittest_custom_options_pb2.TestMessageWithCustomOptions()
enum_options = proto.DESCRIPTOR.enum_types_by_name['AnEnum'].GetOptions()
self.assertTrue(enum_options is not None)
- # TODO(gps): We really should test for the presense of the enum_opt1
+ # TODO(gps): We really should test for the presence of the enum_opt1
# extension and for its value to be set to -789.
def testNestedTypes(self):
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py
index 2f0708d..9b7356f 100755
--- a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/service_reflection_test.py
@@ -118,7 +118,7 @@
rpc_controller = 'controller'
request = 'request'
- # GetDescriptor now static, still works as instance method for compatability
+ # GetDescriptor now static, still works as instance method for compatibility
self.assertEqual(unittest_pb2.TestService_Stub.GetDescriptor(),
stub.GetDescriptor())
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/test_util.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/test_util.py
old mode 100755
new mode 100644
diff --git a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py
index 1e6f063..0bee668 100755
--- a/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py
+++ b/python/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py
@@ -247,7 +247,7 @@
text = text.replace('e+0','e+').replace('e+0','e+') \
.replace('e-0','e-').replace('e-0','e-')
# Floating point fields are printed with .0 suffix even if they are
- # actualy integer numbers.
+ # actually integer numbers.
text = re.compile(r'\.0$', re.MULTILINE).sub('', text)
return text
diff --git a/python/docs/Makefile b/python/docs/Makefile
new file mode 100644
index 0000000..298ea9e
--- /dev/null
+++ b/python/docs/Makefile
@@ -0,0 +1,19 @@
+# Minimal makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+SOURCEDIR = .
+BUILDDIR = _build
+
+# Put it first so that "make" without argument is like "make help".
+help:
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+.PHONY: help Makefile
+
+# Catch-all target: route all unknown targets to Sphinx using the new
+# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
+%: Makefile
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
\ No newline at end of file
diff --git a/python/docs/conf.py b/python/docs/conf.py
new file mode 100644
index 0000000..913f012
--- /dev/null
+++ b/python/docs/conf.py
@@ -0,0 +1,254 @@
+# -*- coding: utf-8 -*-
+# Protocol Buffers - Google's data interchange format
+# Copyright 2019 Google LLC. All rights reserved.
+# https://developers.google.com/protocol-buffers/
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+# Configuration file for the Sphinx documentation builder.
+#
+# This file does only contain a selection of the most common options. For a
+# full list see the documentation:
+# http://www.sphinx-doc.org/en/master/config
+
+# -- Path setup --------------------------------------------------------------
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#
+import os
+# import sys
+# sys.path.insert(0, os.path.abspath('.'))
+import google.protobuf
+
+# -- Project information -----------------------------------------------------
+
+project = u"Protocol Buffers"
+copyright = u"2008, Google LLC"
+author = u"Google LLC"
+
+# The short X.Y version
+version = u""
+# The full version, including alpha/beta/rc tags
+release = google.protobuf.__version__
+
+
+# -- General configuration ---------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#
+# needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ "sphinx.ext.autosummary",
+ "sphinx.ext.ifconfig",
+ "sphinx.ext.intersphinx",
+ "sphinx.ext.napoleon",
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ["_templates"]
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+#
+# source_suffix = ['.rst', '.md']
+source_suffix = ".rst"
+
+# The master toctree document.
+master_doc = "index"
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = None
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This pattern also affects html_static_path and html_extra_path.
+exclude_patterns = [u"_build", "Thumbs.db", ".DS_Store"]
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = None
+
+
+# -- Options for HTML output -------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+#
+html_theme = "alabaster"
+
+# Remove JavaScript.
+html_js_files = []
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#
+# html_theme_options = {}
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ["_static"]
+
+html_show_sourcelink = True
+
+# Custom sidebar templates, must be a dictionary that maps document names
+# to template names.
+#
+# The default sidebars (for documents that don't match any pattern) are
+# defined by theme itself. Builtin themes are using these templates by
+# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
+# 'searchbox.html']``.
+
+# Remove searchbox.html to avoid embedded JavaScript.
+html_sidebars = {
+ "**": [
+ "globaltoc.html", "localtoc.html", "relations.html", "sourcelink.html",
+ ],
+}
+
+
+# -- Options for HTMLHelp output ---------------------------------------------
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = "ProtocolBuffersdoc"
+
+
+# -- Options for LaTeX output ------------------------------------------------
+
+latex_elements = {
+ # The paper size ('letterpaper' or 'a4paper').
+ #
+ # 'papersize': 'letterpaper',
+ # The font size ('10pt', '11pt' or '12pt').
+ #
+ # 'pointsize': '10pt',
+ # Additional stuff for the LaTeX preamble.
+ #
+ # 'preamble': '',
+ # Latex figure (float) alignment
+ #
+ # 'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+# author, documentclass [howto, manual, or own class]).
+latex_documents = [
+ (
+ master_doc,
+ "ProtocolBuffers.tex",
+ "Protocol Buffers Documentation",
+ "Google LLC",
+ "manual",
+ )
+]
+
+
+# -- Options for manual page output ------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ (
+ master_doc, # source start file
+ "protocolbuffers", # name
+ "Protocol Buffers Documentation", # description
+ [author], # authors
+ 1, # manual section
+ )
+]
+
+
+# -- Options for Texinfo output ----------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ (
+ master_doc,
+ "ProtocolBuffers",
+ u"Protocol Buffers Documentation",
+ author,
+ "ProtocolBuffers",
+ "One line description of project.",
+ "Miscellaneous",
+ )
+]
+
+
+# -- Options for Epub output -------------------------------------------------
+
+# Bibliographic Dublin Core info.
+epub_title = project
+
+# The unique identifier of the text. This can be a ISBN number
+# or the project homepage.
+#
+# epub_identifier = ''
+
+# A unique identification for the text.
+#
+# epub_uid = ''
+
+# A list of files that should not be packed into the epub file.
+epub_exclude_files = ["search.html"]
+
+
+# -- Extension configuration -------------------------------------------------
+
+# -- Options for autosummary extension ---------------------------------------
+autosummary_generate = True
+
+# -- Options for intersphinx extension ---------------------------------------
+
+# Example configuration for intersphinx: refer to the Python standard library.
+intersphinx_mapping = {"https://docs.python.org/": None}
+
+# -- Config values -----------------------------------------------------------
+# The setup() function is needed to add configuration values to the Sphinx
+# builder. We use this to show a banner when built on Read the Docs.
+# https://www.sphinx-doc.org/en/master/usage/extensions/ifconfig.html
+
+def setup(app):
+ app.add_config_value(
+ "build_env",
+ # Read the Docs sets a READTHEDOCS environment during builds.
+ # https://docs.readthedocs.io/en/stable/builds.html#build-environment
+ "readthedocs" if os.getenv("READTHEDOCS") else "",
+ "env"
+ )
diff --git a/python/docs/environment.yml b/python/docs/environment.yml
new file mode 100644
index 0000000..0f6390e
--- /dev/null
+++ b/python/docs/environment.yml
@@ -0,0 +1,10 @@
+name: protobuf
+channels:
+ - defaults
+dependencies:
+ - libprotobuf=3.11.4
+ - make=4.2.1
+ - pip=19.3.1
+ - python=3.7.6
+ - sphinx=2.4.0
+ - sphinx_rtd_theme=0.4.3
diff --git a/python/docs/generate_docs.py b/python/docs/generate_docs.py
new file mode 100755
index 0000000..e024aaa
--- /dev/null
+++ b/python/docs/generate_docs.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python
+# 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.
+
+"""Script to generate a list of all modules to use in autosummary.
+
+This script creates a ReStructured Text file for each public module in the
+protobuf Python package. The script also updates the table of contents in
+``docs/index.rst`` to point to these module references.
+
+To build the docs with Sphinx:
+
+1. Install the needed packages (``sphinx``, ``sphinxcontrib-napoleon`` for
+ Google-style docstring support). I've created a conda environment file to
+ make this easier:
+
+.. code:: bash
+
+ conda env create -f python/docs/environment.yml
+
+2. (Optional) Generate reference docs files and regenerate index:
+
+.. code:: bash
+
+ cd python/docs
+ python generate_docs.py
+
+3. Run Sphinx.
+
+.. code:: bash
+
+ make html
+"""
+
+import pathlib
+import re
+
+
+DOCS_DIR = pathlib.Path(__file__).parent.resolve()
+PYTHON_DIR = DOCS_DIR.parent
+SOURCE_DIR = PYTHON_DIR / "google" / "protobuf"
+SOURCE_POSIX = SOURCE_DIR.as_posix()
+
+# Modules which are always included:
+INCLUDED_MODULES = (
+ "google.protobuf.internal.containers",
+)
+
+# Packages to ignore, including all modules (unless in INCLUDED_MODULES):
+IGNORED_PACKAGES = (
+ "compiler",
+ "docs",
+ "internal",
+ "pyext",
+ "util",
+)
+
+# Ignored module stems in all packages (unless in INCLUDED_MODULES):
+IGNORED_MODULES = (
+ "any_test_pb2",
+ "api_pb2",
+ "unittest",
+ "source_context_pb2",
+ "test_messages_proto3_pb2",
+ "test_messages_proto2",
+)
+
+TOC_REGEX = re.compile(
+ r"\.\. START REFTOC.*\.\. END REFTOC\.\n",
+ flags=re.DOTALL,
+)
+TOC_TEMPLATE = """.. START REFTOC, generated by generate_docs.py.
+.. toctree::
+
+ {toctree}
+
+.. END REFTOC.
+"""
+
+AUTOMODULE_TEMPLATE = """.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+{module}
+{underline}
+
+.. automodule:: {module}
+ :members:
+ :inherited-members:
+ :undoc-members:
+"""
+
+
+def find_modules():
+ modules = []
+ for module_path in SOURCE_DIR.glob("**/*.py"):
+ # Determine the (dotted) relative package and module names.
+ package_path = module_path.parent.relative_to(PYTHON_DIR)
+ if package_path == SOURCE_DIR:
+ package_name = ""
+ module_name = module_path.stem
+ else:
+ package_name = package_path.as_posix().replace("/", ".")
+ module_name = package_name + "." + module_path.stem
+
+ # Filter: first, accept anything in the whitelist; then, reject anything
+ # at package level, then module name level.
+ if any(include == module_name for include in INCLUDED_MODULES):
+ pass
+ elif any(ignored in package_name for ignored in IGNORED_PACKAGES):
+ continue
+ elif any(ignored in module_path.stem for ignored in IGNORED_MODULES):
+ continue
+
+ if module_path.name == "__init__.py":
+ modules.append(package_name)
+ else:
+ modules.append(module_name)
+
+ return modules
+
+
+def write_automodule(module):
+ contents = AUTOMODULE_TEMPLATE.format(module=module, underline="=" * len(module),)
+ automodule_path = DOCS_DIR.joinpath(*module.split(".")).with_suffix(".rst")
+ try:
+ automodule_path.parent.mkdir(parents=True)
+ except FileExistsError:
+ pass
+ with open(automodule_path, "w") as automodule_file:
+ automodule_file.write(contents)
+
+
+def replace_toc(modules):
+ toctree = [module.replace(".", "/") for module in modules]
+ with open(DOCS_DIR / "index.rst", "r") as index_file:
+ index_contents = index_file.read()
+ toc = TOC_TEMPLATE.format(
+ toctree="\n ".join(toctree)
+ )
+ index_contents = re.sub(TOC_REGEX, toc, index_contents)
+ with open(DOCS_DIR / "index.rst", "w") as index_file:
+ index_file.write(index_contents)
+
+
+def main():
+ modules = list(sorted(find_modules()))
+ for module in modules:
+ print("Generating reference for {}".format(module))
+ write_automodule(module)
+ print("Generating index.rst")
+ replace_toc(modules)
+
+if __name__ == "__main__":
+ main()
diff --git a/python/docs/google/protobuf.rst b/python/docs/google/protobuf.rst
new file mode 100644
index 0000000..b26102e
--- /dev/null
+++ b/python/docs/google/protobuf.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf
+===============
+
+.. automodule:: google.protobuf
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/any_pb2.rst b/python/docs/google/protobuf/any_pb2.rst
new file mode 100644
index 0000000..b6f47ef
--- /dev/null
+++ b/python/docs/google/protobuf/any_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.any_pb2
+=======================
+
+.. automodule:: google.protobuf.any_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/descriptor.rst b/python/docs/google/protobuf/descriptor.rst
new file mode 100644
index 0000000..29b0774
--- /dev/null
+++ b/python/docs/google/protobuf/descriptor.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.descriptor
+==========================
+
+.. automodule:: google.protobuf.descriptor
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/descriptor_database.rst b/python/docs/google/protobuf/descriptor_database.rst
new file mode 100644
index 0000000..1b8b390
--- /dev/null
+++ b/python/docs/google/protobuf/descriptor_database.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.descriptor_database
+===================================
+
+.. automodule:: google.protobuf.descriptor_database
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/descriptor_pb2.rst b/python/docs/google/protobuf/descriptor_pb2.rst
new file mode 100644
index 0000000..94eec35
--- /dev/null
+++ b/python/docs/google/protobuf/descriptor_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.descriptor_pb2
+==============================
+
+.. automodule:: google.protobuf.descriptor_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/descriptor_pool.rst b/python/docs/google/protobuf/descriptor_pool.rst
new file mode 100644
index 0000000..c2ee33e
--- /dev/null
+++ b/python/docs/google/protobuf/descriptor_pool.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.descriptor_pool
+===============================
+
+.. automodule:: google.protobuf.descriptor_pool
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/duration_pb2.rst b/python/docs/google/protobuf/duration_pb2.rst
new file mode 100644
index 0000000..4233e3c
--- /dev/null
+++ b/python/docs/google/protobuf/duration_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.duration_pb2
+============================
+
+.. automodule:: google.protobuf.duration_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/empty_pb2.rst b/python/docs/google/protobuf/empty_pb2.rst
new file mode 100644
index 0000000..c386a4c
--- /dev/null
+++ b/python/docs/google/protobuf/empty_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.empty_pb2
+=========================
+
+.. automodule:: google.protobuf.empty_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/field_mask_pb2.rst b/python/docs/google/protobuf/field_mask_pb2.rst
new file mode 100644
index 0000000..d9d8070
--- /dev/null
+++ b/python/docs/google/protobuf/field_mask_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.field_mask_pb2
+==============================
+
+.. automodule:: google.protobuf.field_mask_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/internal/containers.rst b/python/docs/google/protobuf/internal/containers.rst
new file mode 100644
index 0000000..c3b8e59
--- /dev/null
+++ b/python/docs/google/protobuf/internal/containers.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.internal.containers
+===================================
+
+.. automodule:: google.protobuf.internal.containers
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/json_format.rst b/python/docs/google/protobuf/json_format.rst
new file mode 100644
index 0000000..eb3b0c5
--- /dev/null
+++ b/python/docs/google/protobuf/json_format.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.json_format
+===========================
+
+.. automodule:: google.protobuf.json_format
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/message.rst b/python/docs/google/protobuf/message.rst
new file mode 100644
index 0000000..a204248
--- /dev/null
+++ b/python/docs/google/protobuf/message.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.message
+=======================
+
+.. automodule:: google.protobuf.message
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/message_factory.rst b/python/docs/google/protobuf/message_factory.rst
new file mode 100644
index 0000000..93183cc
--- /dev/null
+++ b/python/docs/google/protobuf/message_factory.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.message_factory
+===============================
+
+.. automodule:: google.protobuf.message_factory
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/proto_builder.rst b/python/docs/google/protobuf/proto_builder.rst
new file mode 100644
index 0000000..36243a2
--- /dev/null
+++ b/python/docs/google/protobuf/proto_builder.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.proto_builder
+=============================
+
+.. automodule:: google.protobuf.proto_builder
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/reflection.rst b/python/docs/google/protobuf/reflection.rst
new file mode 100644
index 0000000..d177fc0
--- /dev/null
+++ b/python/docs/google/protobuf/reflection.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.reflection
+==========================
+
+.. automodule:: google.protobuf.reflection
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/service.rst b/python/docs/google/protobuf/service.rst
new file mode 100644
index 0000000..6d71f81
--- /dev/null
+++ b/python/docs/google/protobuf/service.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.service
+=======================
+
+.. automodule:: google.protobuf.service
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/service_reflection.rst b/python/docs/google/protobuf/service_reflection.rst
new file mode 100644
index 0000000..30f30dd
--- /dev/null
+++ b/python/docs/google/protobuf/service_reflection.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.service_reflection
+==================================
+
+.. automodule:: google.protobuf.service_reflection
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/struct_pb2.rst b/python/docs/google/protobuf/struct_pb2.rst
new file mode 100644
index 0000000..9179eed
--- /dev/null
+++ b/python/docs/google/protobuf/struct_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.struct_pb2
+==========================
+
+.. automodule:: google.protobuf.struct_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/symbol_database.rst b/python/docs/google/protobuf/symbol_database.rst
new file mode 100644
index 0000000..6ea7352
--- /dev/null
+++ b/python/docs/google/protobuf/symbol_database.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.symbol_database
+===============================
+
+.. automodule:: google.protobuf.symbol_database
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/text_encoding.rst b/python/docs/google/protobuf/text_encoding.rst
new file mode 100644
index 0000000..a2eb959
--- /dev/null
+++ b/python/docs/google/protobuf/text_encoding.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.text_encoding
+=============================
+
+.. automodule:: google.protobuf.text_encoding
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/text_format.rst b/python/docs/google/protobuf/text_format.rst
new file mode 100644
index 0000000..686b8fc
--- /dev/null
+++ b/python/docs/google/protobuf/text_format.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.text_format
+===========================
+
+.. automodule:: google.protobuf.text_format
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/timestamp_pb2.rst b/python/docs/google/protobuf/timestamp_pb2.rst
new file mode 100644
index 0000000..540df83
--- /dev/null
+++ b/python/docs/google/protobuf/timestamp_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.timestamp_pb2
+=============================
+
+.. automodule:: google.protobuf.timestamp_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/type_pb2.rst b/python/docs/google/protobuf/type_pb2.rst
new file mode 100644
index 0000000..e9b19d7
--- /dev/null
+++ b/python/docs/google/protobuf/type_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.type_pb2
+========================
+
+.. automodule:: google.protobuf.type_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/google/protobuf/wrappers_pb2.rst b/python/docs/google/protobuf/wrappers_pb2.rst
new file mode 100644
index 0000000..8f29aa7
--- /dev/null
+++ b/python/docs/google/protobuf/wrappers_pb2.rst
@@ -0,0 +1,21 @@
+.. DO NOT EDIT, generated by generate_docs.py.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+google.protobuf.wrappers_pb2
+============================
+
+.. automodule:: google.protobuf.wrappers_pb2
+ :members:
+ :inherited-members:
+ :undoc-members:
diff --git a/python/docs/index.rst b/python/docs/index.rst
new file mode 100644
index 0000000..5535b39
--- /dev/null
+++ b/python/docs/index.rst
@@ -0,0 +1,63 @@
+.. Protocol Buffers documentation master file, created by
+ sphinx-quickstart on Thu Aug 15 13:56:43 2019.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+.. ifconfig:: build_env == 'readthedocs'
+
+ .. warning::
+
+ You are reading the documentation for the `latest committed changes
+ <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of
+ the `Protocol Buffers package for Python
+ <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_.
+ Some features may not yet be released. Read the documentation for the
+ latest released package at `googleapis.dev
+ <https://googleapis.dev/python/protobuf/latest/>`_.
+
+Protocol Buffers Python API Reference
+=====================================
+
+The complete documentation for Protocol Buffers is available via the web at:
+
+ https://developers.google.com/protocol-buffers/
+
+
+Modules and Packages
+--------------------
+
+.. START REFTOC, generated by generate_docs.py.
+.. toctree::
+
+ google/protobuf
+ google/protobuf/any_pb2
+ google/protobuf/descriptor
+ google/protobuf/descriptor_database
+ google/protobuf/descriptor_pb2
+ google/protobuf/descriptor_pool
+ google/protobuf/duration_pb2
+ google/protobuf/empty_pb2
+ google/protobuf/field_mask_pb2
+ google/protobuf/internal/containers
+ google/protobuf/json_format
+ google/protobuf/message
+ google/protobuf/message_factory
+ google/protobuf/proto_builder
+ google/protobuf/reflection
+ google/protobuf/service
+ google/protobuf/service_reflection
+ google/protobuf/struct_pb2
+ google/protobuf/symbol_database
+ google/protobuf/text_encoding
+ google/protobuf/text_format
+ google/protobuf/timestamp_pb2
+ google/protobuf/type_pb2
+ google/protobuf/wrappers_pb2
+
+.. END REFTOC.
+
+Indices and tables
+------------------
+
+* :ref:`genindex`
+* :ref:`modindex`
diff --git a/python/docs/make.bat b/python/docs/make.bat
new file mode 100644
index 0000000..27f573b
--- /dev/null
+++ b/python/docs/make.bat
@@ -0,0 +1,35 @@
+@ECHO OFF
+
+pushd %~dp0
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set SOURCEDIR=.
+set BUILDDIR=_build
+
+if "%1" == "" goto help
+
+%SPHINXBUILD% >NUL 2>NUL
+if errorlevel 9009 (
+ echo.
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+ echo.installed, then set the SPHINXBUILD environment variable to point
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
+ echo.may add the Sphinx directory to PATH.
+ echo.
+ echo.If you don't have Sphinx installed, grab it from
+ echo.http://sphinx-doc.org/
+ exit /b 1
+)
+
+%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
+goto end
+
+:help
+%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
+
+:end
+popd
diff --git a/python/docs/requirements.txt b/python/docs/requirements.txt
new file mode 100644
index 0000000..2b3e989
--- /dev/null
+++ b/python/docs/requirements.txt
@@ -0,0 +1,3 @@
+sphinx==2.3.1
+sphinx_rtd_theme==0.4.3
+sphinxcontrib-napoleon==0.7
diff --git a/python/google/__init__.py b/python/google/__init__.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/__init__.py b/python/google/protobuf/__init__.py
old mode 100755
new mode 100644
index f3e0a71..cee24d7
--- 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.11.0rc1'
+__version__ = '3.12.0rc2'
if __name__ != '__main__':
try:
diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py
old mode 100755
new mode 100644
index 78d889a..5ef81a2
--- a/python/google/protobuf/descriptor.py
+++ b/python/google/protobuf/descriptor.py
@@ -35,6 +35,7 @@
__author__ = 'robinson@google.com (Will Robinson)'
import threading
+import warnings
import six
from google.protobuf.internal import api_implementation
@@ -91,6 +92,25 @@
_lock = threading.Lock()
+def _Deprecated(name):
+ if _Deprecated.count > 0:
+ _Deprecated.count -= 1
+ warnings.warn(
+ 'Call to deprecated create function %s(). Note: Create unlinked '
+ 'descriptors is going to go away. Please use get/find descriptors from '
+ 'generated code or query the descriptor_pool.'
+ % name,
+ category=DeprecationWarning, stacklevel=3)
+
+
+# Deprecated warnings will print 100 times at most which should be enough for
+# users to notice and do not cause timeout.
+_Deprecated.count = 100
+
+
+_internal_create_key = object()
+
+
class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
"""Descriptors base class.
@@ -173,20 +193,19 @@
Args:
options: Protocol message options or None
to use default message options.
- options_class_name: (str) The class name of the above options.
-
- name: (str) Name of this protocol message type.
- full_name: (str) Fully-qualified name of this protocol message type,
+ options_class_name (str): The class name of the above options.
+ name (str): Name of this protocol message type.
+ full_name (str): Fully-qualified name of this protocol message type,
which will include protocol "package" name and the name of any
enclosing types.
- file: (FileDescriptor) Reference to file info.
+ file (FileDescriptor): Reference to file info.
containing_type: if provided, this is a nested descriptor, with this
descriptor as parent, otherwise None.
serialized_start: The start index (inclusive) in block in the
file.serialized_pb that describes this descriptor.
serialized_end: The end index (exclusive) in block in the
file.serialized_pb that describes this descriptor.
- serialized_options: Protocol message serilized options or None.
+ serialized_options: Protocol message serialized options or None.
"""
super(_NestedDescriptorBase, self).__init__(
options, serialized_options, options_class_name)
@@ -223,56 +242,45 @@
"""Descriptor for a protocol message type.
- A Descriptor instance has the following attributes:
+ Attributes:
+ name (str): Name of this protocol message type.
+ full_name (str): Fully-qualified name of this protocol message type,
+ which will include protocol "package" name and the name of any
+ enclosing types.
+ containing_type (Descriptor): Reference to the descriptor of the type
+ containing us, or None if this is top-level.
+ fields (list[FieldDescriptor]): Field descriptors for all fields in
+ this type.
+ fields_by_number (dict(int, FieldDescriptor)): Same
+ :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed
+ by "number" attribute in each FieldDescriptor.
+ fields_by_name (dict(str, FieldDescriptor)): Same
+ :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by
+ "name" attribute in each :class:`FieldDescriptor`.
+ nested_types (list[Descriptor]): Descriptor references
+ for all protocol message types nested within this one.
+ nested_types_by_name (dict(str, Descriptor)): Same Descriptor
+ objects as in :attr:`nested_types`, but indexed by "name" attribute
+ in each Descriptor.
+ enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references
+ for all enums contained within this type.
+ enum_types_by_name (dict(str, EnumDescriptor)): Same
+ :class:`EnumDescriptor` objects as in :attr:`enum_types`, but
+ indexed by "name" attribute in each EnumDescriptor.
+ enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping
+ from enum value name to :class:`EnumValueDescriptor` for that value.
+ extensions (list[FieldDescriptor]): All extensions defined directly
+ within this message type (NOT within a nested type).
+ extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor
+ objects as :attr:`extensions`, but indexed by "name" attribute of each
+ FieldDescriptor.
+ is_extendable (bool): Does this type define any extension ranges?
+ oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields
+ in this message.
+ oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in
+ :attr:`oneofs`, but indexed by "name" attribute.
+ file (FileDescriptor): Reference to file descriptor.
- name: (str) Name of this protocol message type.
- full_name: (str) Fully-qualified name of this protocol message type,
- which will include protocol "package" name and the name of any
- enclosing types.
-
- containing_type: (Descriptor) Reference to the descriptor of the
- type containing us, or None if this is top-level.
-
- fields: (list of FieldDescriptors) Field descriptors for all
- fields in this type.
- fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor
- objects as in |fields|, but indexed by "number" attribute in each
- FieldDescriptor.
- fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor
- objects as in |fields|, but indexed by "name" attribute in each
- FieldDescriptor.
- fields_by_camelcase_name: (dict str -> FieldDescriptor) Same
- FieldDescriptor objects as in |fields|, but indexed by
- "camelcase_name" attribute in each FieldDescriptor.
-
- nested_types: (list of Descriptors) Descriptor references
- for all protocol message types nested within this one.
- nested_types_by_name: (dict str -> Descriptor) Same Descriptor
- objects as in |nested_types|, but indexed by "name" attribute
- in each Descriptor.
-
- enum_types: (list of EnumDescriptors) EnumDescriptor references
- for all enums contained within this type.
- enum_types_by_name: (dict str ->EnumDescriptor) Same EnumDescriptor
- objects as in |enum_types|, but indexed by "name" attribute
- in each EnumDescriptor.
- enum_values_by_name: (dict str -> EnumValueDescriptor) Dict mapping
- from enum value name to EnumValueDescriptor for that value.
-
- extensions: (list of FieldDescriptor) All extensions defined directly
- within this message type (NOT within a nested type).
- extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor
- objects as |extensions|, but indexed by "name" attribute of each
- FieldDescriptor.
-
- is_extendable: Does this type define any extension ranges?
-
- oneofs: (list of OneofDescriptor) The list of descriptors for oneof fields
- in this message.
- oneofs_by_name: (dict str -> OneofDescriptor) Same objects as in |oneofs|,
- but indexed by "name" attribute.
-
- file: (FileDescriptor) Reference to file descriptor.
"""
if _USE_C_DESCRIPTORS:
@@ -283,7 +291,7 @@
serialized_options=None,
is_extendable=True, extension_ranges=None, oneofs=None,
file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
- syntax=None):
+ syntax=None, create_key=None):
_message.Message._CheckCalledFromGeneratedFile()
return _message.default_pool.FindMessageTypeByName(full_name)
@@ -295,13 +303,16 @@
serialized_options=None,
is_extendable=True, extension_ranges=None, oneofs=None,
file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
- syntax=None):
+ syntax=None, create_key=None):
"""Arguments to __init__() are as described in the description
of Descriptor fields above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute.
"""
+ if create_key is not _internal_create_key:
+ _Deprecated('Descriptor')
+
super(Descriptor, self).__init__(
options, 'MessageOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
@@ -345,6 +356,9 @@
@property
def fields_by_camelcase_name(self):
+ """Same FieldDescriptor objects as in :attr:`fields`, but indexed by
+ :attr:`FieldDescriptor.camelcase_name`.
+ """
if self._fields_by_camelcase_name is None:
self._fields_by_camelcase_name = dict(
(f.camelcase_name, f) for f in self.fields)
@@ -393,53 +407,51 @@
"""Descriptor for a single field in a .proto file.
- A FieldDescriptor instance has the following attributes:
-
- name: (str) Name of this field, exactly as it appears in .proto.
- full_name: (str) Name of this field, including containing scope. This is
+ Attributes:
+ name (str): Name of this field, exactly as it appears in .proto.
+ full_name (str): Name of this field, including containing scope. This is
particularly relevant for extensions.
- camelcase_name: (str) Camelcase name of this field.
- index: (int) Dense, 0-indexed index giving the order that this
+ index (int): Dense, 0-indexed index giving the order that this
field textually appears within its message in the .proto file.
- number: (int) Tag number declared for this field in the .proto file.
+ number (int): Tag number declared for this field in the .proto file.
- type: (One of the TYPE_* constants below) Declared type.
- cpp_type: (One of the CPPTYPE_* constants below) C++ type used to
+ type (int): (One of the TYPE_* constants below) Declared type.
+ cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to
represent this field.
- label: (One of the LABEL_* constants below) Tells whether this
+ label (int): (One of the LABEL_* constants below) Tells whether this
field is optional, required, or repeated.
- has_default_value: (bool) True if this field has a default value defined,
+ has_default_value (bool): True if this field has a default value defined,
otherwise false.
- default_value: (Varies) Default value of this field. Only
+ default_value (Varies): Default value of this field. Only
meaningful for non-repeated scalar fields. Repeated fields
should always set this to [], and non-repeated composite
fields should always set this to None.
- containing_type: (Descriptor) Descriptor of the protocol message
+ containing_type (Descriptor): Descriptor of the protocol message
type that contains this field. Set by the Descriptor constructor
if we're passed into one.
Somewhat confusingly, for extension fields, this is the
descriptor of the EXTENDED message, not the descriptor
of the message containing this field. (See is_extension and
extension_scope below).
- message_type: (Descriptor) If a composite field, a descriptor
+ message_type (Descriptor): If a composite field, a descriptor
of the message type contained in this field. Otherwise, this is None.
- enum_type: (EnumDescriptor) If this field contains an enum, a
+ enum_type (EnumDescriptor): If this field contains an enum, a
descriptor of that enum. Otherwise, this is None.
is_extension: True iff this describes an extension field.
- extension_scope: (Descriptor) Only meaningful if is_extension is True.
+ extension_scope (Descriptor): Only meaningful if is_extension is True.
Gives the message that immediately contains this extension field.
Will be None iff we're a top-level (file-level) extension field.
- options: (descriptor_pb2.FieldOptions) Protocol message field options or
+ options (descriptor_pb2.FieldOptions): Protocol message field options or
None to use default field options.
- containing_oneof: (OneofDescriptor) If the field is a member of a oneof
+ containing_oneof (OneofDescriptor): If the field is a member of a oneof
union, contains its descriptor. Otherwise, None.
- file: (FileDescriptor) Reference to file descriptor.
+ file (FileDescriptor): Reference to file descriptor.
"""
# Must be consistent with C++ FieldDescriptor::Type enum in
@@ -526,7 +538,7 @@
is_extension, extension_scope, options=None,
serialized_options=None,
has_default_value=True, containing_oneof=None, json_name=None,
- file=None): # pylint: disable=redefined-builtin
+ file=None, create_key=None): # pylint: disable=redefined-builtin
_message.Message._CheckCalledFromGeneratedFile()
if is_extension:
return _message.default_pool.FindExtensionByName(full_name)
@@ -538,7 +550,7 @@
is_extension, extension_scope, options=None,
serialized_options=None,
has_default_value=True, containing_oneof=None, json_name=None,
- file=None): # pylint: disable=redefined-builtin
+ file=None, create_key=None): # pylint: disable=redefined-builtin
"""The arguments are as described in the description of FieldDescriptor
attributes above.
@@ -546,6 +558,9 @@
(to deal with circular references between message types, for example).
Likewise for extension_scope.
"""
+ if create_key is not _internal_create_key:
+ _Deprecated('FieldDescriptor')
+
super(FieldDescriptor, self).__init__(
options, serialized_options, 'FieldOptions')
self.name = name
@@ -579,6 +594,11 @@
@property
def camelcase_name(self):
+ """Camelcase name of this field.
+
+ Returns:
+ str: the name in CamelCase.
+ """
if self._camelcase_name is None:
self._camelcase_name = _ToCamelCase(self.name)
return self._camelcase_name
@@ -594,7 +614,7 @@
Args:
proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
Returns:
- descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
+ int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
Raises:
TypeTransformationError: when the Python proto type isn't known.
"""
@@ -608,24 +628,23 @@
"""Descriptor for an enum defined in a .proto file.
- An EnumDescriptor instance has the following attributes:
-
- name: (str) Name of the enum type.
- full_name: (str) Full name of the type, including package name
+ Attributes:
+ name (str): Name of the enum type.
+ full_name (str): Full name of the type, including package name
and any enclosing type(s).
- values: (list of EnumValueDescriptors) List of the values
+ values (list[EnumValueDescriptors]): List of the values
in this enum.
- values_by_name: (dict str -> EnumValueDescriptor) Same as |values|,
+ values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`,
but indexed by the "name" field of each EnumValueDescriptor.
- values_by_number: (dict int -> EnumValueDescriptor) Same as |values|,
+ values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`,
but indexed by the "number" field of each EnumValueDescriptor.
- containing_type: (Descriptor) Descriptor of the immediate containing
+ containing_type (Descriptor): Descriptor of the immediate containing
type of this enum, or None if this is an enum defined at the
top level in a .proto file. Set by Descriptor's constructor
if we're passed into one.
- file: (FileDescriptor) Reference to file descriptor.
- options: (descriptor_pb2.EnumOptions) Enum options message or
+ file (FileDescriptor): Reference to file descriptor.
+ options (descriptor_pb2.EnumOptions): Enum options message or
None to use default enum options.
"""
@@ -635,19 +654,22 @@
def __new__(cls, name, full_name, filename, values,
containing_type=None, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
- serialized_start=None, serialized_end=None):
+ serialized_start=None, serialized_end=None, create_key=None):
_message.Message._CheckCalledFromGeneratedFile()
return _message.default_pool.FindEnumTypeByName(full_name)
def __init__(self, name, full_name, filename, values,
containing_type=None, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
- serialized_start=None, serialized_end=None):
+ serialized_start=None, serialized_end=None, create_key=None):
"""Arguments are as described in the attribute description above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute.
"""
+ if create_key is not _internal_create_key:
+ _Deprecated('EnumDescriptor')
+
super(EnumDescriptor, self).__init__(
options, 'EnumOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
@@ -664,7 +686,7 @@
"""Copies this to a descriptor_pb2.EnumDescriptorProto.
Args:
- proto: An empty descriptor_pb2.EnumDescriptorProto.
+ proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto.
"""
# This function is overridden to give a better doc comment.
super(EnumDescriptor, self).CopyToProto(proto)
@@ -674,14 +696,15 @@
"""Descriptor for a single value within an enum.
- name: (str) Name of this value.
- index: (int) Dense, 0-indexed index giving the order that this
+ Attributes:
+ name (str): Name of this value.
+ index (int): Dense, 0-indexed index giving the order that this
value appears textually within its enum in the .proto file.
- number: (int) Actual number assigned to this enum value.
- type: (EnumDescriptor) EnumDescriptor to which this value
- belongs. Set by EnumDescriptor's constructor if we're
+ number (int): Actual number assigned to this enum value.
+ type (EnumDescriptor): :class:`EnumDescriptor` to which this value
+ belongs. Set by :class:`EnumDescriptor`'s constructor if we're
passed into one.
- options: (descriptor_pb2.EnumValueOptions) Enum value options message or
+ options (descriptor_pb2.EnumValueOptions): Enum value options message or
None to use default enum value options options.
"""
@@ -690,7 +713,7 @@
def __new__(cls, name, index, number,
type=None, # pylint: disable=redefined-builtin
- options=None, serialized_options=None):
+ options=None, serialized_options=None, create_key=None):
_message.Message._CheckCalledFromGeneratedFile()
# There is no way we can build a complete EnumValueDescriptor with the
# given parameters (the name of the Enum is not known, for example).
@@ -700,8 +723,11 @@
def __init__(self, name, index, number,
type=None, # pylint: disable=redefined-builtin
- options=None, serialized_options=None):
+ options=None, serialized_options=None, create_key=None):
"""Arguments are as described in the attribute description above."""
+ if create_key is not _internal_create_key:
+ _Deprecated('EnumValueDescriptor')
+
super(EnumValueDescriptor, self).__init__(
options, serialized_options, 'EnumValueOptions')
self.name = name
@@ -713,14 +739,15 @@
class OneofDescriptor(DescriptorBase):
"""Descriptor for a oneof field.
- name: (str) Name of the oneof field.
- full_name: (str) Full name of the oneof field, including package name.
- index: (int) 0-based index giving the order of the oneof field inside
+ Attributes:
+ name (str): Name of the oneof field.
+ full_name (str): Full name of the oneof field, including package name.
+ index (int): 0-based index giving the order of the oneof field inside
its containing type.
- containing_type: (Descriptor) Descriptor of the protocol message
- type that contains this field. Set by the Descriptor constructor
+ containing_type (Descriptor): :class:`Descriptor` of the protocol message
+ type that contains this field. Set by the :class:`Descriptor` constructor
if we're passed into one.
- fields: (list of FieldDescriptor) The list of field descriptors this
+ fields (list[FieldDescriptor]): The list of field descriptors this
oneof can contain.
"""
@@ -729,14 +756,17 @@
def __new__(
cls, name, full_name, index, containing_type, fields, options=None,
- serialized_options=None):
+ serialized_options=None, create_key=None):
_message.Message._CheckCalledFromGeneratedFile()
return _message.default_pool.FindOneofByName(full_name)
def __init__(
self, name, full_name, index, containing_type, fields, options=None,
- serialized_options=None):
+ serialized_options=None, create_key=None):
"""Arguments are as described in the attribute description above."""
+ if create_key is not _internal_create_key:
+ _Deprecated('OneofDescriptor')
+
super(OneofDescriptor, self).__init__(
options, serialized_options, 'OneofOptions')
self.name = name
@@ -750,18 +780,19 @@
"""Descriptor for a service.
- name: (str) Name of the service.
- full_name: (str) Full name of the service, including package name.
- index: (int) 0-indexed index giving the order that this services
- definition appears withing the .proto file.
- methods: (list of MethodDescriptor) List of methods provided by this
+ Attributes:
+ name (str): Name of the service.
+ full_name (str): Full name of the service, including package name.
+ index (int): 0-indexed index giving the order that this services
+ definition appears within the .proto file.
+ methods (list[MethodDescriptor]): List of methods provided by this
service.
- methods_by_name: (dict str -> MethodDescriptor) Same MethodDescriptor
- objects as in |methods_by_name|, but indexed by "name" attribute in each
- MethodDescriptor.
- options: (descriptor_pb2.ServiceOptions) Service options message or
+ methods_by_name (dict(str, MethodDescriptor)): Same
+ :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but
+ indexed by "name" attribute in each :class:`MethodDescriptor`.
+ options (descriptor_pb2.ServiceOptions): Service options message or
None to use default service options.
- file: (FileDescriptor) Reference to file info.
+ file (FileDescriptor): Reference to file info.
"""
if _USE_C_DESCRIPTORS:
@@ -769,13 +800,16 @@
def __new__(cls, name, full_name, index, methods, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
- serialized_start=None, serialized_end=None):
+ serialized_start=None, serialized_end=None, create_key=None):
_message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
return _message.default_pool.FindServiceByName(full_name)
def __init__(self, name, full_name, index, methods, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
- serialized_start=None, serialized_end=None):
+ serialized_start=None, serialized_end=None, create_key=None):
+ if create_key is not _internal_create_key:
+ _Deprecated('ServiceDescriptor')
+
super(ServiceDescriptor, self).__init__(
options, 'ServiceOptions', name, full_name, file,
None, serialized_start=serialized_start,
@@ -788,14 +822,21 @@
method.containing_service = self
def FindMethodByName(self, name):
- """Searches for the specified method, and returns its descriptor."""
+ """Searches for the specified method, and returns its descriptor.
+
+ Args:
+ name (str): Name of the method.
+ Returns:
+ MethodDescriptor or None: the desctiptor for the requested method, if
+ found.
+ """
return self.methods_by_name.get(name, None)
def CopyToProto(self, proto):
"""Copies this to a descriptor_pb2.ServiceDescriptorProto.
Args:
- proto: An empty descriptor_pb2.ServiceDescriptorProto.
+ proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto.
"""
# This function is overridden to give a better doc comment.
super(ServiceDescriptor, self).CopyToProto(proto)
@@ -805,32 +846,40 @@
"""Descriptor for a method in a service.
- name: (str) Name of the method within the service.
- full_name: (str) Full name of method.
- index: (int) 0-indexed index of the method inside the service.
- containing_service: (ServiceDescriptor) The service that contains this
- method.
- input_type: The descriptor of the message that this method accepts.
- output_type: The descriptor of the message that this method returns.
- options: (descriptor_pb2.MethodOptions) Method options message or
- None to use default method options.
+ Attributes:
+ name (str): Name of the method within the service.
+ full_name (str): Full name of method.
+ index (int): 0-indexed index of the method inside the service.
+ containing_service (ServiceDescriptor): The service that contains this
+ method.
+ input_type (Descriptor): The descriptor of the message that this method
+ accepts.
+ output_type (Descriptor): The descriptor of the message that this method
+ returns.
+ options (descriptor_pb2.MethodOptions or None): Method options message, or
+ None to use default method options.
"""
if _USE_C_DESCRIPTORS:
_C_DESCRIPTOR_CLASS = _message.MethodDescriptor
def __new__(cls, name, full_name, index, containing_service,
- input_type, output_type, options=None, serialized_options=None):
+ input_type, output_type, options=None, serialized_options=None,
+ create_key=None):
_message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
return _message.default_pool.FindMethodByName(full_name)
def __init__(self, name, full_name, index, containing_service,
- input_type, output_type, options=None, serialized_options=None):
+ input_type, output_type, options=None, serialized_options=None,
+ create_key=None):
"""The arguments are as described in the description of MethodDescriptor
attributes above.
Note that containing_service may be None, and may be set later if necessary.
"""
+ if create_key is not _internal_create_key:
+ _Deprecated('MethodDescriptor')
+
super(MethodDescriptor, self).__init__(
options, serialized_options, 'MethodOptions')
self.name = name
@@ -844,24 +893,32 @@
class FileDescriptor(DescriptorBase):
"""Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
- Note that enum_types_by_name, extensions_by_name, and dependencies
- fields are only set by the message_factory module, and not by the
- generated proto code.
+ Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and
+ :attr:`dependencies` fields are only set by the
+ :py:mod:`google.protobuf.message_factory` module, and not by the generated
+ proto code.
- name: name of file, relative to root of source tree.
- package: name of the package
- syntax: string indicating syntax of the file (can be "proto2" or "proto3")
- serialized_pb: (str) Byte string of serialized
- descriptor_pb2.FileDescriptorProto.
- dependencies: List of other FileDescriptors this FileDescriptor depends on.
- public_dependencies: A list of FileDescriptors, subset of the dependencies
- above, which were declared as "public".
- message_types_by_name: Dict of message names and their descriptors.
- enum_types_by_name: Dict of enum names and their descriptors.
- extensions_by_name: Dict of extension names and their descriptors.
- services_by_name: Dict of services names and their descriptors.
- pool: the DescriptorPool this descriptor belongs to. When not passed to the
- constructor, the global default pool is used.
+ Attributes:
+ name (str): Name of file, relative to root of source tree.
+ package (str): Name of the package
+ syntax (str): string indicating syntax of the file (can be "proto2" or
+ "proto3")
+ serialized_pb (bytes): Byte string of serialized
+ :class:`descriptor_pb2.FileDescriptorProto`.
+ dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor`
+ objects this :class:`FileDescriptor` depends on.
+ public_dependencies (list[FileDescriptor]): A subset of
+ :attr:`dependencies`, which were declared as "public".
+ message_types_by_name (dict(str, Descriptor)): Mapping from message names
+ to their :class:`Desctiptor`.
+ enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to
+ their :class:`EnumDescriptor`.
+ extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension
+ names declared at file scope to their :class:`FieldDescriptor`.
+ services_by_name (dict(str, ServiceDescriptor)): Mapping from services'
+ names to their :class:`ServiceDescriptor`.
+ pool (DescriptorPool): The pool this descriptor belongs to. When not
+ passed to the constructor, the global default pool is used.
"""
if _USE_C_DESCRIPTORS:
@@ -870,11 +927,11 @@
def __new__(cls, name, package, options=None,
serialized_options=None, serialized_pb=None,
dependencies=None, public_dependencies=None,
- syntax=None, pool=None):
+ syntax=None, pool=None, create_key=None):
# FileDescriptor() is called from various places, not only from generated
# files, to register dynamic proto files and messages.
# pylint: disable=g-explicit-bool-comparison
- if serialized_pb == '':
+ if serialized_pb == b'':
# Cpp generated code must be linked in if serialized_pb is ''
try:
return _message.default_pool.FindFileByName(name)
@@ -888,8 +945,11 @@
def __init__(self, name, package, options=None,
serialized_options=None, serialized_pb=None,
dependencies=None, public_dependencies=None,
- syntax=None, pool=None):
+ syntax=None, pool=None, create_key=None):
"""Constructor."""
+ if create_key is not _internal_create_key:
+ _Deprecated('FileDescriptor')
+
super(FileDescriptor, self).__init__(
options, serialized_options, 'FileOptions')
@@ -1028,9 +1088,11 @@
for enum_proto in desc_proto.enum_type:
full_name = '.'.join(full_message_name + [enum_proto.name])
enum_desc = EnumDescriptor(
- enum_proto.name, full_name, None, [
- EnumValueDescriptor(enum_val.name, ii, enum_val.number)
- for ii, enum_val in enumerate(enum_proto.value)])
+ enum_proto.name, full_name, None, [
+ EnumValueDescriptor(enum_val.name, ii, enum_val.number,
+ create_key=_internal_create_key)
+ for ii, enum_val in enumerate(enum_proto.value)],
+ create_key=_internal_create_key)
enum_types[full_name] = enum_desc
# Create Descriptors for nested types
@@ -1069,10 +1131,11 @@
FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
field_proto.label, None, nested_desc, enum_desc, None, False, None,
options=_OptionsOrNone(field_proto), has_default_value=False,
- json_name=json_name)
+ json_name=json_name, create_key=_internal_create_key)
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=_OptionsOrNone(desc_proto))
+ options=_OptionsOrNone(desc_proto),
+ create_key=_internal_create_key)
diff --git a/python/google/protobuf/descriptor_pool.py b/python/google/protobuf/descriptor_pool.py
index d99d3f8..de9100b 100644
--- a/python/google/protobuf/descriptor_pool.py
+++ b/python/google/protobuf/descriptor_pool.py
@@ -38,7 +38,7 @@
the protocol buffer compiler tool. This should only be used when the type of
protocol buffers used in an application or library cannot be predetermined.
-Below is a straightforward example on how to use this class:
+Below is a straightforward example on how to use this class::
pool = DescriptorPool()
file_descriptor_protos = [ ... ]
@@ -91,10 +91,10 @@
generated with a leading period. This function removes that prefix.
Args:
- name: A str, the fully-qualified symbol name.
+ name (str): The fully-qualified symbol name.
Returns:
- A str, the normalized fully-qualified symbol name.
+ str: The normalized fully-qualified symbol name.
"""
return name.lstrip('.')
@@ -159,8 +159,8 @@
Args:
desc: Descriptor of a message, enum, service, extension or enum value.
- desc_name: the full name of desc.
- file_name: The file name of descriptor.
+ desc_name (str): the full name of desc.
+ file_name (str): The file name of descriptor.
"""
for register, descriptor_type in [
(self._descriptors, descriptor.Descriptor),
@@ -196,7 +196,7 @@
"""Adds the FileDescriptorProto and its types to this pool.
Args:
- file_desc_proto: The FileDescriptorProto to add.
+ file_desc_proto (FileDescriptorProto): The file descriptor to add.
"""
self._internal_db.Add(file_desc_proto)
@@ -205,8 +205,8 @@
"""Adds the FileDescriptorProto and its types to this pool.
Args:
- serialized_file_desc_proto: A bytes string, serialization of the
- FileDescriptorProto to add.
+ serialized_file_desc_proto (bytes): A bytes string, serialization of the
+ :class:`FileDescriptorProto` to add.
"""
# pylint: disable=g-import-not-at-top
@@ -392,10 +392,10 @@
"""Gets a FileDescriptor by file name.
Args:
- file_name: The path to the file to get a descriptor for.
+ file_name (str): The path to the file to get a descriptor for.
Returns:
- A FileDescriptor for the named file.
+ FileDescriptor: The descriptor for the named file.
Raises:
KeyError: if the file cannot be found in the pool.
@@ -421,10 +421,11 @@
"""Gets the FileDescriptor for the file containing the specified symbol.
Args:
- symbol: The name of the symbol to search for.
+ symbol (str): The name of the symbol to search for.
Returns:
- A FileDescriptor that contains the specified symbol.
+ FileDescriptor: Descriptor for the file that contains the specified
+ symbol.
Raises:
KeyError: if the file cannot be found in the pool.
@@ -447,10 +448,11 @@
"""Gets the already built FileDescriptor containing the specified symbol.
Args:
- symbol: The name of the symbol to search for.
+ symbol (str): The name of the symbol to search for.
Returns:
- A FileDescriptor that contains the specified symbol.
+ FileDescriptor: Descriptor for the file that contains the specified
+ symbol.
Raises:
KeyError: if the file cannot be found in the pool.
@@ -495,10 +497,10 @@
"""Loads the named descriptor from the pool.
Args:
- full_name: The full name of the descriptor to load.
+ full_name (str): The full name of the descriptor to load.
Returns:
- The descriptor for the named type.
+ Descriptor: The descriptor for the named type.
Raises:
KeyError: if the message cannot be found in the pool.
@@ -513,10 +515,10 @@
"""Loads the named enum descriptor from the pool.
Args:
- full_name: The full name of the enum descriptor to load.
+ full_name (str): The full name of the enum descriptor to load.
Returns:
- The enum descriptor for the named type.
+ EnumDescriptor: The enum descriptor for the named type.
Raises:
KeyError: if the enum cannot be found in the pool.
@@ -531,10 +533,10 @@
"""Loads the named field descriptor from the pool.
Args:
- full_name: The full name of the field descriptor to load.
+ full_name (str): The full name of the field descriptor to load.
Returns:
- The field descriptor for the named field.
+ FieldDescriptor: The field descriptor for the named field.
Raises:
KeyError: if the field cannot be found in the pool.
@@ -548,10 +550,10 @@
"""Loads the named oneof descriptor from the pool.
Args:
- full_name: The full name of the oneof descriptor to load.
+ full_name (str): The full name of the oneof descriptor to load.
Returns:
- The oneof descriptor for the named oneof.
+ OneofDescriptor: The oneof descriptor for the named oneof.
Raises:
KeyError: if the oneof cannot be found in the pool.
@@ -565,10 +567,10 @@
"""Loads the named extension descriptor from the pool.
Args:
- full_name: The full name of the extension descriptor to load.
+ full_name (str): The full name of the extension descriptor to load.
Returns:
- A FieldDescriptor, describing the named extension.
+ FieldDescriptor: The field descriptor for the named extension.
Raises:
KeyError: if the extension cannot be found in the pool.
@@ -594,15 +596,15 @@
def FindExtensionByNumber(self, message_descriptor, number):
"""Gets the extension of the specified message with the specified number.
- Extensions have to be registered to this pool by calling
- AddExtensionDescriptor.
+ Extensions have to be registered to this pool by calling :func:`Add` or
+ :func:`AddExtensionDescriptor`.
Args:
- message_descriptor: descriptor of the extended message.
- number: integer, number of the extension field.
+ message_descriptor (Descriptor): descriptor of the extended message.
+ number (int): Number of the extension field.
Returns:
- A FieldDescriptor describing the extension.
+ FieldDescriptor: The descriptor for the extension.
Raises:
KeyError: when no extension with the given number is known for the
@@ -615,16 +617,16 @@
return self._extensions_by_number[message_descriptor][number]
def FindAllExtensions(self, message_descriptor):
- """Gets all the known extension of a given message.
+ """Gets all the known extensions of a given message.
- Extensions have to be registered to this pool by calling
- AddExtensionDescriptor.
+ Extensions have to be registered to this pool by build related
+ :func:`Add` or :func:`AddExtensionDescriptor`.
Args:
- message_descriptor: descriptor of the extended message.
+ message_descriptor (Descriptor): Descriptor of the extended message.
Returns:
- A list of FieldDescriptor describing the extensions.
+ list[FieldDescriptor]: Field descriptors describing the extensions.
"""
# Fallback to descriptor db if FindAllExtensionNumbers is provided.
if self._descriptor_db and hasattr(
@@ -639,7 +641,7 @@
return list(self._extensions_by_number[message_descriptor].values())
def _TryLoadExtensionFromDB(self, message_descriptor, number):
- """Try to Load extensions from decriptor db.
+ """Try to Load extensions from descriptor db.
Args:
message_descriptor: descriptor of the extended message.
@@ -660,18 +662,7 @@
return
try:
- file_desc = self._ConvertFileProtoToFileDescriptor(file_proto)
- for extension in file_desc.extensions_by_name.values():
- self._extensions_by_number[extension.containing_type][
- extension.number] = extension
- self._extensions_by_name[extension.containing_type][
- extension.full_name] = extension
- for message_type in file_desc.message_types_by_name.values():
- for extension in message_type.extensions:
- self._extensions_by_number[extension.containing_type][
- extension.number] = extension
- self._extensions_by_name[extension.containing_type][
- extension.full_name] = extension
+ self._ConvertFileProtoToFileDescriptor(file_proto)
except:
warn_msg = ('Unable to load proto file %s for extension number %d.' %
(file_proto.name, number))
@@ -681,10 +672,10 @@
"""Loads the named service descriptor from the pool.
Args:
- full_name: The full name of the service descriptor to load.
+ full_name (str): The full name of the service descriptor to load.
Returns:
- The service descriptor for the named service.
+ ServiceDescriptor: The service descriptor for the named service.
Raises:
KeyError: if the service cannot be found in the pool.
@@ -698,10 +689,10 @@
"""Loads the named service method descriptor from the pool.
Args:
- full_name: The full name of the method descriptor to load.
+ full_name (str): The full name of the method descriptor to load.
Returns:
- The method descriptor for the service method.
+ MethodDescriptor: The method descriptor for the service method.
Raises:
KeyError: if the method cannot be found in the pool.
@@ -715,10 +706,10 @@
"""Finds the file in descriptor DB containing the specified symbol.
Args:
- symbol: The name of the symbol to search for.
+ symbol (str): The name of the symbol to search for.
Returns:
- A FileDescriptor that contains the specified symbol.
+ FileDescriptor: The file that contains the specified symbol.
Raises:
KeyError: if the file cannot be found in the descriptor database.
@@ -759,7 +750,9 @@
options=_OptionsOrNone(file_proto),
serialized_pb=file_proto.SerializeToString(),
dependencies=direct_deps,
- public_dependencies=public_deps)
+ public_dependencies=public_deps,
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
scope = {}
# This loop extracts all the message and enum types from all the
@@ -818,7 +811,15 @@
self.Add(file_proto)
self._file_descriptors[file_proto.name] = file_descriptor
- return self._file_descriptors[file_proto.name]
+ # Add extensions to the pool
+ file_desc = self._file_descriptors[file_proto.name]
+ for extension in file_desc.extensions_by_name.values():
+ self._AddExtensionDescriptor(extension)
+ for message_type in file_desc.message_types_by_name.values():
+ for extension in message_type.extensions:
+ self._AddExtensionDescriptor(extension)
+
+ return file_desc
def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
scope=None, syntax=None):
@@ -863,8 +864,11 @@
is_extension=True)
for index, extension in enumerate(desc_proto.extension)]
oneofs = [
+ # pylint: disable=g-complex-comprehension
descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
- index, None, [], desc.options)
+ index, None, [], desc.options,
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
for index, desc in enumerate(desc_proto.oneof_decl)]
extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
if extension_ranges:
@@ -887,7 +891,9 @@
file=file_desc,
serialized_start=None,
serialized_end=None,
- syntax=syntax)
+ syntax=syntax,
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
for nested in desc.nested_types:
nested.containing_type = desc
for enum in desc.enum_types:
@@ -938,7 +944,9 @@
file=file_desc,
values=values,
containing_type=containing_type,
- options=_OptionsOrNone(enum_proto))
+ options=_OptionsOrNone(enum_proto),
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
scope['.%s' % enum_name] = desc
self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
self._enum_descriptors[enum_name] = desc
@@ -995,7 +1003,9 @@
is_extension=is_extension,
extension_scope=None,
options=_OptionsOrNone(field_proto),
- file=file_desc)
+ file=file_desc,
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
def _SetAllFieldTypes(self, package, desc_proto, scope):
"""Sets all the descriptor's fields's types.
@@ -1034,7 +1044,7 @@
Args:
field_proto: Data about the field in proto format.
- field_desc: The descriptor to modiy.
+ field_desc: The descriptor to modify.
package: The package the field's container is in.
scope: Enclosing scope of available types.
"""
@@ -1119,7 +1129,9 @@
index=index,
number=value_proto.number,
options=_OptionsOrNone(value_proto),
- type=None)
+ type=None,
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
def _MakeServiceDescriptor(self, service_proto, service_index, scope,
package, file_desc):
@@ -1144,12 +1156,15 @@
methods = [self._MakeMethodDescriptor(method_proto, service_name, package,
scope, index)
for index, method_proto in enumerate(service_proto.method)]
- desc = descriptor.ServiceDescriptor(name=service_proto.name,
- full_name=service_name,
- index=service_index,
- methods=methods,
- options=_OptionsOrNone(service_proto),
- file=file_desc)
+ desc = descriptor.ServiceDescriptor(
+ name=service_proto.name,
+ full_name=service_name,
+ index=service_index,
+ methods=methods,
+ options=_OptionsOrNone(service_proto),
+ file=file_desc,
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
self._service_descriptors[service_name] = desc
return desc
@@ -1173,13 +1188,16 @@
package, method_proto.input_type, scope)
output_type = self._GetTypeFromScope(
package, method_proto.output_type, scope)
- return descriptor.MethodDescriptor(name=method_proto.name,
- full_name=full_name,
- index=index,
- containing_service=None,
- input_type=input_type,
- output_type=output_type,
- options=_OptionsOrNone(method_proto))
+ return descriptor.MethodDescriptor(
+ name=method_proto.name,
+ full_name=full_name,
+ index=index,
+ containing_service=None,
+ input_type=input_type,
+ output_type=output_type,
+ options=_OptionsOrNone(method_proto),
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
def _ExtractSymbols(self, descriptors):
"""Pulls out all the symbols from descriptor protos.
diff --git a/python/google/protobuf/internal/__init__.py b/python/google/protobuf/internal/__init__.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/internal/api_implementation.py b/python/google/protobuf/internal/api_implementation.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/internal/containers.py b/python/google/protobuf/internal/containers.py
old mode 100755
new mode 100644
index 173666f..ecd28ee
--- a/python/google/protobuf/internal/containers.py
+++ b/python/google/protobuf/internal/containers.py
@@ -33,9 +33,10 @@
This file defines container classes which represent categories of protocol
buffer field types which need extra maintenance. Currently these categories
are:
- - Repeated scalar fields - These are all repeated fields which aren't
+
+- Repeated scalar fields - These are all repeated fields which aren't
composite (e.g. they are of simple types like int32, string, etc).
- - Repeated composite fields - Repeated fields which are composite. This
+- Repeated composite fields - Repeated fields which are composite. This
includes groups and nested messages.
"""
@@ -285,7 +286,6 @@
def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
-
one. We do not check the types of the individual fields.
"""
self._values.extend(other._values)
@@ -416,7 +416,6 @@
def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
-
one, copying each individual message.
"""
self.extend(other._values)
diff --git a/python/google/protobuf/internal/decoder.py b/python/google/protobuf/internal/decoder.py
old mode 100755
new mode 100644
index c04df8e..092dab5
--- a/python/google/protobuf/internal/decoder.py
+++ b/python/google/protobuf/internal/decoder.py
@@ -816,8 +816,12 @@
if extension is not None:
value = field_dict.get(extension)
if value is None:
+ message_type = extension.message_type
+ if not hasattr(message_type, '_concrete_class'):
+ # pylint: disable=protected-access
+ message._FACTORY.GetPrototype(message_type)
value = field_dict.setdefault(
- extension, extension.message_type._concrete_class())
+ extension, message_type._concrete_class())
if value._InternalParse(buffer, message_start,message_end) != message_end:
# The only reason _InternalParse would return early is if it encountered
# an end-group tag.
diff --git a/python/google/protobuf/internal/descriptor_database_test.py b/python/google/protobuf/internal/descriptor_database_test.py
old mode 100644
new mode 100755
diff --git a/python/google/protobuf/internal/descriptor_pool_test.py b/python/google/protobuf/internal/descriptor_pool_test.py
old mode 100644
new mode 100755
index ad1eb65..fed82bf
--- a/python/google/protobuf/internal/descriptor_pool_test.py
+++ b/python/google/protobuf/internal/descriptor_pool_test.py
@@ -36,6 +36,7 @@
import copy
import os
+import warnings
try:
import unittest2 as unittest #PY26
@@ -63,6 +64,9 @@
+warnings.simplefilter('error', DeprecationWarning)
+
+
class DescriptorPoolTestBase(object):
def testFindFileByName(self):
@@ -336,12 +340,10 @@
'google.protobuf.python.internal.Factory2Message')
# An extension defined in a message.
one_more_field = factory2_message.extensions_by_name['one_more_field']
- self.pool.AddExtensionDescriptor(one_more_field)
# An extension defined at file scope.
factory_test2 = self.pool.FindFileByName(
'google/protobuf/internal/factory_test2.proto')
another_field = factory_test2.extensions_by_name['another_field']
- self.pool.AddExtensionDescriptor(another_field)
extensions = self.pool.FindAllExtensions(factory1_message)
expected_extension_numbers = set([one_more_field, another_field])
@@ -356,16 +358,9 @@
def testFindExtensionByNumber(self):
factory1_message = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory1Message')
- factory2_message = self.pool.FindMessageTypeByName(
- 'google.protobuf.python.internal.Factory2Message')
- # An extension defined in a message.
- one_more_field = factory2_message.extensions_by_name['one_more_field']
- self.pool.AddExtensionDescriptor(one_more_field)
- # An extension defined at file scope.
- factory_test2 = self.pool.FindFileByName(
+ # Build factory_test2.proto which will put extensions to the pool
+ self.pool.FindFileByName(
'google/protobuf/internal/factory_test2.proto')
- another_field = factory_test2.extensions_by_name['another_field']
- self.pool.AddExtensionDescriptor(another_field)
# An extension defined in a message.
extension = self.pool.FindExtensionByNumber(factory1_message, 1001)
@@ -533,13 +528,13 @@
else:
pool = copy.deepcopy(self.pool)
file_descriptor = unittest_pb2.DESCRIPTOR
- pool.AddDescriptor(
+ pool._AddDescriptor(
file_descriptor.message_types_by_name['TestAllTypes'])
- pool.AddEnumDescriptor(
+ pool._AddEnumDescriptor(
file_descriptor.enum_types_by_name['ForeignEnum'])
- pool.AddServiceDescriptor(
+ pool._AddServiceDescriptor(
file_descriptor.services_by_name['TestService'])
- pool.AddExtensionDescriptor(
+ pool._AddExtensionDescriptor(
file_descriptor.extensions_by_name['optional_int32_extension'])
pool.Add(unittest_fd)
pool.Add(conflict_fd)
@@ -873,7 +868,7 @@
def _TestMessage(self, prefix):
pool = descriptor_pool.DescriptorPool()
- pool.AddDescriptor(unittest_pb2.TestAllTypes.DESCRIPTOR)
+ pool._AddDescriptor(unittest_pb2.TestAllTypes.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.TestAllTypes',
pool.FindMessageTypeByName(
@@ -884,7 +879,7 @@
pool.FindMessageTypeByName(
prefix + 'protobuf_unittest.TestAllTypes.NestedMessage')
- pool.AddDescriptor(unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR)
+ pool._AddDescriptor(unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.TestAllTypes.NestedMessage',
pool.FindMessageTypeByName(
@@ -909,7 +904,10 @@
def _TestEnum(self, prefix):
pool = descriptor_pool.DescriptorPool()
- pool.AddEnumDescriptor(unittest_pb2.ForeignEnum.DESCRIPTOR)
+ if api_implementation.Type() == 'cpp':
+ pool.AddEnumDescriptor(unittest_pb2.ForeignEnum.DESCRIPTOR)
+ else:
+ pool._AddEnumDescriptor(unittest_pb2.ForeignEnum.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.ForeignEnum',
pool.FindEnumTypeByName(
@@ -920,7 +918,10 @@
pool.FindEnumTypeByName(
prefix + 'protobuf_unittest.ForeignEnum.NestedEnum')
- pool.AddEnumDescriptor(unittest_pb2.TestAllTypes.NestedEnum.DESCRIPTOR)
+ if api_implementation.Type() == 'cpp':
+ pool.AddEnumDescriptor(unittest_pb2.TestAllTypes.NestedEnum.DESCRIPTOR)
+ else:
+ pool._AddEnumDescriptor(unittest_pb2.TestAllTypes.NestedEnum.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.TestAllTypes.NestedEnum',
pool.FindEnumTypeByName(
@@ -949,7 +950,7 @@
pool = descriptor_pool.DescriptorPool()
with self.assertRaises(KeyError):
pool.FindServiceByName('protobuf_unittest.TestService')
- pool.AddServiceDescriptor(unittest_pb2._TESTSERVICE)
+ pool._AddServiceDescriptor(unittest_pb2._TESTSERVICE)
self.assertEqual(
'protobuf_unittest.TestService',
pool.FindServiceByName('protobuf_unittest.TestService').full_name)
@@ -958,7 +959,7 @@
'With the cpp implementation, Add() must be called first')
def testFile(self):
pool = descriptor_pool.DescriptorPool()
- pool.AddFileDescriptor(unittest_pb2.DESCRIPTOR)
+ pool._AddFileDescriptor(unittest_pb2.DESCRIPTOR)
self.assertEqual(
'google/protobuf/unittest.proto',
pool.FindFileByName(
@@ -1032,16 +1033,28 @@
def testAddTypeError(self):
pool = descriptor_pool.DescriptorPool()
- with self.assertRaises(TypeError):
- pool.AddDescriptor(0)
- with self.assertRaises(TypeError):
- pool.AddEnumDescriptor(0)
- with self.assertRaises(TypeError):
- pool.AddServiceDescriptor(0)
- with self.assertRaises(TypeError):
- pool.AddExtensionDescriptor(0)
- with self.assertRaises(TypeError):
- pool.AddFileDescriptor(0)
+ if api_implementation.Type() == 'cpp':
+ with self.assertRaises(TypeError):
+ pool.AddDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddEnumDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddServiceDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddExtensionDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool.AddFileDescriptor(0)
+ else:
+ with self.assertRaises(TypeError):
+ pool._AddDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool._AddEnumDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool._AddServiceDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool._AddExtensionDescriptor(0)
+ with self.assertRaises(TypeError):
+ pool._AddFileDescriptor(0)
TEST1_FILE = ProtoFile(
diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py
index bff2d5f..5e3b0a9 100755
--- a/python/google/protobuf/internal/descriptor_test.py
+++ b/python/google/protobuf/internal/descriptor_test.py
@@ -35,6 +35,7 @@
__author__ = 'robinson@google.com (Will Robinson)'
import sys
+import warnings
try:
import unittest2 as unittest #PY26
@@ -58,6 +59,9 @@
"""
+warnings.simplefilter('error', DeprecationWarning)
+
+
class DescriptorTest(unittest.TestCase):
def setUp(self):
diff --git a/python/google/protobuf/internal/encoder.py b/python/google/protobuf/internal/encoder.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/internal/extension_dict.py b/python/google/protobuf/internal/extension_dict.py
index a44bf9d..b346cf2 100644
--- a/python/google/protobuf/internal/extension_dict.py
+++ b/python/google/protobuf/internal/extension_dict.py
@@ -87,6 +87,10 @@
if extension_handle.label == FieldDescriptor.LABEL_REPEATED:
result = extension_handle._default_constructor(self._extended_message)
elif extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
+ message_type = extension_handle.message_type
+ if not hasattr(message_type, '_concrete_class'):
+ # pylint: disable=protected-access
+ self._extended_message._FACTORY.GetPrototype(message_type)
assert getattr(extension_handle.message_type, '_concrete_class', None), (
'Uninitialized concrete class found for field %r (message type %r)'
% (extension_handle.full_name,
@@ -139,7 +143,7 @@
# Note that this is only meaningful for non-repeated, scalar extension
# fields. Note also that we may have to call _Modified() when we do
- # successfully set a field this way, to set any necssary "has" bits in the
+ # successfully set a field this way, to set any necessary "has" bits in the
# ancestors of the extended message.
def __setitem__(self, extension_handle, value):
"""If extension_handle specifies a non-repeated, scalar extension
diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py
old mode 100644
new mode 100755
index e3992f9..2d42674
--- a/python/google/protobuf/internal/json_format_test.py
+++ b/python/google/protobuf/internal/json_format_test.py
@@ -36,6 +36,7 @@
import json
import math
+import struct
import sys
try:
@@ -52,6 +53,7 @@
from google.protobuf import any_test_pb2
from google.protobuf import unittest_mset_pb2
from google.protobuf import unittest_pb2
+from google.protobuf.internal import test_proto3_optional_pb2
from google.protobuf import descriptor_pool
from google.protobuf import json_format
from google.protobuf.util import json_format_pb2
@@ -237,16 +239,19 @@
golden_dict = {
'messageSet': {
'[protobuf_unittest.'
- 'TestMessageSetExtension1.messageSetExtension]': {
+ 'TestMessageSetExtension1.message_set_extension]': {
'i': 23,
},
'[protobuf_unittest.'
- 'TestMessageSetExtension2.messageSetExtension]': {
+ 'TestMessageSetExtension2.message_set_extension]': {
'str': u'foo',
},
},
}
self.assertEqual(golden_dict, message_dict)
+ parsed_msg = unittest_mset_pb2.TestMessageSetContainer()
+ json_format.ParseDict(golden_dict, parsed_msg)
+ self.assertEqual(message, parsed_msg)
def testExtensionSerializationDictMatchesProto3SpecMore(self):
"""See go/proto3-json-spec for spec.
@@ -277,9 +282,9 @@
message
)
ext1_text = ('protobuf_unittest.TestMessageSetExtension1.'
- 'messageSetExtension')
+ 'message_set_extension')
ext2_text = ('protobuf_unittest.TestMessageSetExtension2.'
- 'messageSetExtension')
+ 'message_set_extension')
golden_text = ('{"messageSet": {'
' "[%s]": {'
' "i": 23'
@@ -338,6 +343,20 @@
parsed_message = json_format_proto3_pb2.TestMessage()
self.CheckParseBack(message, parsed_message)
+ def testProto3Optional(self):
+ message = test_proto3_optional_pb2.TestProto3Optional()
+ self.assertEqual(
+ json.loads(
+ json_format.MessageToJson(
+ message, including_default_value_fields=True)),
+ json.loads('{}'))
+ message.optional_int32 = 0
+ self.assertEqual(
+ json.loads(
+ json_format.MessageToJson(
+ message, including_default_value_fields=True)),
+ json.loads('{"optionalInt32": 0}'))
+
def testIntegersRepresentedAsFloat(self):
message = json_format_proto3_pb2.TestMessage()
json_format.Parse('{"int32Value": -2.147483648e9}', message)
@@ -821,11 +840,41 @@
def testFloatPrecision(self):
message = json_format_proto3_pb2.TestMessage()
message.float_value = 1.123456789
+ # Set to 8 valid digits.
+ text = '{\n "floatValue": 1.1234568\n}'
+ self.assertEqual(
+ json_format.MessageToJson(message, float_precision=8), text)
# Set to 7 valid digits.
text = '{\n "floatValue": 1.123457\n}'
self.assertEqual(
json_format.MessageToJson(message, float_precision=7), text)
+ # Default float_precision will automatic print shortest float.
+ message.float_value = 1.1000000011
+ text = '{\n "floatValue": 1.1\n}'
+ self.assertEqual(
+ json_format.MessageToJson(message), text)
+ message.float_value = 1.00000075e-36
+ text = '{\n "floatValue": 1.00000075e-36\n}'
+ self.assertEqual(
+ json_format.MessageToJson(message), text)
+ message.float_value = 12345678912345e+11
+ text = '{\n "floatValue": 1.234568e+24\n}'
+ self.assertEqual(
+ json_format.MessageToJson(message), text)
+
+ # Test a bunch of data and check json encode/decode do not
+ # lose precision
+ value_list = [0x00, 0xD8, 0x6E, 0x00]
+ msg2 = json_format_proto3_pb2.TestMessage()
+ for a in range(0, 256):
+ value_list[3] = a
+ for b in range(0, 256):
+ value_list[0] = b
+ byte_array = bytearray(value_list)
+ message.float_value = struct.unpack('<f', byte_array)[0]
+ self.CheckParseBack(message, msg2)
+
def testParseEmptyText(self):
self.CheckError('',
r'Failed to load JSON: (Expecting value)|(No JSON).')
diff --git a/python/google/protobuf/internal/message_factory_test.py b/python/google/protobuf/internal/message_factory_test.py
old mode 100644
new mode 100755
diff --git a/python/google/protobuf/internal/message_listener.py b/python/google/protobuf/internal/message_listener.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py
index f12b531..0508bb2 100755
--- a/python/google/protobuf/internal/message_test.py
+++ b/python/google/protobuf/internal/message_test.py
@@ -83,6 +83,7 @@
from google.protobuf.internal import more_extensions_pb2
from google.protobuf.internal import packed_field_test_pb2
from google.protobuf.internal import test_util
+from google.protobuf.internal import test_proto3_optional_pb2
from google.protobuf.internal import testing_refleaks
from google.protobuf import message
from google.protobuf.internal import _parameterized
@@ -106,6 +107,9 @@
return isinf(val) and (val < 0)
+warnings.simplefilter('error', DeprecationWarning)
+
+
@_parameterized.named_parameters(
('_proto2', unittest_pb2),
('_proto3', unittest_proto3_arena_pb2))
@@ -438,12 +442,19 @@
self.assertEqual(str(message), 'optional_float: 2.0\n')
def testHighPrecisionFloatPrinting(self, message_module):
- message = message_module.TestAllTypes()
- message.optional_double = 0.12345678912345678
+ msg = message_module.TestAllTypes()
+ msg.optional_float = 0.12345678912345678
+ old_float = msg.optional_float
+ msg.ParseFromString(msg.SerializeToString())
+ self.assertEqual(old_float, msg.optional_float)
+
+ def testHighPrecisionDoublePrinting(self, message_module):
+ msg = message_module.TestAllTypes()
+ msg.optional_double = 0.12345678912345678
if sys.version_info >= (3,):
- self.assertEqual(str(message), 'optional_double: 0.12345678912345678\n')
+ self.assertEqual(str(msg), 'optional_double: 0.12345678912345678\n')
else:
- self.assertEqual(str(message), 'optional_double: 0.123456789123\n')
+ self.assertEqual(str(msg), 'optional_double: 0.123456789123\n')
def testUnknownFieldPrinting(self, message_module):
populated = message_module.TestAllTypes()
@@ -885,11 +896,13 @@
def testOneofDefaultValues(self, message_module):
m = message_module.TestAllTypes()
self.assertIs(None, m.WhichOneof('oneof_field'))
+ self.assertFalse(m.HasField('oneof_field'))
self.assertFalse(m.HasField('oneof_uint32'))
# Oneof is set even when setting it to a default value.
m.oneof_uint32 = 0
self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field'))
+ self.assertTrue(m.HasField('oneof_field'))
self.assertTrue(m.HasField('oneof_uint32'))
self.assertFalse(m.HasField('oneof_string'))
@@ -1662,6 +1675,59 @@
self.assertEqual(False, message.optional_bool)
self.assertEqual(0, message.optional_nested_message.bb)
+ def testProto3Optional(self):
+ msg = test_proto3_optional_pb2.TestProto3Optional()
+ self.assertFalse(msg.HasField('optional_int32'))
+ self.assertFalse(msg.HasField('optional_float'))
+ self.assertFalse(msg.HasField('optional_string'))
+ self.assertFalse(msg.HasField('optional_nested_message'))
+ self.assertFalse(msg.optional_nested_message.HasField('bb'))
+
+ # Set fields.
+ msg.optional_int32 = 1
+ msg.optional_float = 1.0
+ msg.optional_string = '123'
+ msg.optional_nested_message.bb = 1
+ self.assertTrue(msg.HasField('optional_int32'))
+ self.assertTrue(msg.HasField('optional_float'))
+ self.assertTrue(msg.HasField('optional_string'))
+ self.assertTrue(msg.HasField('optional_nested_message'))
+ self.assertTrue(msg.optional_nested_message.HasField('bb'))
+ # Set to default value does not clear the fields
+ msg.optional_int32 = 0
+ msg.optional_float = 0.0
+ msg.optional_string = ''
+ msg.optional_nested_message.bb = 0
+ self.assertTrue(msg.HasField('optional_int32'))
+ self.assertTrue(msg.HasField('optional_float'))
+ self.assertTrue(msg.HasField('optional_string'))
+ self.assertTrue(msg.HasField('optional_nested_message'))
+ self.assertTrue(msg.optional_nested_message.HasField('bb'))
+
+ # Test serialize
+ msg2 = test_proto3_optional_pb2.TestProto3Optional()
+ msg2.ParseFromString(msg.SerializeToString())
+ self.assertTrue(msg2.HasField('optional_int32'))
+ self.assertTrue(msg2.HasField('optional_float'))
+ self.assertTrue(msg2.HasField('optional_string'))
+ self.assertTrue(msg2.HasField('optional_nested_message'))
+ self.assertTrue(msg2.optional_nested_message.HasField('bb'))
+
+ self.assertEqual(msg.WhichOneof('_optional_int32'), 'optional_int32')
+
+ # Clear these fields.
+ msg.ClearField('optional_int32')
+ msg.ClearField('optional_float')
+ msg.ClearField('optional_string')
+ msg.ClearField('optional_nested_message')
+ self.assertFalse(msg.HasField('optional_int32'))
+ self.assertFalse(msg.HasField('optional_float'))
+ self.assertFalse(msg.HasField('optional_string'))
+ self.assertFalse(msg.HasField('optional_nested_message'))
+ self.assertFalse(msg.optional_nested_message.HasField('bb'))
+
+ self.assertEqual(msg.WhichOneof('_optional_int32'), None)
+
def testAssignUnknownEnum(self):
"""Assigning an unknown enum value is allowed and preserves the value."""
m = unittest_proto3_arena_pb2.TestAllTypes()
diff --git a/python/google/protobuf/internal/proto_builder_test.py b/python/google/protobuf/internal/proto_builder_test.py
old mode 100644
new mode 100755
diff --git a/python/google/protobuf/internal/python_message.py b/python/google/protobuf/internal/python_message.py
old mode 100755
new mode 100644
index 8fb1946..beea894
--- a/python/google/protobuf/internal/python_message.py
+++ b/python/google/protobuf/internal/python_message.py
@@ -124,9 +124,16 @@
Returns:
Newly-allocated class.
+
+ Raises:
+ RuntimeError: Generated code only work with python cpp extension.
"""
descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
+ if isinstance(descriptor, str):
+ raise RuntimeError('The generated code only work with python cpp '
+ 'extension, but it is using pure python runtime.')
+
# If a concrete class already exists for this descriptor, don't try to
# create another. Doing so will break any messages that already exist with
# the existing class.
@@ -819,7 +826,8 @@
cls.ListFields = ListFields
_PROTO3_ERROR_TEMPLATE = \
- 'Protocol message %s has no non-repeated submessage field "%s"'
+ ('Protocol message %s has no non-repeated submessage field "%s" '
+ 'nor marked as optional')
_PROTO2_ERROR_TEMPLATE = 'Protocol message %s has no non-repeated field "%s"'
def _AddHasFieldMethod(message_descriptor, cls):
@@ -838,10 +846,9 @@
continue
hassable_fields[field.name] = field
- if not is_proto3:
- # Fields inside oneofs are never repeated (enforced by the compiler).
- for oneof in message_descriptor.oneofs:
- hassable_fields[oneof.name] = oneof
+ # Has methods are supported for oneof descriptors.
+ for oneof in message_descriptor.oneofs:
+ hassable_fields[oneof.name] = oneof
def HasField(self, field_name):
try:
diff --git a/python/google/protobuf/internal/reflection_test.py b/python/google/protobuf/internal/reflection_test.py
index dace154..e67248f 100755
--- a/python/google/protobuf/internal/reflection_test.py
+++ b/python/google/protobuf/internal/reflection_test.py
@@ -40,6 +40,7 @@
import operator
import six
import struct
+import warnings
try:
import unittest2 as unittest #PY26
@@ -70,6 +71,9 @@
long = int # pylint: disable=redefined-builtin,invalid-name
+warnings.simplefilter('error', DeprecationWarning)
+
+
class _MiniDecoder(object):
"""Decodes a stream of values from a string.
@@ -1433,12 +1437,16 @@
label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
containing_type=None, message_type=None, enum_type=None,
is_extension=False, extension_scope=None,
- options=descriptor_pb2.FieldOptions())
+ options=descriptor_pb2.FieldOptions(),
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
mydescriptor = descriptor.Descriptor(
name='MyProto', full_name='MyProto', filename='ignored',
containing_type=None, nested_types=[], enum_types=[],
fields=[foo_field_descriptor], extensions=[],
- options=descriptor_pb2.MessageOptions())
+ options=descriptor_pb2.MessageOptions(),
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = mydescriptor
myproto_instance = MyProtoClass()
@@ -3168,22 +3176,34 @@
'C++ implementation requires a call to MakeDescriptor()')
@testing_refleaks.SkipReferenceLeakChecker('MakeClass is not repeatable')
def testMakeClassWithNestedDescriptor(self):
- leaf_desc = descriptor.Descriptor('leaf', 'package.parent.child.leaf', '',
- containing_type=None, fields=[],
- nested_types=[], enum_types=[],
- extensions=[])
- child_desc = descriptor.Descriptor('child', 'package.parent.child', '',
- containing_type=None, fields=[],
- nested_types=[leaf_desc], enum_types=[],
- extensions=[])
- sibling_desc = descriptor.Descriptor('sibling', 'package.parent.sibling',
- '', containing_type=None, fields=[],
- nested_types=[], enum_types=[],
- extensions=[])
- parent_desc = descriptor.Descriptor('parent', 'package.parent', '',
- containing_type=None, fields=[],
- nested_types=[child_desc, sibling_desc],
- enum_types=[], extensions=[])
+ leaf_desc = descriptor.Descriptor(
+ 'leaf', 'package.parent.child.leaf', '',
+ containing_type=None, fields=[],
+ nested_types=[], enum_types=[],
+ extensions=[],
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
+ child_desc = descriptor.Descriptor(
+ 'child', 'package.parent.child', '',
+ containing_type=None, fields=[],
+ nested_types=[leaf_desc], enum_types=[],
+ extensions=[],
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
+ sibling_desc = descriptor.Descriptor(
+ 'sibling', 'package.parent.sibling',
+ '', containing_type=None, fields=[],
+ nested_types=[], enum_types=[],
+ extensions=[],
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
+ parent_desc = descriptor.Descriptor(
+ 'parent', 'package.parent', '',
+ containing_type=None, fields=[],
+ nested_types=[child_desc, sibling_desc],
+ enum_types=[], extensions=[],
+ # pylint: disable=protected-access
+ create_key=descriptor._internal_create_key)
reflection.MakeClass(parent_desc)
def _GetSerializedFileDescriptor(self, name):
@@ -3305,4 +3325,3 @@
if __name__ == '__main__':
unittest.main()
-
diff --git a/python/google/protobuf/internal/symbol_database_test.py b/python/google/protobuf/internal/symbol_database_test.py
old mode 100644
new mode 100755
diff --git a/python/google/protobuf/internal/test_proto3_optional.proto b/python/google/protobuf/internal/test_proto3_optional.proto
new file mode 100644
index 0000000..f3e0a2e
--- /dev/null
+++ b/python/google/protobuf/internal/test_proto3_optional.proto
@@ -0,0 +1,70 @@
+// 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.python.internal;
+
+message TestProto3Optional {
+ message NestedMessage {
+ // The field name "b" fails to compile in proto1 because it conflicts with
+ // a local variable named "b" in one of the generated methods. Doh.
+ // This file needs to compile in proto1 to test backwards-compatibility.
+ optional int32 bb = 1;
+ }
+
+ enum NestedEnum {
+ UNSPECIFIED = 0;
+ FOO = 1;
+ BAR = 2;
+ BAZ = 3;
+ NEG = -1; // Intentionally negative.
+ }
+
+ // Singular
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional sint32 optional_sint32 = 5;
+ optional sint64 optional_sint64 = 6;
+ optional fixed32 optional_fixed32 = 7;
+ optional fixed64 optional_fixed64 = 8;
+ optional sfixed32 optional_sfixed32 = 9;
+ optional sfixed64 optional_sfixed64 = 10;
+ optional float optional_float = 11;
+ optional double optional_double = 12;
+ optional bool optional_bool = 13;
+ optional string optional_string = 14;
+ optional bytes optional_bytes = 15;
+
+ optional NestedMessage optional_nested_message = 18;
+ optional NestedEnum optional_nested_enum = 21;
+}
diff --git a/python/google/protobuf/internal/test_util.py b/python/google/protobuf/internal/test_util.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py
index aa6f97b..9e84185 100755
--- a/python/google/protobuf/internal/text_format_test.py
+++ b/python/google/protobuf/internal/text_format_test.py
@@ -57,6 +57,7 @@
from google.protobuf import descriptor_pb2
from google.protobuf.internal import any_test_pb2 as test_extend_any
from google.protobuf.internal import message_set_extensions_pb2
+from google.protobuf.internal import test_proto3_optional_pb2
from google.protobuf.internal import test_util
from google.protobuf import descriptor_pool
from google.protobuf import text_format
@@ -97,7 +98,7 @@
text = text.replace('e+0','e+').replace('e+0','e+') \
.replace('e-0','e-').replace('e-0','e-')
# Floating point fields are printed with .0 suffix even if they are
- # actualy integer numbers.
+ # actually integer numbers.
text = re.compile(r'\.0$', re.MULTILINE).sub('', text)
return text
@@ -125,6 +126,110 @@
' "\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""\n'
'repeated_string: "\\303\\274\\352\\234\\237"\n')
+ def testPrintFloatPrecision(self, message_module):
+ message = message_module.TestAllTypes()
+
+ message.repeated_float.append(0.0)
+ message.repeated_float.append(0.8)
+ message.repeated_float.append(1.0)
+ message.repeated_float.append(1.2)
+ message.repeated_float.append(1.23)
+ message.repeated_float.append(1.234)
+ message.repeated_float.append(1.2345)
+ message.repeated_float.append(1.23456)
+ message.repeated_float.append(1.2e10)
+ message.repeated_float.append(1.23e10)
+ message.repeated_float.append(1.234e10)
+ message.repeated_float.append(1.2345e10)
+ message.repeated_float.append(1.23456e10)
+ message.repeated_double.append(0.0)
+ message.repeated_double.append(0.8)
+ message.repeated_double.append(1.0)
+ message.repeated_double.append(1.2)
+ message.repeated_double.append(1.23)
+ message.repeated_double.append(1.234)
+ message.repeated_double.append(1.2345)
+ message.repeated_double.append(1.23456)
+ message.repeated_double.append(1.234567)
+ message.repeated_double.append(1.2345678)
+ message.repeated_double.append(1.23456789)
+ message.repeated_double.append(1.234567898)
+ message.repeated_double.append(1.2345678987)
+ message.repeated_double.append(1.23456789876)
+ message.repeated_double.append(1.234567898765)
+ message.repeated_double.append(1.2345678987654)
+ message.repeated_double.append(1.23456789876543)
+ message.repeated_double.append(1.2e100)
+ message.repeated_double.append(1.23e100)
+ message.repeated_double.append(1.234e100)
+ message.repeated_double.append(1.2345e100)
+ message.repeated_double.append(1.23456e100)
+ message.repeated_double.append(1.234567e100)
+ message.repeated_double.append(1.2345678e100)
+ message.repeated_double.append(1.23456789e100)
+ message.repeated_double.append(1.234567898e100)
+ message.repeated_double.append(1.2345678987e100)
+ message.repeated_double.append(1.23456789876e100)
+ message.repeated_double.append(1.234567898765e100)
+ message.repeated_double.append(1.2345678987654e100)
+ message.repeated_double.append(1.23456789876543e100)
+ # pylint: disable=g-long-ternary
+ self.CompareToGoldenText(
+ self.RemoveRedundantZeros(text_format.MessageToString(message)),
+ 'repeated_float: 0\n'
+ 'repeated_float: 0.8\n'
+ 'repeated_float: 1\n'
+ 'repeated_float: 1.2\n'
+ 'repeated_float: 1.23\n'
+ 'repeated_float: 1.234\n'
+ 'repeated_float: 1.2345\n'
+ 'repeated_float: 1.23456\n'
+ # Note that these don't use scientific notation.
+ 'repeated_float: 12000000000\n'
+ 'repeated_float: 12300000000\n'
+ 'repeated_float: 12340000000\n'
+ 'repeated_float: 12345000000\n'
+ 'repeated_float: 12345600000\n'
+ 'repeated_double: 0\n'
+ 'repeated_double: 0.8\n'
+ 'repeated_double: 1\n'
+ 'repeated_double: 1.2\n'
+ 'repeated_double: 1.23\n'
+ 'repeated_double: 1.234\n'
+ 'repeated_double: 1.2345\n'
+ 'repeated_double: 1.23456\n'
+ 'repeated_double: 1.234567\n'
+ 'repeated_double: 1.2345678\n'
+ 'repeated_double: 1.23456789\n'
+ 'repeated_double: 1.234567898\n'
+ 'repeated_double: 1.2345678987\n'
+ 'repeated_double: 1.23456789876\n' +
+ ('repeated_double: 1.23456789876\n'
+ 'repeated_double: 1.23456789877\n'
+ 'repeated_double: 1.23456789877\n'
+ if six.PY2 else
+ 'repeated_double: 1.234567898765\n'
+ 'repeated_double: 1.2345678987654\n'
+ 'repeated_double: 1.23456789876543\n') +
+ 'repeated_double: 1.2e+100\n'
+ 'repeated_double: 1.23e+100\n'
+ 'repeated_double: 1.234e+100\n'
+ 'repeated_double: 1.2345e+100\n'
+ 'repeated_double: 1.23456e+100\n'
+ 'repeated_double: 1.234567e+100\n'
+ 'repeated_double: 1.2345678e+100\n'
+ 'repeated_double: 1.23456789e+100\n'
+ 'repeated_double: 1.234567898e+100\n'
+ 'repeated_double: 1.2345678987e+100\n'
+ 'repeated_double: 1.23456789876e+100\n' +
+ ('repeated_double: 1.23456789877e+100\n'
+ 'repeated_double: 1.23456789877e+100\n'
+ 'repeated_double: 1.23456789877e+100\n'
+ if six.PY2 else
+ 'repeated_double: 1.234567898765e+100\n'
+ 'repeated_double: 1.2345678987654e+100\n'
+ 'repeated_double: 1.23456789876543e+100\n'))
+
def testPrintExoticUnicodeSubclass(self, message_module):
class UnicodeSub(six.text_type):
@@ -294,8 +399,7 @@
# 32-bit 1.2 is noisy when extended to 64-bit:
# >>> struct.unpack('f', struct.pack('f', 1.2))[0]
# 1.2000000476837158
- # TODO(jieluo): change to 1.2 with cl/241634942.
- message.payload.optional_float = 1.2000000476837158
+ message.payload.optional_float = 1.2
formatted_fields = ['optional_float: 1.2',
'optional_double: -3.45678901234568e-6',
'repeated_float: -5642', 'repeated_double: 7.89e-5']
@@ -316,7 +420,7 @@
'payload {{\n {0}\n {1}\n {2}\n {3}\n}}\n'.format(
*formatted_fields))
- # Test default float_format has 8 valid digits.
+ # Test default float_format will automatic print shortest float.
message.payload.optional_float = 1.2345678912
message.payload.optional_double = 1.2345678912
formatted_fields = ['optional_float: 1.2345679',
@@ -328,6 +432,17 @@
'payload {{\n {0}\n {1}\n {2}\n {3}\n}}\n'.format(
*formatted_fields))
+ message.Clear()
+ message.payload.optional_float = 1.1000000000011
+ self.assertEqual(text_format.MessageToString(message),
+ 'payload {\n optional_float: 1.1\n}\n')
+ message.payload.optional_float = 1.00000075e-36
+ self.assertEqual(text_format.MessageToString(message),
+ 'payload {\n optional_float: 1.00000075e-36\n}\n')
+ message.payload.optional_float = 12345678912345e+11
+ self.assertEqual(text_format.MessageToString(message),
+ 'payload {\n optional_float: 1.234568e+24\n}\n')
+
def testMessageToString(self, message_module):
message = message_module.ForeignMessage()
message.c = 123
@@ -1744,6 +1859,24 @@
text_format.Merge(text, message)
self.assertEqual(str(e.exception), '3:11 : Expected "}".')
+ def testProto3Optional(self):
+ msg = test_proto3_optional_pb2.TestProto3Optional()
+ self.assertEqual(text_format.MessageToString(msg), '')
+ msg.optional_int32 = 0
+ msg.optional_float = 0.0
+ msg.optional_string = ''
+ msg.optional_nested_message.bb = 0
+ text = ('optional_int32: 0\n'
+ 'optional_float: 0.0\n'
+ 'optional_string: ""\n'
+ 'optional_nested_message {\n'
+ ' bb: 0\n'
+ '}\n')
+ self.assertEqual(text_format.MessageToString(msg), text)
+ msg2 = test_proto3_optional_pb2.TestProto3Optional()
+ text_format.Parse(text, msg2)
+ self.assertEqual(text_format.MessageToString(msg2), text)
+
class TokenizerTest(unittest.TestCase):
@@ -2194,5 +2327,23 @@
}"""))
+class OptionalColonMessageToStringTest(unittest.TestCase):
+
+ def testForcePrintOptionalColon(self):
+ packed_message = unittest_pb2.OneString()
+ packed_message.data = 'string'
+ message = any_test_pb2.TestAny()
+ message.any_value.Pack(packed_message)
+ output = text_format.MessageToString(
+ message,
+ force_colon=True)
+ expected = ('any_value: {\n'
+ ' [type.googleapis.com/protobuf_unittest.OneString]: {\n'
+ ' data: "string"\n'
+ ' }\n'
+ '}\n')
+ self.assertEqual(expected, output)
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/type_checkers.py b/python/google/protobuf/internal/type_checkers.py
old mode 100755
new mode 100644
index ac1fbbf..bfde1c3
--- a/python/google/protobuf/internal/type_checkers.py
+++ b/python/google/protobuf/internal/type_checkers.py
@@ -38,13 +38,18 @@
TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization
function.
FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their
- coresponding wire types.
+ corresponding wire types.
TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization
function.
"""
__author__ = 'robinson@google.com (Will Robinson)'
+try:
+ import ctypes
+except Exception: # pylint: disable=broad-except
+ ctypes = None
+ import struct
import numbers
import six
@@ -59,6 +64,34 @@
_FieldDescriptor = descriptor.FieldDescriptor
+
+def TruncateToFourByteFloat(original):
+ if ctypes:
+ return ctypes.c_float(original).value
+ else:
+ return struct.unpack('<f', struct.pack('<f', original))[0]
+
+
+def ToShortestFloat(original):
+ """Returns the shortest float that has same value in wire."""
+ # Return the original value if it is not truncated. This may happen
+ # if someone mixes this code with an old protobuf runtime.
+ # TODO(jieluo): Remove it after maybe 2022.
+ if TruncateToFourByteFloat(original) != original:
+ return original
+ # All 4 byte floats have between 6 and 9 significant digits, so we
+ # start with 6 as the lower bound.
+ # It has to be iterative because use '.9g' directly can not get rid
+ # of the noises for most values. For example if set a float_field=0.9
+ # use '.9g' will print 0.899999976.
+ precision = 6
+ rounded = float('{0:.{1}g}'.format(original, precision))
+ while TruncateToFourByteFloat(rounded) != original:
+ precision += 1
+ rounded = float('{0:.{1}g}'.format(original, precision))
+ return rounded
+
+
def SupportsOpenEnums(field_descriptor):
return field_descriptor.containing_type.syntax == "proto3"
@@ -257,9 +290,7 @@
if converted_value < _FLOAT_MIN:
return _NEG_INF
- return converted_value
- # TODO(jieluo): convert to 4 bytes float (c style float) at setters:
- # return struct.unpack('f', struct.pack('f', converted_value))
+ return TruncateToFourByteFloat(converted_value)
def DefaultValue(self):
return 0.0
diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py
old mode 100644
new mode 100755
diff --git a/python/google/protobuf/internal/wire_format.py b/python/google/protobuf/internal/wire_format.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py
index a11874d..5b3f8b4 100644
--- a/python/google/protobuf/json_format.py
+++ b/python/google/protobuf/json_format.py
@@ -60,6 +60,7 @@
import six
+from google.protobuf.internal import type_checkers
from google.protobuf import descriptor
from google.protobuf import symbol_database
@@ -245,8 +246,7 @@
js[name] = [self._FieldToJsonObject(field, k)
for k in value]
elif field.is_extension:
- full_qualifier = field.full_name[:-len(field.name)]
- name = '[%s%s]' % (full_qualifier, name)
+ name = '[%s]' % field.full_name
js[name] = self._FieldToJsonObject(field, value)
else:
js[name] = self._FieldToJsonObject(field, value)
@@ -265,7 +265,7 @@
else:
name = field.json_name
if name in js:
- # Skip the field which has been serailized already.
+ # Skip the field which has been serialized already.
continue
if _IsMapEntry(field):
js[name] = {}
@@ -313,9 +313,12 @@
return _INFINITY
if math.isnan(value):
return _NAN
- if (self.float_format and
- field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT):
- return float(format(value, self.float_format))
+ if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT:
+ if self.float_format:
+ return float(format(value, self.float_format))
+ else:
+ return type_checkers.ToShortestFloat(value)
+
return value
def _AnyMessageToJsonObject(self, message):
diff --git a/python/google/protobuf/message.py b/python/google/protobuf/message.py
old mode 100755
new mode 100644
index 2f13219..224d2fc
--- a/python/google/protobuf/message.py
+++ b/python/google/protobuf/message.py
@@ -36,9 +36,19 @@
__author__ = 'robinson@google.com (Will Robinson)'
-class Error(Exception): pass
-class DecodeError(Error): pass
-class EncodeError(Error): pass
+class Error(Exception):
+ """Base error type for this module."""
+ pass
+
+
+class DecodeError(Error):
+ """Exception raised when deserializing messages."""
+ pass
+
+
+class EncodeError(Error):
+ """Exception raised when serializing messages."""
+ pass
class Message(object):
@@ -48,22 +58,23 @@
Protocol message classes are almost always generated by the protocol
compiler. These generated types subclass Message and implement the methods
shown below.
-
- TODO(robinson): Link to an HTML document here.
-
- TODO(robinson): Document that instances of this class will also
- have an Extensions attribute with __getitem__ and __setitem__.
- Again, not sure how to best convey this.
-
- TODO(robinson): Document that the class must also have a static
- RegisterExtension(extension_field) method.
- Not sure how to best express at this point.
"""
+ # TODO(robinson): Link to an HTML document here.
+
+ # TODO(robinson): Document that instances of this class will also
+ # have an Extensions attribute with __getitem__ and __setitem__.
+ # Again, not sure how to best convey this.
+
+ # TODO(robinson): Document that the class must also have a static
+ # RegisterExtension(extension_field) method.
+ # Not sure how to best express at this point.
+
# TODO(robinson): Document these fields and methods.
__slots__ = []
+ #: The :class:`google.protobuf.descriptor.Descriptor` for this message type.
DESCRIPTOR = None
def __deepcopy__(self, memo=None):
@@ -99,7 +110,7 @@
appended. Singular sub-messages and groups are recursively merged.
Args:
- other_msg: Message to merge into the current message.
+ other_msg (Message): A message to merge into the current message.
"""
raise NotImplementedError
@@ -110,7 +121,7 @@
message using MergeFrom.
Args:
- other_msg: Message to copy into the current one.
+ other_msg (Message): A message to copy into the current one.
"""
if self is other_msg:
return
@@ -127,15 +138,16 @@
This normally happens automatically when you assign a field of a
sub-message, but sometimes you want to make the sub-message
present while keeping it empty. If you find yourself using this,
- you may want to reconsider your design."""
+ you may want to reconsider your design.
+ """
raise NotImplementedError
def IsInitialized(self):
"""Checks if the message is initialized.
Returns:
- The method returns True if the message is initialized (i.e. all of its
- required fields are set).
+ bool: The method returns True if the message is initialized (i.e. all of
+ its required fields are set).
"""
raise NotImplementedError
@@ -148,40 +160,40 @@
def MergeFromString(self, serialized):
"""Merges serialized protocol buffer data into this message.
- When we find a field in |serialized| that is already present
+ When we find a field in `serialized` that is already present
in this message:
- - If it's a "repeated" field, we append to the end of our list.
- - Else, if it's a scalar, we overwrite our field.
- - Else, (it's a nonrepeated composite), we recursively merge
+
+ - If it's a "repeated" field, we append to the end of our list.
+ - Else, if it's a scalar, we overwrite our field.
+ - Else, (it's a nonrepeated composite), we recursively merge
into the existing composite.
- TODO(robinson): Document handling of unknown fields.
-
Args:
- serialized: Any object that allows us to call buffer(serialized)
- to access a string of bytes using the buffer interface.
-
- TODO(robinson): When we switch to a helper, this will return None.
+ serialized (bytes): Any object that allows us to call
+ ``memoryview(serialized)`` to access a string of bytes using the
+ buffer interface.
Returns:
- The number of bytes read from |serialized|.
- For non-group messages, this will always be len(serialized),
+ int: The number of bytes read from `serialized`.
+ For non-group messages, this will always be `len(serialized)`,
but for messages which are actually groups, this will
- generally be less than len(serialized), since we must
- stop when we reach an END_GROUP tag. Note that if
- we *do* stop because of an END_GROUP tag, the number
+ generally be less than `len(serialized)`, since we must
+ stop when we reach an ``END_GROUP`` tag. Note that if
+ we *do* stop because of an ``END_GROUP`` tag, the number
of bytes returned does not include the bytes
- for the END_GROUP tag information.
+ for the ``END_GROUP`` tag information.
Raises:
- message.DecodeError if the input cannot be parsed.
+ DecodeError: if the input cannot be parsed.
"""
+ # TODO(robinson): Document handling of unknown fields.
+ # TODO(robinson): When we switch to a helper, this will return None.
raise NotImplementedError
def ParseFromString(self, serialized):
"""Parse serialized protocol buffer data into this message.
- Like MergeFromString(), except we clear the object first.
+ Like :func:`MergeFromString()`, except we clear the object first.
"""
self.Clear()
return self.MergeFromString(serialized)
@@ -189,18 +201,16 @@
def SerializeToString(self, **kwargs):
"""Serializes the protocol message to a binary string.
- Arguments:
- **kwargs: Keyword arguments to the serialize method, accepts
- the following keyword args:
- deterministic: If true, requests deterministic serialization of the
- protobuf, with predictable ordering of map keys.
+ Keyword Args:
+ deterministic (bool): If true, requests deterministic serialization
+ of the protobuf, with predictable ordering of map keys.
Returns:
A binary string representation of the message if all of the required
fields in the message are set (i.e. the message is initialized).
Raises:
- message.EncodeError if the message isn't initialized.
+ EncodeError: if the message isn't initialized (see :func:`IsInitialized`).
"""
raise NotImplementedError
@@ -210,14 +220,12 @@
This method is similar to SerializeToString but doesn't check if the
message is initialized.
- Arguments:
- **kwargs: Keyword arguments to the serialize method, accepts
- the following keyword args:
- deterministic: If true, requests deterministic serialization of the
- protobuf, with predictable ordering of map keys.
+ Keyword Args:
+ deterministic (bool): If true, requests deterministic serialization
+ of the protobuf, with predictable ordering of map keys.
Returns:
- A string representation of the partial message.
+ bytes: A serialized representation of the partial message.
"""
raise NotImplementedError
@@ -238,48 +246,116 @@
# keywords. So they would become lambda_ or yield_.
# """
def ListFields(self):
- """Returns a list of (FieldDescriptor, value) tuples for all
- 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"""
+ """Returns a list of (FieldDescriptor, value) tuples for present fields.
+
+ 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.
+
+ Returns:
+ list[tuple(FieldDescriptor, value)]: field descriptors and values
+ for all fields in the message which are not empty. The values vary by
+ field type.
+ """
raise NotImplementedError
def HasField(self, field_name):
- """Checks if a certain field is set for the message, or if any field inside
- a oneof group is set. Note that if the field_name is not defined in the
- message descriptor, ValueError will be raised."""
+ """Checks if a certain field is set for the message.
+
+ For a oneof group, checks if any field inside is set. Note that if the
+ field_name is not defined in the message descriptor, :exc:`ValueError` will
+ be raised.
+
+ Args:
+ field_name (str): The name of the field to check for presence.
+
+ Returns:
+ bool: Whether a value has been set for the named field.
+
+ Raises:
+ ValueError: if the `field_name` is not a member of this message.
+ """
raise NotImplementedError
def ClearField(self, field_name):
- """Clears the contents of a given field, or the field set inside a oneof
- group. If the name neither refers to a defined field or oneof group,
- ValueError is raised."""
+ """Clears the contents of a given field.
+
+ Inside a oneof group, clears the field set. If the name neither refers to a
+ defined field or oneof group, :exc:`ValueError` is raised.
+
+ Args:
+ field_name (str): The name of the field to check for presence.
+
+ Raises:
+ ValueError: if the `field_name` is not a member of this message.
+ """
raise NotImplementedError
def WhichOneof(self, oneof_group):
- """Returns the name of the field that is set inside a oneof group, or
- None if no field is set. If no group with the given name exists, ValueError
- will be raised."""
+ """Returns the name of the field that is set inside a oneof group.
+
+ If no field is set, returns None.
+
+ Args:
+ oneof_group (str): the name of the oneof group to check.
+
+ Returns:
+ str or None: The name of the group that is set, or None.
+
+ Raises:
+ ValueError: no group with the given name exists
+ """
raise NotImplementedError
def HasExtension(self, extension_handle):
+ """Checks if a certain extension is present for this message.
+
+ Extensions are retrieved using the :attr:`Extensions` mapping (if present).
+
+ Args:
+ extension_handle: The handle for the extension to check.
+
+ Returns:
+ bool: Whether the extension is present for this message.
+
+ Raises:
+ KeyError: if the extension is repeated. Similar to repeated fields,
+ there is no separate notion of presence: a "not present" repeated
+ extension is an empty list.
+ """
raise NotImplementedError
def ClearExtension(self, extension_handle):
+ """Clears the contents of a given extension.
+
+ Args:
+ extension_handle: The handle for the extension to clear.
+ """
raise NotImplementedError
def UnknownFields(self):
- """Returns the UnknownFieldSet."""
+ """Returns the UnknownFieldSet.
+
+ Returns:
+ UnknownFieldSet: The unknown fields stored in this message.
+ """
raise NotImplementedError
def DiscardUnknownFields(self):
+ """Clears all fields in the :class:`UnknownFieldSet`.
+
+ This operation is recursive for nested message.
+ """
raise NotImplementedError
def ByteSize(self):
"""Returns the serialized size of this message.
+
Recursively calls ByteSize() on all contained messages.
+
+ Returns:
+ int: The number of bytes required to serialize this message.
"""
raise NotImplementedError
diff --git a/python/google/protobuf/message_factory.py b/python/google/protobuf/message_factory.py
index f3ab0a5..24a524a 100644
--- a/python/google/protobuf/message_factory.py
+++ b/python/google/protobuf/message_factory.py
@@ -83,6 +83,8 @@
descriptor_name,
(message.Message,),
{'DESCRIPTOR': descriptor, '__module__': None})
+ # pylint: disable=protected-access
+ result_class._FACTORY = self
# If module not set, it wrongly points to message_factory module.
self._classes[descriptor] = result_class
for field in descriptor.fields:
diff --git a/python/google/protobuf/pyext/descriptor.cc b/python/google/protobuf/pyext/descriptor.cc
index 6b1f427..24b2b46 100644
--- a/python/google/protobuf/pyext/descriptor.cc
+++ b/python/google/protobuf/pyext/descriptor.cc
@@ -481,7 +481,7 @@
}
static PyObject* GetConcreteClass(PyBaseDescriptor* self, void *closure) {
- // Retuns the canonical class for the given descriptor.
+ // Returns the canonical class for the given descriptor.
// This is the class that was registered with the primary descriptor pool
// which contains this descriptor.
// This might not be the one you expect! For example the returned object does
diff --git a/python/google/protobuf/pyext/field.cc b/python/google/protobuf/pyext/field.cc
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/pyext/field.h b/python/google/protobuf/pyext/field.h
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/pyext/map_container.cc b/python/google/protobuf/pyext/map_container.cc
index ed0d31c..86b8720 100644
--- a/python/google/protobuf/pyext/map_container.cc
+++ b/python/google/protobuf/pyext/map_container.cc
@@ -125,9 +125,9 @@
}
}
-static bool PythonToMapKey(PyObject* obj,
- const FieldDescriptor* field_descriptor,
- MapKey* key) {
+static bool PythonToMapKey(MapContainer* self, PyObject* obj, MapKey* key) {
+ const FieldDescriptor* field_descriptor =
+ self->parent_field_descriptor->message_type()->map_key();
switch (field_descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: {
GOOGLE_CHECK_GET_INT32(obj, value, false);
@@ -171,8 +171,9 @@
return true;
}
-static PyObject* MapKeyToPython(const FieldDescriptor* field_descriptor,
- const MapKey& key) {
+static PyObject* MapKeyToPython(MapContainer* self, const MapKey& key) {
+ const FieldDescriptor* field_descriptor =
+ self->parent_field_descriptor->message_type()->map_key();
switch (field_descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return PyInt_FromLong(key.GetInt32Value());
@@ -196,8 +197,9 @@
// This is only used for ScalarMap, so we don't need to handle the
// CPPTYPE_MESSAGE case.
-PyObject* MapValueRefToPython(const FieldDescriptor* field_descriptor,
- const MapValueRef& value) {
+PyObject* MapValueRefToPython(MapContainer* self, const MapValueRef& value) {
+ const FieldDescriptor* field_descriptor =
+ self->parent_field_descriptor->message_type()->map_value();
switch (field_descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return PyInt_FromLong(value.GetInt32Value());
@@ -227,10 +229,11 @@
// This is only used for ScalarMap, so we don't need to handle the
// CPPTYPE_MESSAGE case.
-static bool PythonToMapValueRef(PyObject* obj,
- const FieldDescriptor* field_descriptor,
+static bool PythonToMapValueRef(MapContainer* self, PyObject* obj,
bool allow_unknown_enum_values,
MapValueRef* value_ref) {
+ const FieldDescriptor* field_descriptor =
+ self->parent_field_descriptor->message_type()->map_value();
switch (field_descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: {
GOOGLE_CHECK_GET_INT32(obj, value, false);
@@ -357,7 +360,7 @@
const Reflection* reflection = message->GetReflection();
MapKey map_key;
- if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
+ if (!PythonToMapKey(self, key, &map_key)) {
return NULL;
}
@@ -391,18 +394,6 @@
self->parent_field_descriptor = parent_field_descriptor;
self->version = 0;
- self->key_field_descriptor =
- parent_field_descriptor->message_type()->FindFieldByName("key");
- self->value_field_descriptor =
- parent_field_descriptor->message_type()->FindFieldByName("value");
-
- if (self->key_field_descriptor == NULL ||
- self->value_field_descriptor == NULL) {
- PyErr_Format(PyExc_KeyError,
- "Map entry descriptor did not have key/value fields");
- return NULL;
- }
-
return self;
}
@@ -415,7 +406,7 @@
MapKey map_key;
MapValueRef value;
- if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
+ if (!PythonToMapKey(self, key, &map_key)) {
return NULL;
}
@@ -424,7 +415,7 @@
self->version++;
}
- return MapValueRefToPython(self->value_field_descriptor, value);
+ return MapValueRefToPython(self, value);
}
int MapReflectionFriend::ScalarMapSetItem(PyObject* _self, PyObject* key,
@@ -436,7 +427,7 @@
MapKey map_key;
MapValueRef value;
- if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
+ if (!PythonToMapKey(self, key, &map_key)) {
return -1;
}
@@ -447,10 +438,11 @@
reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
map_key, &value);
- return PythonToMapValueRef(v, self->value_field_descriptor,
- reflection->SupportsUnknownEnumValues(), &value)
- ? 0
- : -1;
+ if (!PythonToMapValueRef(self, v, reflection->SupportsUnknownEnumValues(),
+ &value)) {
+ return -1;
+ }
+ return 0;
} else {
// Delete key from map.
if (reflection->DeleteMapValue(message, self->parent_field_descriptor,
@@ -505,13 +497,11 @@
message, self->parent_field_descriptor);
it != reflection->MapEnd(message, self->parent_field_descriptor);
++it) {
- key.reset(MapKeyToPython(self->key_field_descriptor,
- it.GetKey()));
+ key.reset(MapKeyToPython(self, it.GetKey()));
if (key == NULL) {
return NULL;
}
- value.reset(MapValueRefToPython(self->value_field_descriptor,
- it.GetValueRef()));
+ value.reset(MapValueRefToPython(self, it.GetValueRef()));
if (value == NULL) {
return NULL;
}
@@ -655,22 +645,9 @@
self->parent_field_descriptor = parent_field_descriptor;
self->version = 0;
- self->key_field_descriptor =
- parent_field_descriptor->message_type()->FindFieldByName("key");
- self->value_field_descriptor =
- parent_field_descriptor->message_type()->FindFieldByName("value");
-
Py_INCREF(message_class);
self->message_class = message_class;
- if (self->key_field_descriptor == NULL ||
- self->value_field_descriptor == NULL) {
- Py_DECREF(self);
- PyErr_SetString(PyExc_KeyError,
- "Map entry descriptor did not have key/value fields");
- return NULL;
- }
-
return self;
}
@@ -692,7 +669,7 @@
self->version++;
- if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
+ if (!PythonToMapKey(self, key, &map_key)) {
return -1;
}
@@ -732,7 +709,7 @@
MapKey map_key;
MapValueRef value;
- if (!PythonToMapKey(key, self->key_field_descriptor, &map_key)) {
+ if (!PythonToMapKey(self, key, &map_key)) {
return NULL;
}
@@ -759,8 +736,7 @@
message, self->parent_field_descriptor);
it != reflection->MapEnd(message, self->parent_field_descriptor);
++it) {
- key.reset(MapKeyToPython(self->key_field_descriptor,
- it.GetKey()));
+ key.reset(MapKeyToPython(self, it.GetKey()));
if (key == NULL) {
return NULL;
}
@@ -961,8 +937,7 @@
return NULL;
}
- PyObject* ret = MapKeyToPython(self->container->key_field_descriptor,
- self->iter->GetKey());
+ PyObject* ret = MapKeyToPython(self->container, self->iter->GetKey());
++(*self->iter);
diff --git a/python/google/protobuf/pyext/map_container.h b/python/google/protobuf/pyext/map_container.h
index 2c9b323..a28945d 100644
--- a/python/google/protobuf/pyext/map_container.h
+++ b/python/google/protobuf/pyext/map_container.h
@@ -54,9 +54,6 @@
// Use to get a mutable message when necessary.
Message* GetMutableMessage();
- // Cache some descriptors, used to convert keys and values.
- const FieldDescriptor* key_field_descriptor;
- const FieldDescriptor* value_field_descriptor;
// We bump this whenever we perform a mutation, to invalidate existing
// iterators.
uint64 version;
diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc
index 419f8f5..41ac2ca 100644
--- a/python/google/protobuf/pyext/message.cc
+++ b/python/google/protobuf/pyext/message.cc
@@ -33,11 +33,14 @@
#include <google/protobuf/pyext/message.h>
+#include <structmember.h> // A Python header file.
+
#include <map>
#include <memory>
#include <string>
#include <vector>
-#include <structmember.h> // A Python header file.
+
+#include <google/protobuf/stubs/strutil.h>
#ifndef PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
@@ -456,7 +459,7 @@
Py_ssize_t attr_size;
static const char kSuffix[] = "_FIELD_NUMBER";
if (PyString_AsStringAndSize(name, &attr, &attr_size) >= 0 &&
- strings::EndsWith(StringPiece(attr, attr_size), kSuffix)) {
+ HasSuffixString(StringPiece(attr, attr_size), kSuffix)) {
std::string field_name(attr, attr_size - sizeof(kSuffix) + 1);
LowerString(&field_name);
@@ -1424,28 +1427,12 @@
return false;
}
- if (field_descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
- // HasField() for a oneof *itself* isn't supported.
- if (in_oneof) {
- PyErr_Format(PyExc_ValueError,
- "Can't test oneof field \"%s.%s\" for presence in proto3, "
- "use WhichOneof instead.", message_name.c_str(),
- field_descriptor->containing_oneof()->name().c_str());
- return false;
- }
-
- // ...but HasField() for fields *in* a oneof is supported.
- if (field_descriptor->containing_oneof() != NULL) {
- return true;
- }
-
- if (field_descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
- PyErr_Format(
- PyExc_ValueError,
- "Can't test non-submessage field \"%s.%s\" for presence in proto3.",
- message_name.c_str(), field_descriptor->name().c_str());
- return false;
- }
+ if (!field_descriptor->has_presence()) {
+ PyErr_Format(PyExc_ValueError,
+ "Can't test non-optional, non-submessage field \"%s.%s\" for "
+ "presence in proto3.",
+ message_name.c_str(), field_descriptor->name().c_str());
+ return false;
}
return true;
@@ -2183,19 +2170,21 @@
// If other is not a message, it cannot be equal.
if (!PyObject_TypeCheck(other, CMessage_Type)) {
equals = false;
- }
- const google::protobuf::Message* other_message =
- reinterpret_cast<CMessage*>(other)->message;
- // If messages don't have the same descriptors, they are not equal.
- if (equals &&
- self->message->GetDescriptor() != other_message->GetDescriptor()) {
- equals = false;
- }
- // Check the message contents.
- if (equals && !google::protobuf::util::MessageDifferencer::Equals(
- *self->message,
- *reinterpret_cast<CMessage*>(other)->message)) {
- equals = false;
+ } else {
+ // Otherwise, we have a CMessage whose message we can inspect.
+ const google::protobuf::Message* other_message =
+ reinterpret_cast<CMessage*>(other)->message;
+ // If messages don't have the same descriptors, they are not equal.
+ if (equals &&
+ self->message->GetDescriptor() != other_message->GetDescriptor()) {
+ equals = false;
+ }
+ // Check the message contents.
+ if (equals &&
+ !google::protobuf::util::MessageDifferencer::Equals(
+ *self->message, *reinterpret_cast<CMessage*>(other)->message)) {
+ equals = false;
+ }
}
if (equals ^ (opid == Py_EQ)) {
diff --git a/python/google/protobuf/pyext/message_module.cc b/python/google/protobuf/pyext/message_module.cc
index 4bb35b3..63d60b7 100644
--- a/python/google/protobuf/pyext/message_module.cc
+++ b/python/google/protobuf/pyext/message_module.cc
@@ -107,9 +107,12 @@
}
// Adds the C++ API
- if (PyObject* api =
- PyCapsule_New(new ApiImplementation(),
- google::protobuf::python::PyProtoAPICapsuleName(), NULL)) {
+ if (PyObject* api = PyCapsule_New(
+ new ApiImplementation(), google::protobuf::python::PyProtoAPICapsuleName(),
+ [](PyObject* o) {
+ delete (ApiImplementation*)PyCapsule_GetPointer(
+ o, google::protobuf::python::PyProtoAPICapsuleName());
+ })) {
PyModule_AddObject(m, "proto_API", api);
} else {
return INITFUNC_ERRORVAL;
diff --git a/python/google/protobuf/pyext/unknown_fields.cc b/python/google/protobuf/pyext/unknown_fields.cc
old mode 100755
new mode 100644
index c3679c0..8509213
--- a/python/google/protobuf/pyext/unknown_fields.cc
+++ b/python/google/protobuf/pyext/unknown_fields.cc
@@ -246,7 +246,7 @@
return NULL;
}
- // Assign a default value to suppress may-unintialized warnings (errors
+ // Assign a default value to suppress may-uninitialized warnings (errors
// when built in some places).
WireFormatLite::WireType wire_type = WireFormatLite::WIRETYPE_VARINT;
switch (unknown_field->type()) {
diff --git a/python/google/protobuf/pyext/unknown_fields.h b/python/google/protobuf/pyext/unknown_fields.h
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/reflection.py b/python/google/protobuf/reflection.py
old mode 100755
new mode 100644
diff --git a/python/google/protobuf/service.py b/python/google/protobuf/service.py
old mode 100755
new mode 100644
index 9e00de7..5625246
--- a/python/google/protobuf/service.py
+++ b/python/google/protobuf/service.py
@@ -73,6 +73,7 @@
In the blocking case, RpcException will be raised on error.
Preconditions:
+
* method_descriptor.service == GetDescriptor
* request is of the exact same classes as returned by
GetRequestClass(method).
@@ -82,6 +83,7 @@
RpcChannel which the stub is using.
Postconditions:
+
* "done" will be called when the method is complete. This may be
before CallMethod() returns or it may be at some point in the future.
* If the RPC failed, the response value passed to "done" will be None.
diff --git a/python/google/protobuf/service_reflection.py b/python/google/protobuf/service_reflection.py
old mode 100755
new mode 100644
index 147131f..8590e46
--- a/python/google/protobuf/service_reflection.py
+++ b/python/google/protobuf/service_reflection.py
@@ -55,14 +55,14 @@
The protocol compiler currently uses this metaclass to create protocol service
classes at runtime. Clients can also manually create their own classes at
- runtime, as in this example:
+ runtime, as in this example::
- mydescriptor = ServiceDescriptor(.....)
- class MyProtoService(service.Service):
- __metaclass__ = GeneratedServiceType
- DESCRIPTOR = mydescriptor
- myservice_instance = MyProtoService()
- ...
+ mydescriptor = ServiceDescriptor(.....)
+ class MyProtoService(service.Service):
+ __metaclass__ = GeneratedServiceType
+ DESCRIPTOR = mydescriptor
+ myservice_instance = MyProtoService()
+ # ...
"""
_DESCRIPTOR_KEY = 'DESCRIPTOR'
diff --git a/python/google/protobuf/symbol_database.py b/python/google/protobuf/symbol_database.py
index 4020b15..fdcf8cf 100644
--- a/python/google/protobuf/symbol_database.py
+++ b/python/google/protobuf/symbol_database.py
@@ -34,7 +34,7 @@
and makes it easy to create new instances of a registered type, given only the
type's protocol buffer symbol name.
-Example usage:
+Example usage::
db = symbol_database.SymbolDatabase()
@@ -72,7 +72,8 @@
Calls to GetSymbol() and GetMessages() will return messages registered here.
Args:
- message: a message.Message, to be registered.
+ message: A :class:`google.protobuf.message.Message` subclass (or
+ instance); its descriptor will be registered.
Returns:
The provided message.
@@ -87,7 +88,7 @@
"""Registers the given message descriptor in the local database.
Args:
- message_descriptor: a descriptor.MessageDescriptor.
+ message_descriptor (Descriptor): the message descriptor to add.
"""
if api_implementation.Type() == 'python':
# pylint: disable=protected-access
@@ -97,10 +98,10 @@
"""Registers the given enum descriptor in the local database.
Args:
- enum_descriptor: a descriptor.EnumDescriptor.
+ enum_descriptor (EnumDescriptor): The enum descriptor to register.
Returns:
- The provided descriptor.
+ EnumDescriptor: The provided descriptor.
"""
if api_implementation.Type() == 'python':
# pylint: disable=protected-access
@@ -111,10 +112,8 @@
"""Registers the given service descriptor in the local database.
Args:
- service_descriptor: a descriptor.ServiceDescriptor.
-
- Returns:
- The provided descriptor.
+ service_descriptor (ServiceDescriptor): the service descriptor to
+ register.
"""
if api_implementation.Type() == 'python':
# pylint: disable=protected-access
@@ -124,10 +123,7 @@
"""Registers the given file descriptor in the local database.
Args:
- file_descriptor: a descriptor.FileDescriptor.
-
- Returns:
- The provided descriptor.
+ file_descriptor (FileDescriptor): The file descriptor to register.
"""
if api_implementation.Type() == 'python':
# pylint: disable=protected-access
@@ -140,7 +136,7 @@
may be extended in future to support other symbol types.
Args:
- symbol: A str, a protocol buffer symbol.
+ symbol (str): a protocol buffer symbol.
Returns:
A Python class corresponding to the symbol.
@@ -161,7 +157,7 @@
messages, but does not register any message extensions.
Args:
- files: The file names to extract messages from.
+ files (list[str]): The file names to extract messages from.
Returns:
A dictionary mapping proto names to the message classes.
diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py
old mode 100755
new mode 100644
index a85184e..8387218
--- a/python/google/protobuf/text_format.py
+++ b/python/google/protobuf/text_format.py
@@ -30,7 +30,7 @@
"""Contains routines for printing protocol messages in text format.
-Simple usage example:
+Simple usage example::
# Create a proto object and serialize it to a text proto string.
message = my_proto_pb2.MyMessage(foo='bar')
@@ -120,19 +120,21 @@
return self._writer.getvalue()
-def MessageToString(message,
- as_utf8=False,
- as_one_line=False,
- use_short_repeated_primitives=False,
- pointy_brackets=False,
- use_index_order=False,
- float_format=None,
- double_format=None,
- use_field_number=False,
- descriptor_pool=None,
- indent=0,
- message_formatter=None,
- print_unknown_fields=False):
+def MessageToString(
+ message,
+ as_utf8=False,
+ as_one_line=False,
+ use_short_repeated_primitives=False,
+ pointy_brackets=False,
+ use_index_order=False,
+ float_format=None,
+ double_format=None,
+ use_field_number=False,
+ descriptor_pool=None,
+ indent=0,
+ message_formatter=None,
+ print_unknown_fields=False,
+ force_colon=False):
# type: (...) -> str
"""Convert protobuf message to text format.
@@ -155,31 +157,43 @@
will be printed at the end of the message and their relative order is
determined by the extension number. By default, use the field number
order.
- float_format: If set, use this to specify float field formatting
- (per the "Format Specification Mini-Language"); otherwise, 8 valid digits
- is used (default '.8g'). Also affect double field if double_format is
- not set but float_format is set.
- double_format: If set, use this to specify double field formatting
+ float_format (str): If set, use this to specify float field formatting
+ (per the "Format Specification Mini-Language"); otherwise, shortest float
+ that has same value in wire will be printed. Also affect double field
+ if double_format is not set but float_format is set.
+ double_format (str): If set, use this to specify double field formatting
(per the "Format Specification Mini-Language"); if it is not set but
- float_format is set, use float_format. Otherwise, use str()
+ float_format is set, use float_format. Otherwise, use ``str()``
use_field_number: If True, print field numbers instead of names.
- descriptor_pool: A DescriptorPool used to resolve Any types.
- indent: The initial indent level, in terms of spaces, for pretty print.
- message_formatter: A function(message, indent, as_one_line): unicode|None
- to custom format selected sub-messages (usually based on message type).
- Use to pretty print parts of the protobuf for easier diffing.
+ descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
+ indent (int): The initial indent level, in terms of spaces, for pretty
+ print.
+ message_formatter (function(message, indent, as_one_line) -> unicode|None):
+ Custom formatter for selected sub-messages (usually based on message
+ type). Use to pretty print parts of the protobuf for easier diffing.
print_unknown_fields: If True, unknown fields will be printed.
+ force_colon: If set, a colon will be added after the field name even if the
+ field is a proto message.
Returns:
- A string of the text formatted protocol buffer message.
+ str: A string of the text formatted protocol buffer message.
"""
out = TextWriter(as_utf8)
- printer = _Printer(out, indent, as_utf8, as_one_line,
- use_short_repeated_primitives, pointy_brackets,
- use_index_order, float_format, double_format,
- use_field_number,
- descriptor_pool, message_formatter,
- print_unknown_fields=print_unknown_fields)
+ printer = _Printer(
+ out,
+ indent,
+ as_utf8,
+ as_one_line,
+ use_short_repeated_primitives,
+ pointy_brackets,
+ use_index_order,
+ float_format,
+ double_format,
+ use_field_number,
+ descriptor_pool,
+ message_formatter,
+ print_unknown_fields=print_unknown_fields,
+ force_colon=force_colon)
printer.PrintMessage(message)
result = out.getvalue()
out.close()
@@ -217,7 +231,8 @@
use_field_number=False,
descriptor_pool=None,
message_formatter=None,
- print_unknown_fields=False):
+ print_unknown_fields=False,
+ force_colon=False):
printer = _Printer(
out=out, indent=indent, as_utf8=as_utf8,
as_one_line=as_one_line,
@@ -229,7 +244,8 @@
use_field_number=use_field_number,
descriptor_pool=descriptor_pool,
message_formatter=message_formatter,
- print_unknown_fields=print_unknown_fields)
+ print_unknown_fields=print_unknown_fields,
+ force_colon=force_colon)
printer.PrintMessage(message)
@@ -245,13 +261,15 @@
float_format=None,
double_format=None,
message_formatter=None,
- print_unknown_fields=False):
+ print_unknown_fields=False,
+ force_colon=False):
"""Print a single field name/value pair."""
printer = _Printer(out, indent, as_utf8, as_one_line,
use_short_repeated_primitives, pointy_brackets,
use_index_order, float_format, double_format,
message_formatter=message_formatter,
- print_unknown_fields=print_unknown_fields)
+ print_unknown_fields=print_unknown_fields,
+ force_colon=force_colon)
printer.PrintField(field, value)
@@ -267,13 +285,15 @@
float_format=None,
double_format=None,
message_formatter=None,
- print_unknown_fields=False):
+ print_unknown_fields=False,
+ force_colon=False):
"""Print a single field value (not including name)."""
printer = _Printer(out, indent, as_utf8, as_one_line,
use_short_repeated_primitives, pointy_brackets,
use_index_order, float_format, double_format,
message_formatter=message_formatter,
- print_unknown_fields=print_unknown_fields)
+ print_unknown_fields=print_unknown_fields,
+ force_colon=force_colon)
printer.PrintFieldValue(field, value)
@@ -310,20 +330,22 @@
class _Printer(object):
"""Text format printer for protocol message."""
- def __init__(self,
- out,
- indent=0,
- as_utf8=False,
- as_one_line=False,
- use_short_repeated_primitives=False,
- pointy_brackets=False,
- use_index_order=False,
- float_format=None,
- double_format=None,
- use_field_number=False,
- descriptor_pool=None,
- message_formatter=None,
- print_unknown_fields=False):
+ def __init__(
+ self,
+ out,
+ indent=0,
+ as_utf8=False,
+ as_one_line=False,
+ use_short_repeated_primitives=False,
+ pointy_brackets=False,
+ use_index_order=False,
+ float_format=None,
+ double_format=None,
+ use_field_number=False,
+ descriptor_pool=None,
+ message_formatter=None,
+ print_unknown_fields=False,
+ force_colon=False):
"""Initialize the Printer.
Double values can be formatted compactly with 15 digits of precision
@@ -345,9 +367,9 @@
defined in source code instead of the field number. By default, use the
field number order.
float_format: If set, use this to specify float field formatting
- (per the "Format Specification Mini-Language"); otherwise, 8 valid
- digits is used (default '.8g'). Also affect double field if
- double_format is not set but float_format is set.
+ (per the "Format Specification Mini-Language"); otherwise, shortest
+ float that has same value in wire will be printed. Also affect double
+ field if double_format is not set but float_format is set.
double_format: If set, use this to specify double field formatting
(per the "Format Specification Mini-Language"); if it is not set but
float_format is set, use float_format. Otherwise, str() is used.
@@ -357,6 +379,8 @@
to custom format selected sub-messages (usually based on message type).
Use to pretty print parts of the protobuf for easier diffing.
print_unknown_fields: If True, unknown fields will be printed.
+ force_colon: If set, a colon will be added after the field name even if
+ the field is a proto message.
"""
self.out = out
self.indent = indent
@@ -374,6 +398,7 @@
self.descriptor_pool = descriptor_pool
self.message_formatter = message_formatter
self.print_unknown_fields = print_unknown_fields
+ self.force_colon = force_colon
def _TryPrintAsAnyMessage(self, message):
"""Serializes if message is a google.protobuf.Any field."""
@@ -383,7 +408,8 @@
self.descriptor_pool)
if packed_message:
packed_message.MergeFromString(message.value)
- self.out.write('%s[%s] ' % (self.indent * ' ', message.type_url))
+ colon = ':' if self.force_colon else ''
+ self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon))
self._PrintMessageFieldValue(packed_message)
self.out.write(' ' if self.as_one_line else '\n')
return True
@@ -517,9 +543,11 @@
else:
out.write(field.name)
- if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
+ if (self.force_colon or
+ field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE):
# The colon is optional in this case, but our cross-language golden files
- # don't include it.
+ # don't include it. Here, the colon is only included if force_colon is
+ # set to True
out.write(':')
def PrintField(self, field, value):
@@ -530,6 +558,7 @@
self.out.write(' ' if self.as_one_line else '\n')
def _PrintShortRepeatedPrimitivesValue(self, field, value):
+ """"Prints short repeated primitives value."""
# Note: this is called only when value has at least one element.
self._PrintFieldName(field)
self.out.write(' [')
@@ -538,6 +567,8 @@
self.out.write(', ')
self.PrintFieldValue(field, value[-1])
self.out.write(']')
+ if self.force_colon:
+ self.out.write(':')
self.out.write(' ' if self.as_one_line else '\n')
def _PrintMessageFieldValue(self, value):
@@ -599,7 +630,7 @@
if self.float_format is not None:
out.write('{1:{0}}'.format(self.float_format, value))
else:
- out.write(str(float(format(value, '.8g'))))
+ out.write(str(type_checkers.ToShortestFloat(value)))
elif (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_DOUBLE and
self.double_format is not None):
out.write('{1:{0}}'.format(self.double_format, value))
@@ -620,7 +651,8 @@
If text contains a field already set in message, the value is appended if the
field is repeated. Otherwise, an error is raised.
- Example
+ Example::
+
a = MyProto()
a.repeated_field.append('test')
b = MyProto()
@@ -640,18 +672,18 @@
Caller is responsible for clearing the message as needed.
Args:
- text: Message text representation.
- message: A protocol buffer message to merge into.
+ text (str): Message text representation.
+ message (Message): A protocol buffer message to merge into.
allow_unknown_extension: if True, skip over missing extensions and keep
parsing
allow_field_number: if True, both field number and field name are allowed.
- descriptor_pool: A DescriptorPool used to resolve Any types.
+ descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
allow_unknown_field: if True, skip over unknown field and keep
parsing. Avoid to use this option if possible. It may hide some
errors (e.g. spelling error on field name)
Returns:
- The same message passed as argument.
+ Message: The same message passed as argument.
Raises:
ParseError: On text parsing problems.
@@ -677,18 +709,18 @@
replace those in the message.
Args:
- text: Message text representation.
- message: A protocol buffer message to merge into.
+ text (str): Message text representation.
+ message (Message): A protocol buffer message to merge into.
allow_unknown_extension: if True, skip over missing extensions and keep
parsing
allow_field_number: if True, both field number and field name are allowed.
- descriptor_pool: A DescriptorPool used to resolve Any types.
+ descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
allow_unknown_field: if True, skip over unknown field and keep
parsing. Avoid to use this option if possible. It may hide some
errors (e.g. spelling error on field name)
Returns:
- The same message passed as argument.
+ Message: The same message passed as argument.
Raises:
ParseError: On text parsing problems.
diff --git a/python/mox.py b/python/mox.py
index 43db021..9dd8ac7 100755
--- a/python/mox.py
+++ b/python/mox.py
@@ -705,7 +705,7 @@
"""Move this method into group of calls which may be called multiple times.
A group of repeating calls must be defined together, and must be executed in
- full before the next expected mehtod can be called.
+ full before the next expected method can be called.
Args:
group_name: the name of the unordered group.
diff --git a/python/setup.py b/python/setup.py
index 9aabbf7..7e462b1 100755
--- a/python/setup.py
+++ b/python/setup.py
@@ -110,6 +110,7 @@
generate_proto("google/protobuf/internal/no_package.proto", False)
generate_proto("google/protobuf/internal/packed_field_test.proto", False)
generate_proto("google/protobuf/internal/test_bad_identifiers.proto", False)
+ generate_proto("google/protobuf/internal/test_proto3_optional.proto", False)
generate_proto("google/protobuf/pyext/python.proto", False)
diff --git a/ruby/Rakefile b/ruby/Rakefile
index ad70e31..53241fd 100644
--- a/ruby/Rakefile
+++ b/ruby/Rakefile
@@ -70,13 +70,18 @@
task 'gem:windows' do
require 'rake_compiler_dock'
- RakeCompilerDock.sh "bundle && IN_DOCKER=true rake cross native gem RUBY_CC_VERSION=2.6.0:2.5.0:2.4.0:2.3.0"
+ ['x86-mingw32', 'x64-mingw32', 'x86_64-linux', 'x86-linux'].each do |plat|
+ RakeCompilerDock.sh <<-"EOT", platform: plat
+ bundle && \
+ IN_DOCKER=true rake native:#{plat} pkg/#{spec.full_name}-#{plat}.gem RUBY_CC_VERSION=2.7.0:2.6.0:2.5.0
+ EOT
+ end
end
if RUBY_PLATFORM =~ /darwin/
task 'gem:native' do
system "rake genproto"
- system "rake cross native gem RUBY_CC_VERSION=2.6.0:2.5.1:2.4.0:2.3.0"
+ system "rake cross native gem RUBY_CC_VERSION=2.7.0:2.6.0:2.5.1"
end
else
task 'gem:native' => [:genproto, 'gem:windows']
@@ -119,7 +124,7 @@
end
file "tests/basic_test.rb" => "tests/basic_test.proto" do |file_task|
- sh "../src/protoc -I../src -I. --ruby_out=. tests/basic_test.proto"
+ sh "../src/protoc --experimental_allow_proto3_optional -I../src -I. --ruby_out=. tests/basic_test.proto"
end
file "tests/basic_test_proto2.rb" => "tests/basic_test_proto2.proto" do |file_task|
diff --git a/ruby/compatibility_tests/v3.0.0/README.md b/ruby/compatibility_tests/v3.0.0/README.md
index eb34122..06d981c 100644
--- a/ruby/compatibility_tests/v3.0.0/README.md
+++ b/ruby/compatibility_tests/v3.0.0/README.md
@@ -1,5 +1,5 @@
# Protobuf Ruby Compatibility Tests
-This drectory contains a snapshot of protobuf ruby 3.0.0 unittest code and
+This directory contains a snapshot of protobuf ruby 3.0.0 unittest code and
test scripts used to verifies whether the latest version of protobuf is
still compatible with 3.0.0 generated code.
diff --git a/ruby/compatibility_tests/v3.0.0/test.sh b/ruby/compatibility_tests/v3.0.0/test.sh
index 996dc02..d5a8fd7 100755
--- a/ruby/compatibility_tests/v3.0.0/test.sh
+++ b/ruby/compatibility_tests/v3.0.0/test.sh
@@ -10,7 +10,7 @@
if [ `uname` = "Darwin" ]; then
PROTOC_BINARY_NAME="protoc-3.0.0-osx-x86_64.exe"
fi
-wget http://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0/${PROTOC_BINARY_NAME} -O protoc
+wget https://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0/${PROTOC_BINARY_NAME} -O protoc
chmod +x protoc
# Run tests
diff --git a/ruby/compatibility_tests/v3.0.0/tests/basic.rb b/ruby/compatibility_tests/v3.0.0/tests/basic.rb
old mode 100644
new mode 100755
diff --git a/ruby/compatibility_tests/v3.0.0/tests/generated_code_test.rb b/ruby/compatibility_tests/v3.0.0/tests/generated_code_test.rb
old mode 100644
new mode 100755
diff --git a/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb b/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb
old mode 100644
new mode 100755
index 4ebb731..b4a158f
--- a/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb
+++ b/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb
@@ -20,6 +20,7 @@
:iter_for_each_with_index, :dimensions, :copy_data, :copy_data_simple,
:nitems, :iter_for_reverse_each, :indexes, :append, :prepend]
arr_methods -= [:union, :difference, :filter!]
+ arr_methods -= [:intersection, :deconstruct] # ruby 2.7 methods we can ignore
arr_methods.each do |method_name|
assert m.repeated_string.respond_to?(method_name) == true, "does not respond to #{method_name}"
end
diff --git a/ruby/compatibility_tests/v3.0.0/tests/stress.rb b/ruby/compatibility_tests/v3.0.0/tests/stress.rb
old mode 100644
new mode 100755
diff --git a/ruby/ext/google/protobuf_c/defs.c b/ruby/ext/google/protobuf_c/defs.c
index d092a5b..1a09cc5 100644
--- a/ruby/ext/google/protobuf_c/defs.c
+++ b/ruby/ext/google/protobuf_c/defs.c
@@ -136,7 +136,7 @@
* same number.
*
* Here we do a pass over all enum defaults and rewrite numeric defaults by
- * looking up their labels. This is compilcated by the fact that the enum
+ * looking up their labels. This is complicated by the fact that the enum
* definition can live in either the symtab or the file_proto.
* */
static void rewrite_enum_defaults(
@@ -572,7 +572,7 @@
* call-seq:
* Descriptor.name => name
*
- * Returns the name of this message type as a fully-qualfied string (e.g.,
+ * Returns the name of this message type as a fully-qualified string (e.g.,
* My.Package.MessageType).
*/
VALUE Descriptor_name(VALUE _self) {
@@ -1100,7 +1100,7 @@
* FieldDescriptor.has?(message) => boolean
*
* Returns whether the value is set on the given message. Raises an
- * exception when calling with proto syntax 3.
+ * exception when calling for fields that do not have presence.
*/
VALUE FieldDescriptor_has(VALUE _self, VALUE msg_rb) {
DEFINE_SELF(FieldDescriptor, self, _self);
@@ -1434,6 +1434,7 @@
rb_define_method(klass, "initialize",
MessageBuilderContext_initialize, 2);
rb_define_method(klass, "optional", MessageBuilderContext_optional, -1);
+ rb_define_method(klass, "proto3_optional", MessageBuilderContext_proto3_optional, -1);
rb_define_method(klass, "required", MessageBuilderContext_required, -1);
rb_define_method(klass, "repeated", MessageBuilderContext_repeated, -1);
rb_define_method(klass, "map", MessageBuilderContext_map, -1);
@@ -1469,7 +1470,8 @@
static void msgdef_add_field(VALUE msgbuilder_rb, upb_label_t label, VALUE name,
VALUE type, VALUE number, VALUE type_class,
- VALUE options, int oneof_index) {
+ VALUE options, int oneof_index,
+ bool proto3_optional) {
DEFINE_SELF(MessageBuilderContext, self, msgbuilder_rb);
FileBuilderContext* file_context =
ruby_to_FileBuilderContext(self->file_builder);
@@ -1489,6 +1491,10 @@
google_protobuf_FieldDescriptorProto_set_type(
field_proto, (int)ruby_to_descriptortype(type));
+ if (proto3_optional) {
+ google_protobuf_FieldDescriptorProto_set_proto3_optional(field_proto, true);
+ }
+
if (type_class != Qnil) {
Check_Type(type_class, T_STRING);
@@ -1574,7 +1580,38 @@
}
msgdef_add_field(_self, UPB_LABEL_OPTIONAL, name, type, number, type_class,
- options, -1);
+ options, -1, false);
+
+ return Qnil;
+}
+
+/*
+ * call-seq:
+ * MessageBuilderContext.proto3_optional(name, type, number,
+ * type_class = nil, options = nil)
+ *
+ * Defines a true proto3 optional field (that tracks presence) on this message
+ * type with the given type, tag number, and type class (for message and enum
+ * fields). The type must be a Ruby symbol (as accepted by
+ * FieldDescriptor#type=) and the type_class must be a string, if present (as
+ * accepted by FieldDescriptor#submsg_name=).
+ */
+VALUE MessageBuilderContext_proto3_optional(int argc, VALUE* argv,
+ VALUE _self) {
+ VALUE name, type, number;
+ VALUE type_class, options = Qnil;
+
+ rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
+
+ // Allow passing (name, type, number, options) or
+ // (name, type, number, type_class, options)
+ if (argc == 4 && RB_TYPE_P(type_class, T_HASH)) {
+ options = type_class;
+ type_class = Qnil;
+ }
+
+ msgdef_add_field(_self, UPB_LABEL_OPTIONAL, name, type, number, type_class,
+ options, -1, true);
return Qnil;
}
@@ -1607,7 +1644,7 @@
}
msgdef_add_field(_self, UPB_LABEL_REQUIRED, name, type, number, type_class,
- options, -1);
+ options, -1, false);
return Qnil;
}
@@ -1633,7 +1670,7 @@
type_class = (argc > 3) ? argv[3] : Qnil;
msgdef_add_field(_self, UPB_LABEL_REPEATED, name, type, number, type_class,
- Qnil, -1);
+ Qnil, -1, false);
return Qnil;
}
@@ -1758,6 +1795,56 @@
return Qnil;
}
+void MessageBuilderContext_add_synthetic_oneofs(VALUE _self) {
+ DEFINE_SELF(MessageBuilderContext, self, _self);
+ FileBuilderContext* file_context =
+ ruby_to_FileBuilderContext(self->file_builder);
+ size_t field_count, oneof_count;
+ google_protobuf_FieldDescriptorProto** fields =
+ google_protobuf_DescriptorProto_mutable_field(self->msg_proto, &field_count);
+ const google_protobuf_OneofDescriptorProto*const* oneofs =
+ google_protobuf_DescriptorProto_oneof_decl(self->msg_proto, &oneof_count);
+ VALUE names = rb_hash_new();
+ VALUE underscore = rb_str_new2("_");
+ size_t i;
+
+ // We have to build a set of all names, to ensure that synthetic oneofs are
+ // not creating conflicts.
+ for (i = 0; i < field_count; i++) {
+ upb_strview name = google_protobuf_FieldDescriptorProto_name(fields[i]);
+ rb_hash_aset(names, rb_str_new(name.data, name.size), Qtrue);
+ }
+ for (i = 0; i < oneof_count; i++) {
+ upb_strview name = google_protobuf_OneofDescriptorProto_name(oneofs[i]);
+ rb_hash_aset(names, rb_str_new(name.data, name.size), Qtrue);
+ }
+
+ for (i = 0; i < field_count; i++) {
+ google_protobuf_OneofDescriptorProto* oneof_proto;
+ VALUE oneof_name;
+ upb_strview field_name;
+
+ if (!google_protobuf_FieldDescriptorProto_proto3_optional(fields[i])) {
+ continue;
+ }
+
+ // Prepend '_' until we are no longer conflicting.
+ field_name = google_protobuf_FieldDescriptorProto_name(fields[i]);
+ oneof_name = rb_str_new(field_name.data, field_name.size);
+ while (rb_hash_lookup(names, oneof_name) != Qnil) {
+ oneof_name = rb_str_plus(underscore, oneof_name);
+ }
+
+ rb_hash_aset(names, oneof_name, Qtrue);
+ google_protobuf_FieldDescriptorProto_set_oneof_index(fields[i],
+ oneof_count++);
+ oneof_proto = google_protobuf_DescriptorProto_add_oneof_decl(
+ self->msg_proto, file_context->arena);
+ google_protobuf_OneofDescriptorProto_set_name(
+ oneof_proto, FileBuilderContext_strdup(self->file_builder, oneof_name));
+ }
+}
+
// -----------------------------------------------------------------------------
// OneofBuilderContext.
// -----------------------------------------------------------------------------
@@ -1829,7 +1916,7 @@
rb_scan_args(argc, argv, "32", &name, &type, &number, &type_class, &options);
msgdef_add_field(self->message_builder, UPB_LABEL_OPTIONAL, name, type,
- number, type_class, options, self->oneof_index);
+ number, type_class, options, self->oneof_index, false);
return Qnil;
}
@@ -2033,6 +2120,7 @@
VALUE ctx = rb_class_new_instance(2, args, cMessageBuilderContext);
VALUE block = rb_block_proc();
rb_funcall_with_block(ctx, rb_intern("instance_eval"), 0, NULL, block);
+ MessageBuilderContext_add_synthetic_oneofs(ctx);
return Qnil;
}
diff --git a/ruby/ext/google/protobuf_c/encode_decode.c b/ruby/ext/google/protobuf_c/encode_decode.c
index 713da43..a58a5d2 100644
--- a/ruby/ext/google/protobuf_c/encode_decode.c
+++ b/ruby/ext/google/protobuf_c/encode_decode.c
@@ -30,6 +30,10 @@
#include "protobuf.h"
+VALUE initialize_rb_class_with_no_args(VALUE klass) {
+ return rb_funcall(klass, rb_intern("new"), 0);
+}
+
// This function is equivalent to rb_str_cat(), but unlike the real
// rb_str_cat(), it doesn't leak memory in some versions of Ruby.
// For more information, see:
@@ -44,6 +48,23 @@
return rb_str;
}
+bool is_wrapper(const upb_msgdef* m) {
+ switch (upb_msgdef_wellknowntype(m)) {
+ case UPB_WELLKNOWN_DOUBLEVALUE:
+ case UPB_WELLKNOWN_FLOATVALUE:
+ case UPB_WELLKNOWN_INT64VALUE:
+ case UPB_WELLKNOWN_UINT64VALUE:
+ case UPB_WELLKNOWN_INT32VALUE:
+ case UPB_WELLKNOWN_UINT32VALUE:
+ case UPB_WELLKNOWN_STRINGVALUE:
+ case UPB_WELLKNOWN_BYTESVALUE:
+ case UPB_WELLKNOWN_BOOLVALUE:
+ return true;
+ default:
+ return false;
+ }
+}
+
// The code below also comes from upb's prototype Ruby binding, developed by
// haberman@.
@@ -117,19 +138,26 @@
typedef struct {
size_t ofs;
int32_t hasbit;
+ upb_fieldtype_t wrapped_type; // Only for wrappers.
VALUE subklass;
} submsg_handlerdata_t;
// Creates a handlerdata that contains offset and submessage type information.
static const void *newsubmsghandlerdata(upb_handlers* h,
+ const upb_fielddef *f,
uint32_t ofs,
int32_t hasbit,
VALUE subklass) {
submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
+ const upb_msgdef *subm = upb_fielddef_msgsubdef(f);
hd->ofs = ofs;
hd->hasbit = hasbit;
hd->subklass = subklass;
upb_handlers_addcleanup(h, hd, xfree);
+ if (is_wrapper(subm)) {
+ const upb_fielddef *value_f = upb_msgdef_itof(subm, 1);
+ hd->wrapped_type = upb_fielddef_type(value_f);
+ }
return hd;
}
@@ -271,7 +299,7 @@
const submsg_handlerdata_t *submsgdata = hd;
MessageHeader* submsg;
- VALUE submsg_rb = rb_class_new_instance(0, NULL, submsgdata->subklass);
+ VALUE submsg_rb = initialize_rb_class_with_no_args(submsgdata->subklass);
RepeatedField_push(ary, submsg_rb);
TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
@@ -298,7 +326,7 @@
if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
DEREF(msg, submsgdata->ofs, VALUE) =
- rb_class_new_instance(0, NULL, submsgdata->subklass);
+ initialize_rb_class_with_no_args(submsgdata->subklass);
}
set_hasbit(closure, submsgdata->hasbit);
@@ -310,12 +338,39 @@
}
static void* startwrapper(void* closure, const void* hd) {
- char* msg = closure;
const submsg_handlerdata_t* submsgdata = hd;
+ char* msg = closure;
+ VALUE* field = (VALUE*)(msg + submsgdata->ofs);
set_hasbit(closure, submsgdata->hasbit);
- return msg + submsgdata->ofs;
+ switch (submsgdata->wrapped_type) {
+ case UPB_TYPE_FLOAT:
+ case UPB_TYPE_DOUBLE:
+ *field = DBL2NUM(0);
+ break;
+ case UPB_TYPE_BOOL:
+ *field = Qfalse;
+ break;
+ case UPB_TYPE_STRING:
+ *field = get_frozen_string(NULL, 0, false);
+ break;
+ case UPB_TYPE_BYTES:
+ *field = get_frozen_string(NULL, 0, true);
+ break;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_UINT64:
+ *field = INT2NUM(0);
+ break;
+ case UPB_TYPE_MESSAGE:
+ rb_raise(rb_eRuntimeError,
+ "Internal logic error with well-known types.");
+ }
+
+ return field;
}
// Handler data for startmap/endmap handlers.
@@ -379,10 +434,8 @@
}
static bool endmap_handler(void *closure, const void *hd) {
- MessageHeader* msg = closure;
- const map_handlerdata_t* mapdata = hd;
- VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
- Map_set_frame(map_rb, Qnil);
+ map_parse_frame_t* frame = closure;
+ Map_set_frame(frame->map, Qnil);
return true;
}
@@ -498,7 +551,7 @@
if (oldcase != oneofdata->oneof_case_num ||
DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
DEREF(msg, oneofdata->ofs, VALUE) =
- rb_class_new_instance(0, NULL, oneofdata->subklass);
+ initialize_rb_class_with_no_args(oneofdata->subklass);
}
// Set the oneof case *after* allocating the new class instance -- otherwise,
// if the Ruby GC is invoked as part of a call into the VM, it might invoke
@@ -522,23 +575,6 @@
return msg + oneofdata->ofs;
}
-bool is_wrapper(const upb_msgdef* m) {
- switch (upb_msgdef_wellknowntype(m)) {
- case UPB_WELLKNOWN_DOUBLEVALUE:
- case UPB_WELLKNOWN_FLOATVALUE:
- case UPB_WELLKNOWN_INT64VALUE:
- case UPB_WELLKNOWN_UINT64VALUE:
- case UPB_WELLKNOWN_INT32VALUE:
- case UPB_WELLKNOWN_UINT32VALUE:
- case UPB_WELLKNOWN_STRINGVALUE:
- case UPB_WELLKNOWN_BYTESVALUE:
- case UPB_WELLKNOWN_BOOLVALUE:
- return true;
- default:
- return false;
- }
-}
-
// Set up handlers for a repeated field.
static void add_handlers_for_repeated_field(upb_handlers *h,
const Descriptor* desc,
@@ -579,7 +615,7 @@
case UPB_TYPE_MESSAGE: {
VALUE subklass = field_type_class(desc->layout, f);
upb_handlerattr attr = UPB_HANDLERATTR_INIT;
- attr.handler_data = newsubmsghandlerdata(h, 0, -1, subklass);
+ attr.handler_data = newsubmsghandlerdata(h, f, 0, -1, subklass);
if (is_wrapper(upb_fielddef_msgsubdef(f))) {
upb_handlers_setstartsubmsg(h, f, appendwrapper_handler, &attr);
} else {
@@ -708,7 +744,7 @@
case UPB_TYPE_MESSAGE: {
upb_handlerattr attr = UPB_HANDLERATTR_INIT;
attr.handler_data = newsubmsghandlerdata(
- h, offset, hasbit, field_type_class(desc->layout, f));
+ h, f, offset, hasbit, field_type_class(desc->layout, f));
if (is_wrapper(upb_fielddef_msgsubdef(f))) {
upb_handlers_setstartsubmsg(h, f, startwrapper, &attr);
} else {
@@ -897,7 +933,7 @@
!upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
const upb_fielddef *f = upb_msg_iter_field(&i);
- const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(f);
size_t offset = get_field_offset(desc->layout, f);
if (oneof) {
@@ -1004,7 +1040,7 @@
rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
}
- msg_rb = rb_class_new_instance(0, NULL, msgklass);
+ msg_rb = initialize_rb_class_with_no_args(msgklass);
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
{
@@ -1080,7 +1116,7 @@
// convert, because string handlers pass data directly to message string
// fields.
- msg_rb = rb_class_new_instance(0, NULL, msgklass);
+ msg_rb = initialize_rb_class_with_no_args(msgklass);
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
{
@@ -1162,7 +1198,7 @@
upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
putmsg(submsg, subdesc, subsink, depth + 1, emit_defaults, is_json, true);
- upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
+ upb_sink_endsubmsg(sink, subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
}
static void putary(VALUE ary, const upb_fielddef* f, upb_sink sink, int depth,
@@ -1307,7 +1343,7 @@
entry_sink, emit_defaults, is_json);
upb_sink_endmsg(entry_sink, &status);
- upb_sink_endsubmsg(subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
+ upb_sink_endsubmsg(subsink, entry_sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
}
upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
@@ -1432,6 +1468,7 @@
MessageHeader* msg;
upb_msg_field_iter i;
upb_status status;
+ bool json_wrapper = is_wrapper(desc->msgdef) && is_json;
if (is_json &&
upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
@@ -1469,7 +1506,7 @@
!upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
upb_fielddef *f = upb_msg_iter_field(&i);
- const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(f);
bool is_matching_oneof = false;
uint32_t offset =
desc->layout->fields[upb_fielddef_index(f)].offset +
@@ -1508,7 +1545,7 @@
is_default = RSTRING_LEN(str) == 0;
}
- if (is_matching_oneof || emit_defaults || !is_default) {
+ if (is_matching_oneof || emit_defaults || !is_default || json_wrapper) {
putstr(str, f, sink);
}
} else if (upb_fielddef_issubmsg(f)) {
@@ -1528,7 +1565,7 @@
} else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) { \
is_default = default_value == value; \
} \
- if (is_matching_oneof || emit_defaults || !is_default) { \
+ if (is_matching_oneof || emit_defaults || !is_default || json_wrapper) { \
upb_sink_put##upbtype(sink, sel, value); \
} \
} break;
@@ -1677,7 +1714,7 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
upb_fielddef *f = upb_msg_iter_field(&it);
- const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(f);
uint32_t offset =
desc->layout->fields[upb_fielddef_index(f)].offset +
sizeof(MessageHeader);
diff --git a/ruby/ext/google/protobuf_c/extconf.rb b/ruby/ext/google/protobuf_c/extconf.rb
old mode 100644
new mode 100755
diff --git a/ruby/ext/google/protobuf_c/map.c b/ruby/ext/google/protobuf_c/map.c
index 719706b..00d23a7 100644
--- a/ruby/ext/google/protobuf_c/map.c
+++ b/ruby/ext/google/protobuf_c/map.c
@@ -100,11 +100,11 @@
return key;
}
-static VALUE table_key_to_ruby(Map* self, const char* buf, size_t length) {
+static VALUE table_key_to_ruby(Map* self, upb_strview key) {
switch (self->key_type) {
case UPB_TYPE_BYTES:
case UPB_TYPE_STRING: {
- VALUE ret = rb_str_new(buf, length);
+ VALUE ret = rb_str_new(key.data, key.size);
rb_enc_associate(ret,
(self->key_type == UPB_TYPE_BYTES) ?
kRubyString8bitEncoding : kRubyStringUtf8Encoding);
@@ -116,7 +116,7 @@
case UPB_TYPE_INT64:
case UPB_TYPE_UINT32:
case UPB_TYPE_UINT64:
- return native_slot_get(self->key_type, Qnil, buf);
+ return native_slot_get(self->key_type, Qnil, key.data);
default:
assert(false);
@@ -289,9 +289,7 @@
for (upb_strtable_begin(&it, &self->table);
!upb_strtable_done(&it);
upb_strtable_next(&it)) {
-
- VALUE key = table_key_to_ruby(
- self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
+ VALUE key = table_key_to_ruby(self, upb_strtable_iter_key(&it));
upb_value v = upb_strtable_iter_value(&it);
void* mem = value_memory(&v);
@@ -319,9 +317,7 @@
for (upb_strtable_begin(&it, &self->table);
!upb_strtable_done(&it);
upb_strtable_next(&it)) {
-
- VALUE key = table_key_to_ruby(
- self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
+ VALUE key = table_key_to_ruby(self, upb_strtable_iter_key(&it));
rb_ary_push(ret, key);
}
@@ -526,17 +522,14 @@
for (upb_strtable_begin(&it, &self->table);
!upb_strtable_done(&it);
upb_strtable_next(&it)) {
-
+ upb_strview k = upb_strtable_iter_key(&it);
upb_value v = upb_strtable_iter_value(&it);
void* mem = value_memory(&v);
upb_value dup;
void* dup_mem = value_memory(&dup);
native_slot_dup(self->value_type, dup_mem, mem);
- if (!upb_strtable_insert2(&new_self->table,
- upb_strtable_iter_key(&it),
- upb_strtable_iter_keylength(&it),
- dup)) {
+ if (!upb_strtable_insert2(&new_self->table, k.data, k.size, dup)) {
rb_raise(rb_eRuntimeError, "Error inserting value into new table");
}
}
@@ -554,7 +547,7 @@
for (upb_strtable_begin(&it, &self->table);
!upb_strtable_done(&it);
upb_strtable_next(&it)) {
-
+ upb_strview k = upb_strtable_iter_key(&it);
upb_value v = upb_strtable_iter_value(&it);
void* mem = value_memory(&v);
upb_value dup;
@@ -562,10 +555,7 @@
native_slot_deep_copy(self->value_type, self->value_type_class, dup_mem,
mem);
- if (!upb_strtable_insert2(&new_self->table,
- upb_strtable_iter_key(&it),
- upb_strtable_iter_keylength(&it),
- dup)) {
+ if (!upb_strtable_insert2(&new_self->table, k.data, k.size, dup)) {
rb_raise(rb_eRuntimeError, "Error inserting value into new table");
}
}
@@ -618,16 +608,13 @@
for (upb_strtable_begin(&it, &self->table);
!upb_strtable_done(&it);
upb_strtable_next(&it)) {
-
+ upb_strview k = upb_strtable_iter_key(&it);
upb_value v = upb_strtable_iter_value(&it);
void* mem = value_memory(&v);
upb_value other_v;
void* other_mem = value_memory(&other_v);
- if (!upb_strtable_lookup2(&other->table,
- upb_strtable_iter_key(&it),
- upb_strtable_iter_keylength(&it),
- &other_v)) {
+ if (!upb_strtable_lookup2(&other->table, k.data, k.size, &other_v)) {
// Not present in other map.
return Qfalse;
}
@@ -655,11 +642,9 @@
VALUE hash_sym = rb_intern("hash");
upb_strtable_iter it;
- for (upb_strtable_begin(&it, &self->table);
- !upb_strtable_done(&it);
+ for (upb_strtable_begin(&it, &self->table); !upb_strtable_done(&it);
upb_strtable_next(&it)) {
- VALUE key = table_key_to_ruby(
- self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
+ VALUE key = table_key_to_ruby(self, upb_strtable_iter_key(&it));
upb_value v = upb_strtable_iter_value(&it);
void* mem = value_memory(&v);
@@ -687,8 +672,7 @@
for (upb_strtable_begin(&it, &self->table);
!upb_strtable_done(&it);
upb_strtable_next(&it)) {
- VALUE key = table_key_to_ruby(
- self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
+ VALUE key = table_key_to_ruby(self, upb_strtable_iter_key(&it));
upb_value v = upb_strtable_iter_value(&it);
void* mem = value_memory(&v);
VALUE value = native_slot_get(self->value_type,
@@ -720,11 +704,9 @@
VALUE inspect_sym = rb_intern("inspect");
upb_strtable_iter it;
- for (upb_strtable_begin(&it, &self->table);
- !upb_strtable_done(&it);
+ for (upb_strtable_begin(&it, &self->table); !upb_strtable_done(&it);
upb_strtable_next(&it)) {
- VALUE key = table_key_to_ruby(
- self, upb_strtable_iter_key(&it), upb_strtable_iter_keylength(&it));
+ VALUE key = table_key_to_ruby(self, upb_strtable_iter_key(&it));
upb_value v = upb_strtable_iter_value(&it);
void* mem = value_memory(&v);
@@ -785,20 +767,15 @@
for (upb_strtable_begin(&it, &other->table);
!upb_strtable_done(&it);
upb_strtable_next(&it)) {
+ upb_strview k = upb_strtable_iter_key(&it);
// Replace any existing value by issuing a 'remove' operation first.
upb_value v;
upb_value oldv;
- upb_strtable_remove2(&self->table,
- upb_strtable_iter_key(&it),
- upb_strtable_iter_keylength(&it),
- &oldv);
+ upb_strtable_remove2(&self->table, k.data, k.size, &oldv);
v = upb_strtable_iter_value(&it);
- upb_strtable_insert2(&self->table,
- upb_strtable_iter_key(&it),
- upb_strtable_iter_keylength(&it),
- v);
+ upb_strtable_insert2(&self->table, k.data, k.size, v);
}
} else {
rb_raise(rb_eArgError, "Unknown type merging into Map");
@@ -822,10 +799,7 @@
}
VALUE Map_iter_key(Map_iter* iter) {
- return table_key_to_ruby(
- iter->self,
- upb_strtable_iter_key(&iter->it),
- upb_strtable_iter_keylength(&iter->it));
+ return table_key_to_ruby(iter->self, upb_strtable_iter_key(&iter->it));
}
VALUE Map_iter_value(Map_iter* iter) {
diff --git a/ruby/ext/google/protobuf_c/message.c b/ruby/ext/google/protobuf_c/message.c
index f57501c..0050506 100644
--- a/ruby/ext/google/protobuf_c/message.c
+++ b/ruby/ext/google/protobuf_c/message.c
@@ -242,9 +242,14 @@
// Method calls like 'has_foo?' are not allowed if field "foo" does not have
// a hasbit (e.g. repeated fields or non-message type fields for proto3
// syntax).
- if (accessor_type == METHOD_PRESENCE && test_f != NULL &&
- !upb_fielddef_haspresence(test_f)) {
- return METHOD_UNKNOWN;
+ if (accessor_type == METHOD_PRESENCE && test_f != NULL) {
+ if (!upb_fielddef_haspresence(test_f)) return METHOD_UNKNOWN;
+
+ // TODO(haberman): remove this case, allow for proto3 oneofs.
+ if (upb_fielddef_realcontainingoneof(test_f) &&
+ upb_filedef_syntax(upb_fielddef_file(test_f)) == UPB_SYNTAX_PROTO3) {
+ return METHOD_UNKNOWN;
+ }
}
*o = test_o;
@@ -605,11 +610,17 @@
*/
VALUE Message_to_h(VALUE _self) {
MessageHeader* self;
- VALUE hash;
+ VALUE hash = rb_hash_new();
upb_msg_field_iter it;
+ bool is_proto2;
TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
- hash = rb_hash_new();
+ // We currently have a few behaviors that are specific to proto2.
+ // This is unfortunate, we should key behaviors off field attributes (like
+ // whether a field has presence), not proto2 vs. proto3. We should see if we
+ // can change this without breaking users.
+ is_proto2 =
+ upb_msgdef_syntax(self->descriptor->msgdef) == UPB_SYNTAX_PROTO2;
for (upb_msg_field_begin(&it, self->descriptor->msgdef);
!upb_msg_field_done(&it);
@@ -618,10 +629,9 @@
VALUE msg_value;
VALUE msg_key;
- // For proto2, do not include fields which are not set.
- if (upb_msgdef_syntax(self->descriptor->msgdef) == UPB_SYNTAX_PROTO2 &&
- field_contains_hasbit(self->descriptor->layout, field) &&
- !layout_has(self->descriptor->layout, Message_data(self), field)) {
+ // Do not include fields that are not present (oneof or optional fields).
+ if (is_proto2 && upb_fielddef_haspresence(field) &&
+ !layout_has(self->descriptor->layout, Message_data(self), field)) {
continue;
}
@@ -631,8 +641,7 @@
msg_value = Map_to_h(msg_value);
} else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
msg_value = RepeatedField_to_ary(msg_value);
- if (upb_msgdef_syntax(self->descriptor->msgdef) == UPB_SYNTAX_PROTO2 &&
- RARRAY_LEN(msg_value) == 0) {
+ if (is_proto2 && RARRAY_LEN(msg_value) == 0) {
continue;
}
diff --git a/ruby/ext/google/protobuf_c/protobuf.h b/ruby/ext/google/protobuf_c/protobuf.h
index ae9895c..0ec78fc 100644
--- a/ruby/ext/google/protobuf_c/protobuf.h
+++ b/ruby/ext/google/protobuf_c/protobuf.h
@@ -285,6 +285,7 @@
VALUE _file_builder,
VALUE name);
VALUE MessageBuilderContext_optional(int argc, VALUE* argv, VALUE _self);
+VALUE MessageBuilderContext_proto3_optional(int argc, VALUE* argv, VALUE _self);
VALUE MessageBuilderContext_required(int argc, VALUE* argv, VALUE _self);
VALUE MessageBuilderContext_repeated(int argc, VALUE* argv, VALUE _self);
VALUE MessageBuilderContext_map(int argc, VALUE* argv, VALUE _self);
diff --git a/ruby/ext/google/protobuf_c/storage.c b/ruby/ext/google/protobuf_c/storage.c
index 739c0a7..a3805c9 100644
--- a/ruby/ext/google/protobuf_c/storage.c
+++ b/ruby/ext/google/protobuf_c/storage.c
@@ -496,11 +496,14 @@
const upb_msgdef *msgdef = desc->msgdef;
MessageLayout* layout = ALLOC(MessageLayout);
int nfields = upb_msgdef_numfields(msgdef);
- int noneofs = upb_msgdef_numoneofs(msgdef);
+ int noneofs = upb_msgdef_numrealoneofs(msgdef);
upb_msg_field_iter it;
upb_msg_oneof_iter oit;
size_t off = 0;
size_t hasbit = 0;
+ int i;
+
+ (void)i;
layout->empty_template = NULL;
layout->desc = desc;
@@ -513,11 +516,22 @@
layout->oneofs = ALLOC_N(MessageOneof, noneofs);
}
+#ifndef NDEBUG
+ for (i = 0; i < nfields; i++) {
+ layout->fields[i].offset = -1;
+ }
+
+ for (i = 0; i < noneofs; i++) {
+ layout->oneofs[i].offset = -1;
+ }
+#endif
+
for (upb_msg_field_begin(&it, msgdef);
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
- if (upb_fielddef_haspresence(field)) {
+ if (upb_fielddef_haspresence(field) &&
+ !upb_fielddef_realcontainingoneof(field)) {
layout->fields[upb_fielddef_index(field)].hasbit = hasbit++;
} else {
layout->fields[upb_fielddef_index(field)].hasbit =
@@ -540,7 +554,7 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
- if (upb_fielddef_containingoneof(field) || !upb_fielddef_isseq(field) ||
+ if (upb_fielddef_realcontainingoneof(field) || !upb_fielddef_isseq(field) ||
upb_fielddef_ismap(field)) {
continue;
}
@@ -555,7 +569,7 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
- if (upb_fielddef_containingoneof(field) || !upb_fielddef_isseq(field) ||
+ if (upb_fielddef_realcontainingoneof(field) || !upb_fielddef_isseq(field) ||
!upb_fielddef_ismap(field)) {
continue;
}
@@ -572,7 +586,7 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
- if (upb_fielddef_containingoneof(field) || !is_value_field(field) ||
+ if (upb_fielddef_realcontainingoneof(field) || !is_value_field(field) ||
upb_fielddef_isseq(field)) {
continue;
}
@@ -589,7 +603,7 @@
const upb_fielddef* field = upb_msg_iter_field(&it);
size_t field_size;
- if (upb_fielddef_containingoneof(field) || is_value_field(field)) {
+ if (upb_fielddef_realcontainingoneof(field) || is_value_field(field)) {
continue;
}
@@ -624,6 +638,10 @@
// Always allocate NATIVE_SLOT_MAX_SIZE bytes, but share the slot between
// all fields.
size_t field_size = NATIVE_SLOT_MAX_SIZE;
+
+ if (upb_oneofdef_issynthetic(oneof)) continue;
+ assert(upb_oneofdef_index(oneof) < noneofs);
+
// Align the offset.
off = align_up_to(off, field_size);
// Assign all fields in the oneof this same offset.
@@ -643,6 +661,8 @@
upb_msg_oneof_next(&oit)) {
const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
size_t field_size = sizeof(uint32_t);
+ if (upb_oneofdef_issynthetic(oneof)) continue;
+ assert(upb_oneofdef_index(oneof) < noneofs);
// Align the offset.
off = (off + field_size - 1) & ~(field_size - 1);
layout->oneofs[upb_oneofdef_index(oneof)].case_offset = off;
@@ -652,6 +672,16 @@
layout->size = off;
layout->msgdef = msgdef;
+#ifndef NDEBUG
+ for (i = 0; i < nfields; i++) {
+ assert(layout->fields[i].offset != -1);
+ }
+
+ for (i = 0; i < noneofs; i++) {
+ assert(layout->oneofs[i].offset != -1);
+ }
+#endif
+
// Create the empty message template.
layout->empty_template = ALLOC_N(char, layout->size);
memset(layout->empty_template, 0, layout->size);
@@ -725,10 +755,7 @@
const void* storage,
const upb_fielddef* field) {
size_t hasbit = layout->fields[upb_fielddef_index(field)].hasbit;
- if (hasbit == MESSAGE_FIELD_NO_HASBIT) {
- return false;
- }
-
+ assert(field_contains_hasbit(layout, field));
return DEREF_OFFSET(
(uint8_t*)storage, hasbit / 8, char) & (1 << (hasbit % 8));
}
@@ -736,15 +763,21 @@
VALUE layout_has(MessageLayout* layout,
const void* storage,
const upb_fielddef* field) {
- assert(field_contains_hasbit(layout, field));
- return slot_is_hasbit_set(layout, storage, field) ? Qtrue : Qfalse;
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(field);
+ assert(upb_fielddef_haspresence(field));
+ if (oneof) {
+ uint32_t oneof_case = slot_read_oneof_case(layout, storage, oneof);
+ return oneof_case == upb_fielddef_number(field) ? Qtrue : Qfalse;
+ } else {
+ return slot_is_hasbit_set(layout, storage, field) ? Qtrue : Qfalse;
+ }
}
void layout_clear(MessageLayout* layout,
const void* storage,
const upb_fielddef* field) {
void* memory = slot_memory(layout, storage, field);
- const upb_oneofdef* oneof = upb_fielddef_containingoneof(field);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(field);
if (field_contains_hasbit(layout, field)) {
slot_clear_hasbit(layout, storage, field);
@@ -837,7 +870,7 @@
const void* storage,
const upb_fielddef* field) {
void* memory = slot_memory(layout, storage, field);
- const upb_oneofdef* oneof = upb_fielddef_containingoneof(field);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(field);
bool field_set;
if (field_contains_hasbit(layout, field)) {
field_set = slot_is_hasbit_set(layout, storage, field);
@@ -910,7 +943,7 @@
const upb_fielddef* field,
VALUE val) {
void* memory = slot_memory(layout, storage, field);
- const upb_oneofdef* oneof = upb_fielddef_containingoneof(field);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(field);
if (oneof) {
uint32_t* oneof_case = slot_oneof_case(layout, storage, oneof);
@@ -953,7 +986,16 @@
if (layout->fields[upb_fielddef_index(field)].hasbit !=
MESSAGE_FIELD_NO_HASBIT) {
- slot_set_hasbit(layout, storage, field);
+ if (val == Qnil) {
+ // No other field type has a hasbit and allows nil assignment.
+ if (upb_fielddef_type(field) != UPB_TYPE_MESSAGE) {
+ fprintf(stderr, "field: %s\n", upb_fielddef_fullname(field));
+ }
+ assert(upb_fielddef_type(field) == UPB_TYPE_MESSAGE);
+ slot_clear_hasbit(layout, storage, field);
+ } else {
+ slot_set_hasbit(layout, storage, field);
+ }
}
}
@@ -972,7 +1014,7 @@
void layout_mark(MessageLayout* layout, void* storage) {
VALUE* values = (VALUE*)CHARPTR_AT(storage, layout->value_offset);
- int noneofs = upb_msgdef_numoneofs(layout->msgdef);
+ int noneofs = upb_msgdef_numrealoneofs(layout->msgdef);
int i;
for (i = 0; i < layout->value_count; i++) {
@@ -994,7 +1036,7 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
- const upb_oneofdef* oneof = upb_fielddef_containingoneof(field);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(field);
void* to_memory = slot_memory(layout, to, field);
void* from_memory = slot_memory(layout, from, field);
@@ -1028,7 +1070,7 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
- const upb_oneofdef* oneof = upb_fielddef_containingoneof(field);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(field);
void* to_memory = slot_memory(layout, to, field);
void* from_memory = slot_memory(layout, from, field);
@@ -1068,7 +1110,7 @@
!upb_msg_field_done(&it);
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
- const upb_oneofdef* oneof = upb_fielddef_containingoneof(field);
+ const upb_oneofdef* oneof = upb_fielddef_realcontainingoneof(field);
void* msg1_memory = slot_memory(layout, msg1, field);
void* msg2_memory = slot_memory(layout, msg2, field);
@@ -1095,9 +1137,16 @@
return Qfalse;
}
} else {
- if (slot_is_hasbit_set(layout, msg1, field) !=
- slot_is_hasbit_set(layout, msg2, field) ||
- !native_slot_eq(upb_fielddef_type(field),
+ if (field_contains_hasbit(layout, field) &&
+ slot_is_hasbit_set(layout, msg1, field) !=
+ slot_is_hasbit_set(layout, msg2, field)) {
+ // TODO(haberman): I don't think we should actually care about hasbits
+ // here: an unset default should be able to equal a set default. But we
+ // can address this later (will also have to make sure defaults are
+ // being properly set when hasbit is clear).
+ return Qfalse;
+ }
+ if (!native_slot_eq(upb_fielddef_type(field),
field_type_class(layout, field), msg1_memory,
msg2_memory)) {
return Qfalse;
diff --git a/ruby/ext/google/protobuf_c/upb.c b/ruby/ext/google/protobuf_c/upb.c
index bc87ea6..61e86fc 100644
--- a/ruby/ext/google/protobuf_c/upb.c
+++ b/ruby/ext/google/protobuf_c/upb.c
@@ -22,9 +22,7 @@
*
* This file is private and must not be included by users!
*/
-#ifndef UINTPTR_MAX
-#error must include stdint.h first
-#endif
+#include <stdint.h>
#if UINTPTR_MAX == 0xffffffff
#define UPB_SIZE(size32, size64) size32
@@ -32,17 +30,21 @@
#define UPB_SIZE(size32, size64) size64
#endif
-#define UPB_FIELD_AT(msg, fieldtype, offset) \
- *(fieldtype*)((const char*)(msg) + offset)
+/* If we always read/write as a consistent type to each address, this shouldn't
+ * violate aliasing.
+ */
+#define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
#define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
- UPB_FIELD_AT(msg, int, case_offset) == case_val \
- ? UPB_FIELD_AT(msg, fieldtype, offset) \
+ *UPB_PTR_AT(msg, case_offset, int) == case_val \
+ ? *UPB_PTR_AT(msg, offset, fieldtype) \
: default
#define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
- UPB_FIELD_AT(msg, int, case_offset) = case_val; \
- UPB_FIELD_AT(msg, fieldtype, offset) = value;
+ *UPB_PTR_AT(msg, case_offset, int) = case_val; \
+ *UPB_PTR_AT(msg, offset, fieldtype) = value;
+
+#define UPB_MAPTYPE_STRING 0
/* UPB_INLINE: inline if possible, emit standalone code if required. */
#ifdef __cplusplus
@@ -116,7 +118,7 @@
#ifdef __cplusplus
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
(defined(_MSC_VER) && _MSC_VER >= 1900)
-// C++11 is present
+/* C++11 is present */
#else
#error upb requires C++11 for C++ support
#endif
@@ -127,6 +129,18 @@
#define UPB_UNUSED(var) (void)var
+/* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
+ */
+#ifdef NDEBUG
+#ifdef __GNUC__
+#define UPB_ASSUME(expr) if (!(expr)) __builtin_unreachable()
+#else
+#define UPB_ASSUME(expr) do {} if (false && (expr))
+#endif
+#else
+#define UPB_ASSUME(expr) assert(expr)
+#endif
+
/* UPB_ASSERT(): in release mode, we use the expression without letting it be
* evaluated. This prevents "unused variable" warnings. */
#ifdef NDEBUG
@@ -153,606 +167,572 @@
#define UPB_INFINITY (1.0 / 0.0)
#endif
+#include <setjmp.h>
#include <string.h>
+
/* Maps descriptor type -> upb field type. */
-const uint8_t upb_desctype_to_fieldtype[] = {
- UPB_WIRE_TYPE_END_GROUP, /* ENDGROUP */
- UPB_TYPE_DOUBLE, /* DOUBLE */
- UPB_TYPE_FLOAT, /* FLOAT */
- UPB_TYPE_INT64, /* INT64 */
- UPB_TYPE_UINT64, /* UINT64 */
- UPB_TYPE_INT32, /* INT32 */
- UPB_TYPE_UINT64, /* FIXED64 */
- UPB_TYPE_UINT32, /* FIXED32 */
- UPB_TYPE_BOOL, /* BOOL */
- UPB_TYPE_STRING, /* STRING */
- UPB_TYPE_MESSAGE, /* GROUP */
- UPB_TYPE_MESSAGE, /* MESSAGE */
- UPB_TYPE_BYTES, /* BYTES */
- UPB_TYPE_UINT32, /* UINT32 */
- UPB_TYPE_ENUM, /* ENUM */
- UPB_TYPE_INT32, /* SFIXED32 */
- UPB_TYPE_INT64, /* SFIXED64 */
- UPB_TYPE_INT32, /* SINT32 */
- UPB_TYPE_INT64, /* SINT64 */
+static const uint8_t desctype_to_fieldtype[] = {
+ -1, /* invalid descriptor type */
+ UPB_TYPE_DOUBLE, /* DOUBLE */
+ UPB_TYPE_FLOAT, /* FLOAT */
+ UPB_TYPE_INT64, /* INT64 */
+ UPB_TYPE_UINT64, /* UINT64 */
+ UPB_TYPE_INT32, /* INT32 */
+ UPB_TYPE_UINT64, /* FIXED64 */
+ UPB_TYPE_UINT32, /* FIXED32 */
+ UPB_TYPE_BOOL, /* BOOL */
+ UPB_TYPE_STRING, /* STRING */
+ UPB_TYPE_MESSAGE, /* GROUP */
+ UPB_TYPE_MESSAGE, /* MESSAGE */
+ UPB_TYPE_BYTES, /* BYTES */
+ UPB_TYPE_UINT32, /* UINT32 */
+ UPB_TYPE_ENUM, /* ENUM */
+ UPB_TYPE_INT32, /* SFIXED32 */
+ UPB_TYPE_INT64, /* SFIXED64 */
+ UPB_TYPE_INT32, /* SINT32 */
+ UPB_TYPE_INT64, /* SINT64 */
+};
+
+/* Maps descriptor type -> upb map size. */
+static const uint8_t desctype_to_mapsize[] = {
+ -1, /* invalid descriptor type */
+ 8, /* DOUBLE */
+ 4, /* FLOAT */
+ 8, /* INT64 */
+ 8, /* UINT64 */
+ 4, /* INT32 */
+ 8, /* FIXED64 */
+ 4, /* FIXED32 */
+ 1, /* BOOL */
+ UPB_MAPTYPE_STRING, /* STRING */
+ sizeof(void *), /* GROUP */
+ sizeof(void *), /* MESSAGE */
+ UPB_MAPTYPE_STRING, /* BYTES */
+ 4, /* UINT32 */
+ 4, /* ENUM */
+ 4, /* SFIXED32 */
+ 8, /* SFIXED64 */
+ 4, /* SINT32 */
+ 8, /* SINT64 */
+};
+
+static const unsigned fixed32_ok = (1 << UPB_DTYPE_FLOAT) |
+ (1 << UPB_DTYPE_FIXED32) |
+ (1 << UPB_DTYPE_SFIXED32);
+
+static const unsigned fixed64_ok = (1 << UPB_DTYPE_DOUBLE) |
+ (1 << UPB_DTYPE_FIXED64) |
+ (1 << UPB_DTYPE_SFIXED64);
+
+/* Op: an action to be performed for a wire-type/field-type combination. */
+#define OP_SCALAR_LG2(n) (n)
+#define OP_FIXPCK_LG2(n) (n + 4)
+#define OP_VARPCK_LG2(n) (n + 8)
+#define OP_STRING 4
+#define OP_SUBMSG 5
+
+static const int8_t varint_ops[19] = {
+ -1, /* field not found */
+ -1, /* DOUBLE */
+ -1, /* FLOAT */
+ OP_SCALAR_LG2(3), /* INT64 */
+ OP_SCALAR_LG2(3), /* UINT64 */
+ OP_SCALAR_LG2(2), /* INT32 */
+ -1, /* FIXED64 */
+ -1, /* FIXED32 */
+ OP_SCALAR_LG2(0), /* BOOL */
+ -1, /* STRING */
+ -1, /* GROUP */
+ -1, /* MESSAGE */
+ -1, /* BYTES */
+ OP_SCALAR_LG2(2), /* UINT32 */
+ OP_SCALAR_LG2(2), /* ENUM */
+ -1, /* SFIXED32 */
+ -1, /* SFIXED64 */
+ OP_SCALAR_LG2(2), /* SINT32 */
+ OP_SCALAR_LG2(3), /* SINT64 */
+};
+
+static const int8_t delim_ops[37] = {
+ /* For non-repeated field type. */
+ -1, /* field not found */
+ -1, /* DOUBLE */
+ -1, /* FLOAT */
+ -1, /* INT64 */
+ -1, /* UINT64 */
+ -1, /* INT32 */
+ -1, /* FIXED64 */
+ -1, /* FIXED32 */
+ -1, /* BOOL */
+ OP_STRING, /* STRING */
+ -1, /* GROUP */
+ OP_SUBMSG, /* MESSAGE */
+ OP_STRING, /* BYTES */
+ -1, /* UINT32 */
+ -1, /* ENUM */
+ -1, /* SFIXED32 */
+ -1, /* SFIXED64 */
+ -1, /* SINT32 */
+ -1, /* SINT64 */
+ /* For repeated field type. */
+ OP_FIXPCK_LG2(3), /* REPEATED DOUBLE */
+ OP_FIXPCK_LG2(2), /* REPEATED FLOAT */
+ OP_VARPCK_LG2(3), /* REPEATED INT64 */
+ OP_VARPCK_LG2(3), /* REPEATED UINT64 */
+ OP_VARPCK_LG2(2), /* REPEATED INT32 */
+ OP_FIXPCK_LG2(3), /* REPEATED FIXED64 */
+ OP_FIXPCK_LG2(2), /* REPEATED FIXED32 */
+ OP_VARPCK_LG2(0), /* REPEATED BOOL */
+ OP_STRING, /* REPEATED STRING */
+ OP_SUBMSG, /* REPEATED GROUP */
+ OP_SUBMSG, /* REPEATED MESSAGE */
+ OP_STRING, /* REPEATED BYTES */
+ OP_VARPCK_LG2(2), /* REPEATED UINT32 */
+ OP_VARPCK_LG2(2), /* REPEATED ENUM */
+ OP_FIXPCK_LG2(2), /* REPEATED SFIXED32 */
+ OP_FIXPCK_LG2(3), /* REPEATED SFIXED64 */
+ OP_VARPCK_LG2(2), /* REPEATED SINT32 */
+ OP_VARPCK_LG2(3), /* REPEATED SINT64 */
};
/* Data pertaining to the parse. */
typedef struct {
- const char *ptr; /* Current parsing position. */
- const char *field_start; /* Start of this field. */
- const char *limit; /* End of delimited region or end of buffer. */
+ const char *limit; /* End of delimited region or end of buffer. */
upb_arena *arena;
int depth;
- uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
+ uint32_t end_group; /* Set to field number of END_GROUP tag, if any. */
+ jmp_buf err;
} upb_decstate;
-/* Data passed by value to each parsing function. */
-typedef struct {
- char *msg;
- const upb_msglayout *layout;
- upb_decstate *state;
-} upb_decframe;
+typedef union {
+ bool bool_val;
+ int32_t int32_val;
+ int64_t int64_val;
+ uint32_t uint32_val;
+ uint64_t uint64_val;
+ upb_strview str_val;
+} wireval;
-#define CHK(x) if (!(x)) { return 0; }
+static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
+ const upb_msglayout *layout);
-static bool upb_skip_unknowngroup(upb_decstate *d, int field_number);
-static bool upb_decode_message(upb_decstate *d, char *msg,
- const upb_msglayout *l);
+UPB_NORETURN static void decode_err(upb_decstate *d) { longjmp(d->err, 1); }
-static bool upb_decode_varint(const char **ptr, const char *limit,
- uint64_t *val) {
+static bool decode_reserve(upb_decstate *d, upb_array *arr, int elem) {
+ bool need_realloc = arr->size - arr->len < elem;
+ if (need_realloc && !_upb_array_realloc(arr, arr->len + elem, d->arena)) {
+ decode_err(d);
+ }
+ return need_realloc;
+}
+
+UPB_NOINLINE
+static const char *decode_longvarint64(upb_decstate *d, const char *ptr,
+ const char *limit, uint64_t *val) {
uint8_t byte;
int bitpos = 0;
- const char *p = *ptr;
- *val = 0;
+ uint64_t out = 0;
do {
- CHK(bitpos < 70 && p < limit);
- byte = *p;
- *val |= (uint64_t)(byte & 0x7F) << bitpos;
- p++;
+ if (bitpos >= 70 || ptr == limit) decode_err(d);
+ byte = *ptr;
+ out |= (uint64_t)(byte & 0x7F) << bitpos;
+ ptr++;
bitpos += 7;
} while (byte & 0x80);
- *ptr = p;
- return true;
+ *val = out;
+ return ptr;
}
-static bool upb_decode_varint32(const char **ptr, const char *limit,
- uint32_t *val) {
+UPB_FORCEINLINE
+static const char *decode_varint64(upb_decstate *d, const char *ptr,
+ const char *limit, uint64_t *val) {
+ if (UPB_LIKELY(ptr < limit && (*ptr & 0x80) == 0)) {
+ *val = (uint8_t)*ptr;
+ return ptr + 1;
+ } else {
+ return decode_longvarint64(d, ptr, limit, val);
+ }
+}
+
+static const char *decode_varint32(upb_decstate *d, const char *ptr,
+ const char *limit, uint32_t *val) {
uint64_t u64;
- CHK(upb_decode_varint(ptr, limit, &u64) && u64 <= UINT32_MAX);
+ ptr = decode_varint64(d, ptr, limit, &u64);
+ if (u64 > UINT32_MAX) decode_err(d);
*val = (uint32_t)u64;
- return true;
+ return ptr;
}
-static bool upb_decode_64bit(const char **ptr, const char *limit,
- uint64_t *val) {
- CHK(limit - *ptr >= 8);
- memcpy(val, *ptr, 8);
- *ptr += 8;
- return true;
-}
-
-static bool upb_decode_32bit(const char **ptr, const char *limit,
- uint32_t *val) {
- CHK(limit - *ptr >= 4);
- memcpy(val, *ptr, 4);
- *ptr += 4;
- return true;
-}
-
-static int32_t upb_zzdecode_32(uint32_t n) {
- return (n >> 1) ^ -(int32_t)(n & 1);
-}
-
-static int64_t upb_zzdecode_64(uint64_t n) {
- return (n >> 1) ^ -(int64_t)(n & 1);
-}
-
-static bool upb_decode_string(const char **ptr, const char *limit,
- int *outlen) {
- uint32_t len;
-
- CHK(upb_decode_varint32(ptr, limit, &len) &&
- len < INT32_MAX &&
- limit - *ptr >= (int32_t)len);
-
- *outlen = len;
- return true;
-}
-
-static void upb_set32(void *msg, size_t ofs, uint32_t val) {
- memcpy((char*)msg + ofs, &val, sizeof(val));
-}
-
-static bool upb_append_unknown(upb_decstate *d, upb_decframe *frame) {
- upb_msg_addunknown(frame->msg, d->field_start, d->ptr - d->field_start,
- d->arena);
- return true;
-}
-
-
-static bool upb_skip_unknownfielddata(upb_decstate *d, uint32_t tag,
- uint32_t group_fieldnum) {
- switch (tag & 7) {
- case UPB_WIRE_TYPE_VARINT: {
- uint64_t val;
- return upb_decode_varint(&d->ptr, d->limit, &val);
- }
- case UPB_WIRE_TYPE_32BIT: {
- uint32_t val;
- return upb_decode_32bit(&d->ptr, d->limit, &val);
- }
- case UPB_WIRE_TYPE_64BIT: {
- uint64_t val;
- return upb_decode_64bit(&d->ptr, d->limit, &val);
- }
- case UPB_WIRE_TYPE_DELIMITED: {
- int len;
- CHK(upb_decode_string(&d->ptr, d->limit, &len));
- d->ptr += len;
- return true;
- }
- case UPB_WIRE_TYPE_START_GROUP:
- return upb_skip_unknowngroup(d, tag >> 3);
- case UPB_WIRE_TYPE_END_GROUP:
- return (tag >> 3) == group_fieldnum;
- }
- return false;
-}
-
-static bool upb_skip_unknowngroup(upb_decstate *d, int field_number) {
- while (d->ptr < d->limit && d->end_group == 0) {
- uint32_t tag = 0;
- CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
- CHK(upb_skip_unknownfielddata(d, tag, field_number));
- }
-
- CHK(d->end_group == field_number);
- d->end_group = 0;
- return true;
-}
-
-static bool upb_array_grow(upb_array *arr, size_t elements, size_t elem_size,
- upb_arena *arena) {
- size_t needed = arr->len + elements;
- size_t new_size = UPB_MAX(arr->size, 8);
- size_t new_bytes;
- size_t old_bytes;
- void *new_data;
- upb_alloc *alloc = upb_arena_alloc(arena);
-
- while (new_size < needed) {
- new_size *= 2;
- }
-
- old_bytes = arr->len * elem_size;
- new_bytes = new_size * elem_size;
- new_data = upb_realloc(alloc, arr->data, old_bytes, new_bytes);
- CHK(new_data);
-
- arr->data = new_data;
- arr->size = new_size;
- return true;
-}
-
-static void *upb_array_reserve(upb_array *arr, size_t elements,
- size_t elem_size, upb_arena *arena) {
- if (arr->size - arr->len < elements) {
- CHK(upb_array_grow(arr, elements, elem_size, arena));
- }
- return (char*)arr->data + (arr->len * elem_size);
-}
-
-bool upb_array_add(upb_array *arr, size_t elements, size_t elem_size,
- const void *data, upb_arena *arena) {
- void *dest = upb_array_reserve(arr, elements, elem_size, arena);
-
- CHK(dest);
- arr->len += elements;
- memcpy(dest, data, elements * elem_size);
-
- return true;
-}
-
-static upb_array *upb_getarr(upb_decframe *frame,
- const upb_msglayout_field *field) {
- UPB_ASSERT(field->label == UPB_LABEL_REPEATED);
- return *(upb_array**)&frame->msg[field->offset];
-}
-
-static upb_array *upb_getorcreatearr(upb_decframe *frame,
- const upb_msglayout_field *field) {
- upb_array *arr = upb_getarr(frame, field);
-
- if (!arr) {
- arr = upb_array_new(frame->state->arena);
- CHK(arr);
- *(upb_array**)&frame->msg[field->offset] = arr;
- }
-
- return arr;
-}
-
-static upb_msg *upb_getorcreatemsg(upb_decframe *frame,
- const upb_msglayout_field *field,
- const upb_msglayout **subm) {
- upb_msg **submsg = (void*)(frame->msg + field->offset);
- *subm = frame->layout->submsgs[field->submsg_index];
-
- UPB_ASSERT(field->label != UPB_LABEL_REPEATED);
-
- if (!*submsg) {
- *submsg = upb_msg_new(*subm, frame->state->arena);
- CHK(*submsg);
- }
-
- return *submsg;
-}
-
-static upb_msg *upb_addmsg(upb_decframe *frame,
- const upb_msglayout_field *field,
- const upb_msglayout **subm) {
- upb_msg *submsg;
- upb_array *arr = upb_getorcreatearr(frame, field);
-
- *subm = frame->layout->submsgs[field->submsg_index];
- submsg = upb_msg_new(*subm, frame->state->arena);
- CHK(submsg);
- upb_array_add(arr, 1, sizeof(submsg), &submsg, frame->state->arena);
-
- return submsg;
-}
-
-static void upb_sethasbit(upb_decframe *frame,
- const upb_msglayout_field *field) {
- int32_t hasbit = field->presence;
- UPB_ASSERT(field->presence > 0);
- frame->msg[hasbit / 8] |= (1 << (hasbit % 8));
-}
-
-static void upb_setoneofcase(upb_decframe *frame,
- const upb_msglayout_field *field) {
- UPB_ASSERT(field->presence < 0);
- upb_set32(frame->msg, ~field->presence, field->number);
-}
-
-static bool upb_decode_addval(upb_decframe *frame,
- const upb_msglayout_field *field, void *val,
- size_t size) {
- char *field_mem = frame->msg + field->offset;
- upb_array *arr;
-
- if (field->label == UPB_LABEL_REPEATED) {
- arr = upb_getorcreatearr(frame, field);
- CHK(arr);
- field_mem = upb_array_reserve(arr, 1, size, frame->state->arena);
- CHK(field_mem);
- }
-
- memcpy(field_mem, val, size);
- return true;
-}
-
-static void upb_decode_setpresent(upb_decframe *frame,
- const upb_msglayout_field *field) {
- if (field->label == UPB_LABEL_REPEATED) {
- upb_array *arr = upb_getarr(frame, field);
- UPB_ASSERT(arr->len < arr->size);
- arr->len++;
- } else if (field->presence < 0) {
- upb_setoneofcase(frame, field);
- } else if (field->presence > 0) {
- upb_sethasbit(frame, field);
- }
-}
-
-static bool upb_decode_msgfield(upb_decstate *d, upb_msg *msg,
- const upb_msglayout *layout, int limit) {
- const char* saved_limit = d->limit;
- d->limit = d->ptr + limit;
- CHK(--d->depth >= 0);
- upb_decode_message(d, msg, layout);
- d->depth++;
- d->limit = saved_limit;
- CHK(d->end_group == 0);
- return true;
-}
-
-static bool upb_decode_groupfield(upb_decstate *d, upb_msg *msg,
- const upb_msglayout *layout,
- int field_number) {
- CHK(--d->depth >= 0);
- upb_decode_message(d, msg, layout);
- d->depth++;
- CHK(d->end_group == field_number);
- d->end_group = 0;
- return true;
-}
-
-static bool upb_decode_varintfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- uint64_t val;
- CHK(upb_decode_varint(&d->ptr, d->limit, &val));
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_INT64:
- case UPB_DESCRIPTOR_TYPE_UINT64:
- CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
+static void decode_munge(int type, wireval *val) {
+ switch (type) {
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ val->bool_val = val->uint64_val != 0;
break;
- case UPB_DESCRIPTOR_TYPE_INT32:
- case UPB_DESCRIPTOR_TYPE_UINT32:
- case UPB_DESCRIPTOR_TYPE_ENUM: {
- uint32_t val32 = (uint32_t)val;
- CHK(upb_decode_addval(frame, field, &val32, sizeof(val32)));
- break;
- }
- case UPB_DESCRIPTOR_TYPE_BOOL: {
- bool valbool = val != 0;
- CHK(upb_decode_addval(frame, field, &valbool, sizeof(valbool)));
- break;
- }
case UPB_DESCRIPTOR_TYPE_SINT32: {
- int32_t decoded = upb_zzdecode_32((uint32_t)val);
- CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
+ uint32_t n = val->uint32_val;
+ val->int32_val = (n >> 1) ^ -(int32_t)(n & 1);
break;
}
case UPB_DESCRIPTOR_TYPE_SINT64: {
- int64_t decoded = upb_zzdecode_64(val);
- CHK(upb_decode_addval(frame, field, &decoded, sizeof(decoded)));
+ uint64_t n = val->uint64_val;
+ val->int64_val = (n >> 1) ^ -(int64_t)(n & 1);
break;
}
- default:
- return upb_append_unknown(d, frame);
- }
-
- upb_decode_setpresent(frame, field);
- return true;
-}
-
-static bool upb_decode_64bitfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- uint64_t val;
- CHK(upb_decode_64bit(&d->ptr, d->limit, &val));
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_DOUBLE:
- case UPB_DESCRIPTOR_TYPE_FIXED64:
- case UPB_DESCRIPTOR_TYPE_SFIXED64:
- CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
- break;
- default:
- return upb_append_unknown(d, frame);
- }
-
- upb_decode_setpresent(frame, field);
- return true;
-}
-
-static bool upb_decode_32bitfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- uint32_t val;
- CHK(upb_decode_32bit(&d->ptr, d->limit, &val));
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_FLOAT:
- case UPB_DESCRIPTOR_TYPE_FIXED32:
- case UPB_DESCRIPTOR_TYPE_SFIXED32:
- CHK(upb_decode_addval(frame, field, &val, sizeof(val)));
- break;
- default:
- return upb_append_unknown(d, frame);
- }
-
- upb_decode_setpresent(frame, field);
- return true;
-}
-
-static bool upb_decode_fixedpacked(upb_decstate *d, upb_array *arr,
- uint32_t len, int elem_size) {
- size_t elements = len / elem_size;
-
- CHK((size_t)(elements * elem_size) == len);
- CHK(upb_array_add(arr, elements, elem_size, d->ptr, d->arena));
- d->ptr += len;
-
- return true;
-}
-
-static upb_strview upb_decode_strfield(upb_decstate *d, uint32_t len) {
- upb_strview ret;
- ret.data = d->ptr;
- ret.size = len;
- d->ptr += len;
- return ret;
-}
-
-static bool upb_decode_toarray(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field, int len) {
- upb_array *arr = upb_getorcreatearr(frame, field);
- CHK(arr);
-
-#define VARINT_CASE(ctype, decode) \
- VARINT_CASE_EX(ctype, decode, decode)
-
-#define VARINT_CASE_EX(ctype, decode, dtype) \
- { \
- const char *ptr = d->ptr; \
- const char *limit = ptr + len; \
- while (ptr < limit) { \
- uint64_t val; \
- ctype decoded; \
- CHK(upb_decode_varint(&ptr, limit, &val)); \
- decoded = (decode)((dtype)val); \
- CHK(upb_array_add(arr, 1, sizeof(decoded), &decoded, d->arena)); \
- } \
- d->ptr = ptr; \
- return true; \
- }
-
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_STRING:
- case UPB_DESCRIPTOR_TYPE_BYTES: {
- upb_strview str = upb_decode_strfield(d, len);
- return upb_array_add(arr, 1, sizeof(str), &str, d->arena);
- }
- case UPB_DESCRIPTOR_TYPE_FLOAT:
- case UPB_DESCRIPTOR_TYPE_FIXED32:
- case UPB_DESCRIPTOR_TYPE_SFIXED32:
- return upb_decode_fixedpacked(d, arr, len, sizeof(int32_t));
- case UPB_DESCRIPTOR_TYPE_DOUBLE:
- case UPB_DESCRIPTOR_TYPE_FIXED64:
- case UPB_DESCRIPTOR_TYPE_SFIXED64:
- return upb_decode_fixedpacked(d, arr, len, sizeof(int64_t));
- case UPB_DESCRIPTOR_TYPE_INT32:
- case UPB_DESCRIPTOR_TYPE_UINT32:
- case UPB_DESCRIPTOR_TYPE_ENUM:
- VARINT_CASE(uint32_t, uint32_t);
- case UPB_DESCRIPTOR_TYPE_INT64:
- case UPB_DESCRIPTOR_TYPE_UINT64:
- VARINT_CASE(uint64_t, uint64_t);
- case UPB_DESCRIPTOR_TYPE_BOOL:
- VARINT_CASE(bool, bool);
- case UPB_DESCRIPTOR_TYPE_SINT32:
- VARINT_CASE_EX(int32_t, upb_zzdecode_32, uint32_t);
- case UPB_DESCRIPTOR_TYPE_SINT64:
- VARINT_CASE_EX(int64_t, upb_zzdecode_64, uint64_t);
- case UPB_DESCRIPTOR_TYPE_MESSAGE: {
- const upb_msglayout *subm;
- upb_msg *submsg = upb_addmsg(frame, field, &subm);
- CHK(submsg);
- return upb_decode_msgfield(d, submsg, subm, len);
- }
- case UPB_DESCRIPTOR_TYPE_GROUP:
- return upb_append_unknown(d, frame);
- }
-#undef VARINT_CASE
- UPB_UNREACHABLE();
-}
-
-static bool upb_decode_delimitedfield(upb_decstate *d, upb_decframe *frame,
- const upb_msglayout_field *field) {
- int len;
-
- CHK(upb_decode_string(&d->ptr, d->limit, &len));
-
- if (field->label == UPB_LABEL_REPEATED) {
- return upb_decode_toarray(d, frame, field, len);
- } else {
- switch (field->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_STRING:
- case UPB_DESCRIPTOR_TYPE_BYTES: {
- upb_strview str = upb_decode_strfield(d, len);
- CHK(upb_decode_addval(frame, field, &str, sizeof(str)));
- break;
- }
- case UPB_DESCRIPTOR_TYPE_MESSAGE: {
- const upb_msglayout *subm;
- upb_msg *submsg = upb_getorcreatemsg(frame, field, &subm);
- CHK(submsg);
- CHK(upb_decode_msgfield(d, submsg, subm, len));
- break;
- }
- default:
- /* TODO(haberman): should we accept the last element of a packed? */
- d->ptr += len;
- return upb_append_unknown(d, frame);
- }
- upb_decode_setpresent(frame, field);
- return true;
}
}
static const upb_msglayout_field *upb_find_field(const upb_msglayout *l,
uint32_t field_number) {
+ static upb_msglayout_field none = {0};
+
/* Lots of optimization opportunities here. */
int i;
+ if (l == NULL) return &none;
for (i = 0; i < l->field_count; i++) {
if (l->fields[i].number == field_number) {
return &l->fields[i];
}
}
- return NULL; /* Unknown field. */
+ return &none; /* Unknown field. */
}
-static bool upb_decode_field(upb_decstate *d, upb_decframe *frame) {
- uint32_t tag;
- const upb_msglayout_field *field;
- int field_number;
+static upb_msg *decode_newsubmsg(upb_decstate *d, const upb_msglayout *layout,
+ const upb_msglayout_field *field) {
+ const upb_msglayout *subl = layout->submsgs[field->submsg_index];
+ return _upb_msg_new(subl, d->arena);
+}
- d->field_start = d->ptr;
- CHK(upb_decode_varint32(&d->ptr, d->limit, &tag));
- field_number = tag >> 3;
- field = upb_find_field(frame->layout, field_number);
+static void decode_tosubmsg(upb_decstate *d, upb_msg *submsg,
+ const upb_msglayout *layout,
+ const upb_msglayout_field *field, upb_strview val) {
+ const upb_msglayout *subl = layout->submsgs[field->submsg_index];
+ const char *saved_limit = d->limit;
+ if (--d->depth < 0) decode_err(d);
+ d->limit = val.data + val.size;
+ decode_msg(d, val.data, submsg, subl);
+ d->limit = saved_limit;
+ if (d->end_group != 0) decode_err(d);
+ d->depth++;
+}
- if (field) {
- switch (tag & 7) {
- case UPB_WIRE_TYPE_VARINT:
- return upb_decode_varintfield(d, frame, field);
- case UPB_WIRE_TYPE_32BIT:
- return upb_decode_32bitfield(d, frame, field);
- case UPB_WIRE_TYPE_64BIT:
- return upb_decode_64bitfield(d, frame, field);
- case UPB_WIRE_TYPE_DELIMITED:
- return upb_decode_delimitedfield(d, frame, field);
- case UPB_WIRE_TYPE_START_GROUP: {
- const upb_msglayout *layout;
- upb_msg *group;
+static const char *decode_group(upb_decstate *d, const char *ptr,
+ upb_msg *submsg, const upb_msglayout *subl,
+ uint32_t number) {
+ if (--d->depth < 0) decode_err(d);
+ ptr = decode_msg(d, ptr, submsg, subl);
+ if (d->end_group != number) decode_err(d);
+ d->end_group = 0;
+ d->depth++;
+ return ptr;
+}
- if (field->label == UPB_LABEL_REPEATED) {
- group = upb_addmsg(frame, field, &layout);
- } else {
- group = upb_getorcreatemsg(frame, field, &layout);
- }
+static const char *decode_togroup(upb_decstate *d, const char *ptr,
+ upb_msg *submsg, const upb_msglayout *layout,
+ const upb_msglayout_field *field) {
+ const upb_msglayout *subl = layout->submsgs[field->submsg_index];
+ return decode_group(d, ptr, submsg, subl, field->number);
+}
- return upb_decode_groupfield(d, group, layout, field_number);
+static const char *decode_toarray(upb_decstate *d, const char *ptr,
+ upb_msg *msg, const upb_msglayout *layout,
+ const upb_msglayout_field *field, wireval val,
+ int op) {
+ upb_array **arrp = UPB_PTR_AT(msg, field->offset, void);
+ upb_array *arr = *arrp;
+ void *mem;
+
+ if (!arr) {
+ upb_fieldtype_t type = desctype_to_fieldtype[field->descriptortype];
+ arr = _upb_array_new(d->arena, type);
+ if (!arr) decode_err(d);
+ *arrp = arr;
+ }
+
+ decode_reserve(d, arr, 1);
+
+ switch (op) {
+ case OP_SCALAR_LG2(0):
+ case OP_SCALAR_LG2(2):
+ case OP_SCALAR_LG2(3):
+ /* Append scalar value. */
+ mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << op, void);
+ arr->len++;
+ memcpy(mem, &val, 1 << op);
+ return ptr;
+ case OP_STRING:
+ /* Append string. */
+ mem =
+ UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(upb_strview), void);
+ arr->len++;
+ memcpy(mem, &val, sizeof(upb_strview));
+ return ptr;
+ case OP_SUBMSG: {
+ /* Append submessage / group. */
+ upb_msg *submsg = decode_newsubmsg(d, layout, field);
+ *UPB_PTR_AT(_upb_array_ptr(arr), arr->len * sizeof(void *), upb_msg *) =
+ submsg;
+ arr->len++;
+ if (UPB_UNLIKELY(field->descriptortype == UPB_DTYPE_GROUP)) {
+ ptr = decode_togroup(d, ptr, submsg, layout, field);
+ } else {
+ decode_tosubmsg(d, submsg, layout, field, val.str_val);
}
+ return ptr;
+ }
+ case OP_FIXPCK_LG2(2):
+ case OP_FIXPCK_LG2(3): {
+ /* Fixed packed. */
+ int lg2 = op - OP_FIXPCK_LG2(0);
+ int mask = (1 << lg2) - 1;
+ int count = val.str_val.size >> lg2;
+ if ((val.str_val.size & mask) != 0) {
+ decode_err(d); /* Length isn't a round multiple of elem size. */
+ }
+ decode_reserve(d, arr, count);
+ mem = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
+ arr->len += count;
+ memcpy(mem, val.str_val.data, count << op);
+ return ptr;
+ }
+ case OP_VARPCK_LG2(0):
+ case OP_VARPCK_LG2(2):
+ case OP_VARPCK_LG2(3): {
+ /* Varint packed. */
+ int lg2 = op - OP_VARPCK_LG2(0);
+ int scale = 1 << lg2;
+ const char *ptr = val.str_val.data;
+ const char *end = ptr + val.str_val.size;
+ char *out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
+ while (ptr < end) {
+ wireval elem;
+ ptr = decode_varint64(d, ptr, end, &elem.uint64_val);
+ decode_munge(field->descriptortype, &elem);
+ if (decode_reserve(d, arr, 1)) {
+ out = UPB_PTR_AT(_upb_array_ptr(arr), arr->len << lg2, void);
+ }
+ arr->len++;
+ memcpy(out, &elem, scale);
+ out += scale;
+ }
+ if (ptr != end) decode_err(d);
+ return ptr;
+ }
+ default:
+ UPB_UNREACHABLE();
+ }
+}
+
+static void decode_tomap(upb_decstate *d, upb_msg *msg,
+ const upb_msglayout *layout,
+ const upb_msglayout_field *field, wireval val) {
+ upb_map **map_p = UPB_PTR_AT(msg, field->offset, upb_map *);
+ upb_map *map = *map_p;
+ upb_map_entry ent;
+ const upb_msglayout *entry = layout->submsgs[field->submsg_index];
+
+ if (!map) {
+ /* Lazily create map. */
+ const upb_msglayout *entry = layout->submsgs[field->submsg_index];
+ const upb_msglayout_field *key_field = &entry->fields[0];
+ const upb_msglayout_field *val_field = &entry->fields[1];
+ char key_size = desctype_to_mapsize[key_field->descriptortype];
+ char val_size = desctype_to_mapsize[val_field->descriptortype];
+ UPB_ASSERT(key_field->offset == 0);
+ UPB_ASSERT(val_field->offset == sizeof(upb_strview));
+ map = _upb_map_new(d->arena, key_size, val_size);
+ *map_p = map;
+ }
+
+ /* Parse map entry. */
+ memset(&ent, 0, sizeof(ent));
+
+ if (entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
+ entry->fields[1].descriptortype == UPB_DESCRIPTOR_TYPE_GROUP) {
+ /* Create proactively to handle the case where it doesn't appear. */
+ ent.v.val.val = (uint64_t)_upb_msg_new(entry->submsgs[0], d->arena);
+ }
+
+ decode_tosubmsg(d, &ent.k, layout, field, val.str_val);
+
+ /* Insert into map. */
+ _upb_map_set(map, &ent.k, map->key_size, &ent.v, map->val_size, d->arena);
+}
+
+static const char *decode_tomsg(upb_decstate *d, const char *ptr, upb_msg *msg,
+ const upb_msglayout *layout,
+ const upb_msglayout_field *field, wireval val,
+ int op) {
+ void *mem = UPB_PTR_AT(msg, field->offset, void);
+ int type = field->descriptortype;
+
+ /* Set presence if necessary. */
+ if (field->presence < 0) {
+ /* Oneof case */
+ *UPB_PTR_AT(msg, -field->presence, int32_t) = field->number;
+ } else if (field->presence > 0) {
+ /* Hasbit */
+ uint32_t hasbit = field->presence;
+ *UPB_PTR_AT(msg, hasbit / 8, uint8_t) |= (1 << (hasbit % 8));
+ }
+
+ /* Store into message. */
+ switch (op) {
+ case OP_SUBMSG: {
+ upb_msg **submsgp = mem;
+ upb_msg *submsg = *submsgp;
+ if (!submsg) {
+ submsg = decode_newsubmsg(d, layout, field);
+ *submsgp = submsg;
+ }
+ if (UPB_UNLIKELY(type == UPB_DTYPE_GROUP)) {
+ ptr = decode_togroup(d, ptr, submsg, layout, field);
+ } else {
+ decode_tosubmsg(d, submsg, layout, field, val.str_val);
+ }
+ break;
+ }
+ case OP_STRING:
+ memcpy(mem, &val, sizeof(upb_strview));
+ break;
+ case OP_SCALAR_LG2(3):
+ memcpy(mem, &val, 8);
+ break;
+ case OP_SCALAR_LG2(2):
+ memcpy(mem, &val, 4);
+ break;
+ case OP_SCALAR_LG2(0):
+ memcpy(mem, &val, 1);
+ break;
+ default:
+ UPB_UNREACHABLE();
+ }
+
+ return ptr;
+}
+
+static const char *decode_msg(upb_decstate *d, const char *ptr, upb_msg *msg,
+ const upb_msglayout *layout) {
+ while (ptr < d->limit) {
+ uint32_t tag;
+ const upb_msglayout_field *field;
+ int field_number;
+ int wire_type;
+ const char *field_start = ptr;
+ wireval val;
+ int op;
+
+ ptr = decode_varint32(d, ptr, d->limit, &tag);
+ field_number = tag >> 3;
+ wire_type = tag & 7;
+
+ field = upb_find_field(layout, field_number);
+
+ switch (wire_type) {
+ case UPB_WIRE_TYPE_VARINT:
+ ptr = decode_varint64(d, ptr, d->limit, &val.uint64_val);
+ op = varint_ops[field->descriptortype];
+ decode_munge(field->descriptortype, &val);
+ break;
+ case UPB_WIRE_TYPE_32BIT:
+ if (d->limit - ptr < 4) decode_err(d);
+ memcpy(&val, ptr, 4);
+ ptr += 4;
+ op = OP_SCALAR_LG2(2);
+ if (((1 << field->descriptortype) & fixed32_ok) == 0) goto unknown;
+ break;
+ case UPB_WIRE_TYPE_64BIT:
+ if (d->limit - ptr < 8) decode_err(d);
+ memcpy(&val, ptr, 8);
+ ptr += 8;
+ op = OP_SCALAR_LG2(3);
+ if (((1 << field->descriptortype) & fixed64_ok) == 0) goto unknown;
+ break;
+ case UPB_WIRE_TYPE_DELIMITED: {
+ uint32_t size;
+ int ndx = field->descriptortype;
+ if (_upb_isrepeated(field)) ndx += 18;
+ ptr = decode_varint32(d, ptr, d->limit, &size);
+ if (size >= INT32_MAX || (size_t)(d->limit - ptr) < size) {
+ decode_err(d); /* Length overflow. */
+ }
+ val.str_val.data = ptr;
+ val.str_val.size = size;
+ ptr += size;
+ op = delim_ops[ndx];
+ break;
+ }
+ case UPB_WIRE_TYPE_START_GROUP:
+ val.int32_val = field_number;
+ op = OP_SUBMSG;
+ if (field->descriptortype != UPB_DTYPE_GROUP) goto unknown;
+ break;
case UPB_WIRE_TYPE_END_GROUP:
d->end_group = field_number;
- return true;
+ return ptr;
default:
- CHK(false);
+ decode_err(d);
}
- } else {
- CHK(field_number != 0);
- CHK(upb_skip_unknownfielddata(d, tag, -1));
- CHK(upb_append_unknown(d, frame));
- return true;
- }
-}
-static bool upb_decode_message(upb_decstate *d, char *msg, const upb_msglayout *l) {
- upb_decframe frame;
- frame.msg = msg;
- frame.layout = l;
- frame.state = d;
-
- while (d->ptr < d->limit) {
- CHK(upb_decode_field(d, &frame));
+ if (op >= 0) {
+ /* Parse, using op for dispatch. */
+ switch (field->label) {
+ case UPB_LABEL_REPEATED:
+ case _UPB_LABEL_PACKED:
+ ptr = decode_toarray(d, ptr, msg, layout, field, val, op);
+ break;
+ case _UPB_LABEL_MAP:
+ decode_tomap(d, msg, layout, field, val);
+ break;
+ default:
+ ptr = decode_tomsg(d, ptr, msg, layout, field, val, op);
+ break;
+ }
+ } else {
+ unknown:
+ /* Skip unknown field. */
+ if (field_number == 0) decode_err(d);
+ if (wire_type == UPB_WIRE_TYPE_START_GROUP) {
+ ptr = decode_group(d, ptr, NULL, NULL, field_number);
+ }
+ if (msg) {
+ if (!_upb_msg_addunknown(msg, field_start, ptr - field_start,
+ d->arena)) {
+ decode_err(d);
+ }
+ }
+ }
}
- return true;
+ if (ptr != d->limit) decode_err(d);
+ return ptr;
}
bool upb_decode(const char *buf, size_t size, void *msg, const upb_msglayout *l,
upb_arena *arena) {
upb_decstate state;
- state.ptr = buf;
state.limit = buf + size;
state.arena = arena;
state.depth = 64;
state.end_group = 0;
- CHK(upb_decode_message(&state, msg, l));
+ if (setjmp(state.err)) return false;
+
+ if (size == 0) return true;
+ decode_msg(&state, buf, msg, l);
+
return state.end_group == 0;
}
-#undef CHK
+#undef OP_SCALAR_LG2
+#undef OP_FIXPCK_LG2
+#undef OP_VARPCK_LG2
+#undef OP_STRING
+#undef OP_SUBMSG
/* We encode backwards, to avoid pre-computing lengths (one-pass encode). */
@@ -821,6 +801,7 @@
/* Writes the given bytes to the buffer, handling reserve/advance. */
static bool upb_put_bytes(upb_encstate *e, const void *data, size_t len) {
+ if (len == 0) return true;
CHK(upb_encode_reserve(e, len));
memcpy(e->ptr, data, len);
return true;
@@ -863,15 +844,14 @@
static uint32_t upb_readcase(const char *msg, const upb_msglayout_field *f) {
uint32_t ret;
- uint32_t offset = ~f->presence;
- memcpy(&ret, msg + offset, sizeof(ret));
+ memcpy(&ret, msg - f->presence, sizeof(ret));
return ret;
}
static bool upb_readhasbit(const char *msg, const upb_msglayout_field *f) {
uint32_t hasbit = f->presence;
UPB_ASSERT(f->presence > 0);
- return msg[hasbit / 8] & (1 << (hasbit % 8));
+ return (*UPB_PTR_AT(msg, hasbit / 8, uint8_t)) & (1 << (hasbit % 8));
}
static bool upb_put_tag(upb_encstate *e, int field_number, int wire_type) {
@@ -879,116 +859,30 @@
}
static bool upb_put_fixedarray(upb_encstate *e, const upb_array *arr,
- size_t size) {
- size_t bytes = arr->len * size;
- return upb_put_bytes(e, arr->data, bytes) && upb_put_varint(e, bytes);
+ size_t elem_size, uint32_t tag) {
+ size_t bytes = arr->len * elem_size;
+ const char* data = _upb_array_constptr(arr);
+ const char* ptr = data + bytes - elem_size;
+ if (tag) {
+ while (true) {
+ CHK(upb_put_bytes(e, ptr, elem_size) && upb_put_varint(e, tag));
+ if (ptr == data) break;
+ ptr -= elem_size;
+ }
+ return true;
+ } else {
+ return upb_put_bytes(e, data, bytes) && upb_put_varint(e, bytes);
+ }
}
bool upb_encode_message(upb_encstate *e, const char *msg,
const upb_msglayout *m, size_t *size);
-static bool upb_encode_array(upb_encstate *e, const char *field_mem,
- const upb_msglayout *m,
- const upb_msglayout_field *f) {
- const upb_array *arr = *(const upb_array**)field_mem;
-
- if (arr == NULL || arr->len == 0) {
- return true;
- }
-
-#define VARINT_CASE(ctype, encode) { \
- ctype *start = arr->data; \
- ctype *ptr = start + arr->len; \
- size_t pre_len = e->limit - e->ptr; \
- do { \
- ptr--; \
- CHK(upb_put_varint(e, encode)); \
- } while (ptr != start); \
- CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
-} \
-break; \
-do { ; } while(0)
-
- switch (f->descriptortype) {
- case UPB_DESCRIPTOR_TYPE_DOUBLE:
- CHK(upb_put_fixedarray(e, arr, sizeof(double)));
- break;
- case UPB_DESCRIPTOR_TYPE_FLOAT:
- CHK(upb_put_fixedarray(e, arr, sizeof(float)));
- break;
- case UPB_DESCRIPTOR_TYPE_SFIXED64:
- case UPB_DESCRIPTOR_TYPE_FIXED64:
- CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t)));
- break;
- case UPB_DESCRIPTOR_TYPE_FIXED32:
- case UPB_DESCRIPTOR_TYPE_SFIXED32:
- CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t)));
- break;
- case UPB_DESCRIPTOR_TYPE_INT64:
- case UPB_DESCRIPTOR_TYPE_UINT64:
- VARINT_CASE(uint64_t, *ptr);
- case UPB_DESCRIPTOR_TYPE_UINT32:
- VARINT_CASE(uint32_t, *ptr);
- case UPB_DESCRIPTOR_TYPE_INT32:
- case UPB_DESCRIPTOR_TYPE_ENUM:
- VARINT_CASE(int32_t, (int64_t)*ptr);
- case UPB_DESCRIPTOR_TYPE_BOOL:
- VARINT_CASE(bool, *ptr);
- case UPB_DESCRIPTOR_TYPE_SINT32:
- VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
- case UPB_DESCRIPTOR_TYPE_SINT64:
- VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
- case UPB_DESCRIPTOR_TYPE_STRING:
- case UPB_DESCRIPTOR_TYPE_BYTES: {
- upb_strview *start = arr->data;
- upb_strview *ptr = start + arr->len;
- do {
- ptr--;
- CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
- upb_put_varint(e, ptr->size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- } while (ptr != start);
- return true;
- }
- case UPB_DESCRIPTOR_TYPE_GROUP: {
- void **start = arr->data;
- void **ptr = start + arr->len;
- const upb_msglayout *subm = m->submsgs[f->submsg_index];
- do {
- size_t size;
- ptr--;
- CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
- upb_encode_message(e, *ptr, subm, &size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
- } while (ptr != start);
- return true;
- }
- case UPB_DESCRIPTOR_TYPE_MESSAGE: {
- void **start = arr->data;
- void **ptr = start + arr->len;
- const upb_msglayout *subm = m->submsgs[f->submsg_index];
- do {
- size_t size;
- ptr--;
- CHK(upb_encode_message(e, *ptr, subm, &size) &&
- upb_put_varint(e, size) &&
- upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- } while (ptr != start);
- return true;
- }
- }
-#undef VARINT_CASE
-
- /* We encode all primitive arrays as packed, regardless of what was specified
- * in the .proto file. Could special case 1-sized arrays. */
- CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
- return true;
-}
-
-static bool upb_encode_scalarfield(upb_encstate *e, const char *field_mem,
+static bool upb_encode_scalarfield(upb_encstate *e, const void *_field_mem,
const upb_msglayout *m,
const upb_msglayout_field *f,
bool skip_zero_value) {
+ const char *field_mem = _field_mem;
#define CASE(ctype, type, wire_type, encodeval) do { \
ctype val = *(ctype*)field_mem; \
if (skip_zero_value && val == 0) { \
@@ -1060,6 +954,146 @@
UPB_UNREACHABLE();
}
+static bool upb_encode_array(upb_encstate *e, const char *field_mem,
+ const upb_msglayout *m,
+ const upb_msglayout_field *f) {
+ const upb_array *arr = *(const upb_array**)field_mem;
+ bool packed = f->label == _UPB_LABEL_PACKED;
+
+ if (arr == NULL || arr->len == 0) {
+ return true;
+ }
+
+#define VARINT_CASE(ctype, encode) \
+ { \
+ const ctype *start = _upb_array_constptr(arr); \
+ const ctype *ptr = start + arr->len; \
+ size_t pre_len = e->limit - e->ptr; \
+ uint32_t tag = packed ? 0 : (f->number << 3) | UPB_WIRE_TYPE_VARINT; \
+ do { \
+ ptr--; \
+ CHK(upb_put_varint(e, encode)); \
+ if (tag) CHK(upb_put_varint(e, tag)); \
+ } while (ptr != start); \
+ if (!tag) CHK(upb_put_varint(e, e->limit - e->ptr - pre_len)); \
+ } \
+ break; \
+ do { \
+ ; \
+ } while (0)
+
+#define TAG(wire_type) (packed ? 0 : (f->number << 3 | wire_type))
+
+ switch (f->descriptortype) {
+ case UPB_DESCRIPTOR_TYPE_DOUBLE:
+ CHK(upb_put_fixedarray(e, arr, sizeof(double), TAG(UPB_WIRE_TYPE_64BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FLOAT:
+ CHK(upb_put_fixedarray(e, arr, sizeof(float), TAG(UPB_WIRE_TYPE_32BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_SFIXED64:
+ case UPB_DESCRIPTOR_TYPE_FIXED64:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint64_t), TAG(UPB_WIRE_TYPE_64BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_FIXED32:
+ case UPB_DESCRIPTOR_TYPE_SFIXED32:
+ CHK(upb_put_fixedarray(e, arr, sizeof(uint32_t), TAG(UPB_WIRE_TYPE_32BIT)));
+ break;
+ case UPB_DESCRIPTOR_TYPE_INT64:
+ case UPB_DESCRIPTOR_TYPE_UINT64:
+ VARINT_CASE(uint64_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_UINT32:
+ VARINT_CASE(uint32_t, *ptr);
+ case UPB_DESCRIPTOR_TYPE_INT32:
+ case UPB_DESCRIPTOR_TYPE_ENUM:
+ VARINT_CASE(int32_t, (int64_t)*ptr);
+ case UPB_DESCRIPTOR_TYPE_BOOL:
+ VARINT_CASE(bool, *ptr);
+ case UPB_DESCRIPTOR_TYPE_SINT32:
+ VARINT_CASE(int32_t, upb_zzencode_32(*ptr));
+ case UPB_DESCRIPTOR_TYPE_SINT64:
+ VARINT_CASE(int64_t, upb_zzencode_64(*ptr));
+ case UPB_DESCRIPTOR_TYPE_STRING:
+ case UPB_DESCRIPTOR_TYPE_BYTES: {
+ const upb_strview *start = _upb_array_constptr(arr);
+ const upb_strview *ptr = start + arr->len;
+ do {
+ ptr--;
+ CHK(upb_put_bytes(e, ptr->data, ptr->size) &&
+ upb_put_varint(e, ptr->size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_GROUP: {
+ const void *const*start = _upb_array_constptr(arr);
+ const void *const*ptr = start + arr->len;
+ const upb_msglayout *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_END_GROUP) &&
+ upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_START_GROUP));
+ } while (ptr != start);
+ return true;
+ }
+ case UPB_DESCRIPTOR_TYPE_MESSAGE: {
+ const void *const*start = _upb_array_constptr(arr);
+ const void *const*ptr = start + arr->len;
+ const upb_msglayout *subm = m->submsgs[f->submsg_index];
+ do {
+ size_t size;
+ ptr--;
+ CHK(upb_encode_message(e, *ptr, subm, &size) &&
+ upb_put_varint(e, size) &&
+ upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ } while (ptr != start);
+ return true;
+ }
+ }
+#undef VARINT_CASE
+
+ if (packed) {
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ }
+ return true;
+}
+
+static bool upb_encode_map(upb_encstate *e, const char *field_mem,
+ const upb_msglayout *m,
+ const upb_msglayout_field *f) {
+ const upb_map *map = *(const upb_map**)field_mem;
+ const upb_msglayout *entry = m->submsgs[f->submsg_index];
+ const upb_msglayout_field *key_field = &entry->fields[0];
+ const upb_msglayout_field *val_field = &entry->fields[1];
+ upb_strtable_iter i;
+ if (map == NULL) {
+ return true;
+ }
+
+ upb_strtable_begin(&i, &map->table);
+ for(; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ size_t pre_len = e->limit - e->ptr;
+ size_t size;
+ upb_strview key = upb_strtable_iter_key(&i);
+ const upb_value val = upb_strtable_iter_value(&i);
+ const void *keyp =
+ map->key_size == UPB_MAPTYPE_STRING ? (void *)&key : key.data;
+ const void *valp =
+ map->val_size == UPB_MAPTYPE_STRING ? upb_value_getptr(val) : &val;
+
+ CHK(upb_encode_scalarfield(e, valp, entry, val_field, false));
+ CHK(upb_encode_scalarfield(e, keyp, entry, key_field, false));
+ size = (e->limit - e->ptr) - pre_len;
+ CHK(upb_put_varint(e, size));
+ CHK(upb_put_tag(e, f->number, UPB_WIRE_TYPE_DELIMITED));
+ }
+
+ return true;
+}
+
+
bool upb_encode_message(upb_encstate *e, const char *msg,
const upb_msglayout *m, size_t *size) {
int i;
@@ -1067,11 +1101,19 @@
const char *unknown;
size_t unknown_size;
+ unknown = upb_msg_getunknown(msg, &unknown_size);
+
+ if (unknown) {
+ upb_put_bytes(e, unknown, unknown_size);
+ }
+
for (i = m->field_count - 1; i >= 0; i--) {
const upb_msglayout_field *f = &m->fields[i];
- if (f->label == UPB_LABEL_REPEATED) {
+ if (_upb_isrepeated(f)) {
CHK(upb_encode_array(e, msg + f->offset, m, f));
+ } else if (f->label == _UPB_LABEL_MAP) {
+ CHK(upb_encode_map(e, msg + f->offset, m, f));
} else {
bool skip_empty = false;
if (f->presence == 0) {
@@ -1092,12 +1134,6 @@
}
}
- unknown = upb_msg_getunknown(msg, &unknown_size);
-
- if (unknown) {
- upb_put_bytes(e, unknown, unknown_size);
- }
-
*size = (e->limit - e->ptr) - pre_len;
return true;
}
@@ -1131,24 +1167,27 @@
-#define VOIDPTR_AT(msg, ofs) (void*)((char*)msg + (int)ofs)
+/** upb_msg *******************************************************************/
-/* Internal members of a upb_msg. We can change this without breaking binary
- * compatibility. We put these before the user's data. The user's upb_msg*
- * points after the upb_msg_internal. */
+static const char _upb_fieldtype_to_sizelg2[12] = {
+ 0,
+ 0, /* UPB_TYPE_BOOL */
+ 2, /* UPB_TYPE_FLOAT */
+ 2, /* UPB_TYPE_INT32 */
+ 2, /* UPB_TYPE_UINT32 */
+ 2, /* UPB_TYPE_ENUM */
+ UPB_SIZE(2, 3), /* UPB_TYPE_MESSAGE */
+ 3, /* UPB_TYPE_DOUBLE */
+ 3, /* UPB_TYPE_INT64 */
+ 3, /* UPB_TYPE_UINT64 */
+ UPB_SIZE(3, 4), /* UPB_TYPE_STRING */
+ UPB_SIZE(3, 4), /* UPB_TYPE_BYTES */
+};
-/* Used when a message is not extendable. */
-typedef struct {
- char *unknown;
- size_t unknown_len;
- size_t unknown_size;
-} upb_msg_internal;
-
-/* Used when a message is extendable. */
-typedef struct {
- upb_inttable *extdict;
- upb_msg_internal base;
-} upb_msg_internal_withext;
+static uintptr_t tag_arrptr(void* ptr, int elem_size_lg2) {
+ UPB_ASSERT(elem_size_lg2 <= 4);
+ return (uintptr_t)ptr | elem_size_lg2;
+}
static int upb_msg_internalsize(const upb_msglayout *l) {
return sizeof(upb_msg_internal) - l->extendable * sizeof(void *);
@@ -1159,22 +1198,22 @@
}
static upb_msg_internal *upb_msg_getinternal(upb_msg *msg) {
- return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+ return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
}
static const upb_msg_internal *upb_msg_getinternal_const(const upb_msg *msg) {
- return VOIDPTR_AT(msg, -sizeof(upb_msg_internal));
+ return UPB_PTR_AT(msg, -sizeof(upb_msg_internal), upb_msg_internal);
}
static upb_msg_internal_withext *upb_msg_getinternalwithext(
upb_msg *msg, const upb_msglayout *l) {
UPB_ASSERT(l->extendable);
- return VOIDPTR_AT(msg, -sizeof(upb_msg_internal_withext));
+ return UPB_PTR_AT(msg, -sizeof(upb_msg_internal_withext),
+ upb_msg_internal_withext);
}
-upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a) {
- upb_alloc *alloc = upb_arena_alloc(a);
- void *mem = upb_malloc(alloc, upb_msg_sizeof(l));
+upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a) {
+ void *mem = upb_arena_malloc(a, upb_msg_sizeof(l));
upb_msg_internal *in;
upb_msg *msg;
@@ -1182,7 +1221,7 @@
return NULL;
}
- msg = VOIDPTR_AT(mem, upb_msg_internalsize(l));
+ msg = UPB_PTR_AT(mem, upb_msg_internalsize(l), upb_msg);
/* Initialize normal members. */
memset(msg, 0, l->size);
@@ -1200,66 +1239,122 @@
return msg;
}
-upb_array *upb_array_new(upb_arena *a) {
- upb_array *ret = upb_arena_malloc(a, sizeof(upb_array));
-
- if (!ret) {
- return NULL;
- }
-
- ret->data = NULL;
- ret->len = 0;
- ret->size = 0;
-
- return ret;
-}
-
-void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
- upb_arena *arena) {
+bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
+ upb_arena *arena) {
upb_msg_internal *in = upb_msg_getinternal(msg);
if (len > in->unknown_size - in->unknown_len) {
upb_alloc *alloc = upb_arena_alloc(arena);
size_t need = in->unknown_size + len;
size_t newsize = UPB_MAX(in->unknown_size * 2, need);
- in->unknown = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
+ void *mem = upb_realloc(alloc, in->unknown, in->unknown_size, newsize);
+ if (!mem) return false;
+ in->unknown = mem;
in->unknown_size = newsize;
}
memcpy(in->unknown + in->unknown_len, data, len);
in->unknown_len += len;
+ return true;
}
const char *upb_msg_getunknown(const upb_msg *msg, size_t *len) {
- const upb_msg_internal* in = upb_msg_getinternal_const(msg);
+ const upb_msg_internal *in = upb_msg_getinternal_const(msg);
*len = in->unknown_len;
return in->unknown;
}
-#undef VOIDPTR_AT
+/** upb_array *****************************************************************/
+upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type) {
+ upb_array *arr = upb_arena_malloc(a, sizeof(upb_array));
-#ifdef UPB_MSVC_VSNPRINTF
-/* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
- * vsnprintf. To support them, missing functions are manually implemented
- * using the existing secure functions. */
-int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
- if (!s) {
- return _vscprintf(format, arg);
+ if (!arr) {
+ return NULL;
}
- int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
- if (ret < 0) {
- ret = _vscprintf(format, arg);
- }
- return ret;
+
+ arr->data = tag_arrptr(NULL, _upb_fieldtype_to_sizelg2[type]);
+ arr->len = 0;
+ arr->size = 0;
+
+ return arr;
}
-int msvc_snprintf(char* s, size_t n, const char* format, ...) {
- va_list arg;
- va_start(arg, format);
- int ret = msvc_vsnprintf(s, n, format, arg);
- va_end(arg);
- return ret;
+bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena) {
+ size_t new_size = UPB_MAX(arr->size, 4);
+ int elem_size_lg2 = arr->data & 7;
+ size_t old_bytes = arr->size << elem_size_lg2;
+ size_t new_bytes;
+ void* ptr = _upb_array_ptr(arr);
+
+ /* Log2 ceiling of size. */
+ while (new_size < min_size) new_size *= 2;
+
+ new_bytes = new_size << elem_size_lg2;
+ ptr = upb_arena_realloc(arena, ptr, old_bytes, new_bytes);
+
+ if (!ptr) {
+ return false;
+ }
+
+ arr->data = tag_arrptr(ptr, elem_size_lg2);
+ arr->size = new_size;
+ return true;
}
-#endif
+
+static upb_array *getorcreate_array(upb_array **arr_ptr, upb_fieldtype_t type,
+ upb_arena *arena) {
+ upb_array *arr = *arr_ptr;
+ if (!arr) {
+ arr = _upb_array_new(arena, type);
+ if (!arr) return NULL;
+ *arr_ptr = arr;
+ }
+ return arr;
+}
+
+static bool resize_array(upb_array *arr, size_t size, upb_arena *arena) {
+ if (size > arr->size && !_upb_array_realloc(arr, size, arena)) {
+ return false;
+ }
+
+ arr->len = size;
+ return true;
+}
+
+void *_upb_array_resize_fallback(upb_array **arr_ptr, size_t size,
+ upb_fieldtype_t type, upb_arena *arena) {
+ upb_array *arr = getorcreate_array(arr_ptr, type, arena);
+ return arr && resize_array(arr, size, arena) ? _upb_array_ptr(arr) : NULL;
+}
+
+bool _upb_array_append_fallback(upb_array **arr_ptr, const void *value,
+ upb_fieldtype_t type, upb_arena *arena) {
+ upb_array *arr = getorcreate_array(arr_ptr, type, arena);
+ size_t elem = arr->len;
+ int lg2 = _upb_fieldtype_to_sizelg2[type];
+ char *data;
+
+ if (!arr || !resize_array(arr, elem + 1, arena)) return false;
+
+ data = _upb_array_ptr(arr);
+ memcpy(data + (elem << lg2), value, 1 << lg2);
+ return true;
+}
+
+/** upb_map *******************************************************************/
+
+upb_map *_upb_map_new(upb_arena *a, size_t key_size, size_t value_size) {
+ upb_map *map = upb_arena_malloc(a, sizeof(upb_map));
+
+ if (!map) {
+ return NULL;
+ }
+
+ upb_strtable_init2(&map->table, UPB_CTYPE_INT32, upb_arena_alloc(a));
+ map->key_size = key_size;
+ map->val_size = value_size;
+
+ return map;
+}
/*
** upb_table Implementation
**
@@ -1276,12 +1371,6 @@
#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
@@ -1360,17 +1449,12 @@
}
}
-static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
- upb_alloc *a) {
+static bool init(upb_table *t, 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 = upb_malloc(a, bytes);
@@ -1383,7 +1467,6 @@
}
static void uninit(upb_table *t, upb_alloc *a) {
- upb_check_alloc(t, a);
upb_free(a, mutable_entries(t));
}
@@ -1419,7 +1502,7 @@
const upb_tabent *e = findentry(t, key, hash, eql);
if (e) {
if (v) {
- _upb_value_setval(v, e->val.val, t->ctype);
+ _upb_value_setval(v, e->val.val);
}
return true;
} else {
@@ -1435,7 +1518,6 @@
upb_tabent *our_e;
UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
- UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
t->count++;
mainpos_e = getentry_mutable(t, hash);
@@ -1481,7 +1563,7 @@
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);
if (removed) *removed = chain->key;
if (chain->next) {
upb_tabent *move = (upb_tabent*)chain->next;
@@ -1501,7 +1583,7 @@
/* Found element to remove. */
upb_tabent *rm = (upb_tabent*)chain->next;
t->count--;
- if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
+ if (val) _upb_value_setval(val, chain->next->val.val);
if (removed) *removed = rm->key;
rm->key = 0; /* Make the slot empty. */
chain->next = rm->next;
@@ -1554,7 +1636,13 @@
}
bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
- return init(&t->t, ctype, 2, a);
+ return init(&t->t, 2, a);
+}
+
+void upb_strtable_clear(upb_strtable *t) {
+ size_t bytes = upb_table_size(&t->t) * sizeof(upb_tabent);
+ t->t.count = 0;
+ memset((char*)t->t.entries, 0, bytes);
}
void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
@@ -1568,18 +1656,14 @@
upb_strtable new_table;
upb_strtable_iter i;
- upb_check_alloc(&t->t, a);
-
- if (!init(&new_table.t, t->t.ctype, size_lg2, a))
+ if (!init(&new_table.t, size_lg2, a))
return false;
upb_strtable_begin(&i, t);
for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
+ upb_strview key = upb_strtable_iter_key(&i);
upb_strtable_insert3(
- &new_table,
- upb_strtable_iter_key(&i),
- upb_strtable_iter_keylength(&i),
- upb_strtable_iter_value(&i),
- a);
+ &new_table, key.data, key.size,
+ upb_strtable_iter_value(&i), a);
}
upb_strtable_uninit2(t, a);
*t = new_table;
@@ -1592,8 +1676,6 @@
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, a)) {
@@ -1621,7 +1703,10 @@
uint32_t hash = upb_murmur_hash2(key, len, 0);
upb_tabkey tabkey;
if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
- upb_free(alloc, (void*)tabkey);
+ if (alloc) {
+ /* Arena-based allocs don't need to free and won't pass this. */
+ upb_free(alloc, (void*)tabkey);
+ }
return true;
} else {
return false;
@@ -1630,10 +1715,6 @@
/* Iteration */
-static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
- return &i->t->t.entries[i->index];
-}
-
void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
i->t = t;
i->index = begin(&t->t);
@@ -1649,21 +1730,18 @@
upb_tabent_isempty(str_tabent(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(const upb_strtable_iter *i) {
+upb_strview upb_strtable_iter_key(const upb_strtable_iter *i) {
+ upb_strview key;
uint32_t len;
UPB_ASSERT(!upb_strtable_done(i));
- upb_tabstr(str_tabent(i)->key, &len);
- return len;
+ key.data = upb_tabstr(str_tabent(i)->key, &len);
+ key.size = len;
+ return key;
}
upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
UPB_ASSERT(!upb_strtable_done(i));
- return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
+ return _upb_value_val(str_tabent(i)->val.val);
}
void upb_strtable_iter_setdone(upb_strtable_iter *i) {
@@ -1729,11 +1807,11 @@
#endif
}
-bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
- size_t asize, int hsize_lg2, upb_alloc *a) {
+bool upb_inttable_sizedinit(upb_inttable *t, size_t asize, int hsize_lg2,
+ upb_alloc *a) {
size_t array_bytes;
- if (!init(&t->t, ctype, hsize_lg2, a)) return false;
+ if (!init(&t->t, 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);
@@ -1750,7 +1828,7 @@
}
bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
- return upb_inttable_sizedinit(t, ctype, 0, 4, a);
+ return upb_inttable_sizedinit(t, 0, 4, a);
}
void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
@@ -1764,8 +1842,6 @@
tabval.val = val.val;
UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
- upb_check_alloc(&t->t, a);
-
if (key < t->array_size) {
UPB_ASSERT(!upb_arrhas(t->array[key]));
t->array_count++;
@@ -1776,7 +1852,7 @@
size_t i;
upb_table new_table;
- if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
+ if (!init(&new_table, t->t.size_lg2 + 1, a)) {
return false;
}
@@ -1785,7 +1861,7 @@
uint32_t hash;
upb_value v;
- _upb_value_setval(&v, e->val.val, t->t.ctype);
+ _upb_value_setval(&v, e->val.val);
hash = upb_inthash(e->key);
insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
}
@@ -1804,7 +1880,7 @@
bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
const upb_tabval *table_v = inttable_val_const(t, key);
if (!table_v) return false;
- if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
+ if (v) _upb_value_setval(v, table_v->val);
return true;
}
@@ -1822,7 +1898,7 @@
upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
t->array_count--;
if (val) {
- _upb_value_setval(val, t->array[key].val, t->t.ctype);
+ _upb_value_setval(val, t->array[key].val);
}
mutable_array(t)[key] = empty;
success = true;
@@ -1837,7 +1913,6 @@
}
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);
}
@@ -1850,7 +1925,6 @@
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);
}
@@ -1875,8 +1949,6 @@
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);
@@ -1909,7 +1981,7 @@
size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
int hashsize_lg2 = log2ceil(hash_size);
- upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
+ upb_inttable_sizedinit(&new_t, 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);
@@ -1975,8 +2047,7 @@
upb_value upb_inttable_iter_value(const upb_inttable_iter *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);
+ i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val);
}
void upb_inttable_iter_setdone(upb_inttable_iter *i) {
@@ -2016,7 +2087,8 @@
/* Mix 4 bytes at a time into the hash */
const uint8_t * data = (const uint8_t *)key;
while(len >= 4) {
- uint32_t k = *(uint32_t *)data;
+ uint32_t k;
+ memcpy(&k, data, sizeof(k));
k *= m;
k ^= k >> r;
@@ -2181,17 +2253,6 @@
#include <string.h>
-/* Guarantee null-termination and provide ellipsis truncation.
- * It may be tempting to "optimize" this by initializing these final
- * four bytes up-front and then being careful never to overwrite them,
- * this is safer and simpler. */
-static void nullz(upb_status *status) {
- const char *ellipsis = "...";
- size_t len = strlen(ellipsis);
- UPB_ASSERT(sizeof(status->msg) > len);
- memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
-}
-
/* upb_status *****************************************************************/
void upb_status_clear(upb_status *status) {
@@ -2207,8 +2268,8 @@
void upb_status_seterrmsg(upb_status *status, const char *msg) {
if (!status) return;
status->ok = false;
- strncpy(status->msg, msg, sizeof(status->msg));
- nullz(status);
+ strncpy(status->msg, msg, UPB_STATUS_MAX_MESSAGE - 1);
+ status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
}
void upb_status_seterrf(upb_status *status, const char *fmt, ...) {
@@ -2222,7 +2283,7 @@
if (!status) return;
status->ok = false;
_upb_vsnprintf(status->msg, sizeof(status->msg), fmt, args);
- nullz(status);
+ status->msg[UPB_STATUS_MAX_MESSAGE - 1] = '\0';
}
/* upb_alloc ******************************************************************/
@@ -2244,16 +2305,10 @@
/* upb_arena ******************************************************************/
/* Be conservative and choose 16 in case anyone is using SSE. */
-static const size_t maxalign = 16;
-
-static size_t align_up_max(size_t size) {
- return ((size + maxalign - 1) / maxalign) * maxalign;
-}
struct upb_arena {
- /* We implement the allocator interface.
- * This must be the first member of upb_arena! */
- upb_alloc alloc;
+ _upb_arena_head head;
+ char *start;
/* Allocator to allocate arena blocks. We are responsible for freeing these
* when we are destroyed. */
@@ -2272,8 +2327,6 @@
typedef struct mem_block {
struct mem_block *next;
- size_t size;
- size_t used;
bool owned;
/* Data follows. */
} mem_block;
@@ -2288,12 +2341,17 @@
bool owned) {
mem_block *block = ptr;
+ if (a->block_head) {
+ a->bytes_allocated += a->head.ptr - a->start;
+ }
+
block->next = a->block_head;
- block->size = size;
- block->used = align_up_max(sizeof(mem_block));
block->owned = owned;
a->block_head = block;
+ a->start = (char*)block + _upb_arena_alignup(sizeof(mem_block));
+ a->head.ptr = a->start;
+ a->head.end = (char*)block + size;
/* TODO(haberman): ASAN poison. */
}
@@ -2312,39 +2370,31 @@
return block;
}
+void *_upb_arena_slowmalloc(upb_arena *a, size_t size) {
+ mem_block *block = upb_arena_allocblock(a, size);
+ if (!block) return NULL; /* Out of memory. */
+ return upb_arena_malloc(a, size);
+}
+
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_max(size);
+ ret = upb_arena_malloc(a, size);
+ if (!ret) return NULL;
/* 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;
}
@@ -2373,7 +2423,10 @@
a = (void*)((char*)mem + n - sizeof(*a));
n -= sizeof(*a);
- a->alloc.func = &upb_arena_doalloc;
+ a->head.alloc.func = &upb_arena_doalloc;
+ a->head.ptr = NULL;
+ a->head.end = NULL;
+ a->start = NULL;
a->block_alloc = &upb_alloc_global;
a->bytes_allocated = 0;
a->next_block_size = 256;
@@ -2413,7 +2466,7 @@
}
bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func) {
- cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
+ cleanup_ent *ent = upb_malloc(&a->head.alloc, sizeof(cleanup_ent));
if (!ent) {
return false; /* Out of memory. */
}
@@ -2427,7 +2480,7 @@
}
size_t upb_arena_bytesallocated(const upb_arena *a) {
- return a->bytes_allocated;
+ return a->bytes_allocated + (a->head.ptr - a->start);
}
/* This file was generated by upbc (the upb compiler) from the input
* file:
@@ -2558,23 +2611,24 @@
&google_protobuf_FieldOptions_msginit,
};
-static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[10] = {
- {1, UPB_SIZE(32, 32), 5, 0, 9, 1},
- {2, UPB_SIZE(40, 48), 6, 0, 9, 1},
+static const upb_msglayout_field google_protobuf_FieldDescriptorProto__fields[11] = {
+ {1, UPB_SIZE(36, 40), 6, 0, 9, 1},
+ {2, UPB_SIZE(44, 56), 7, 0, 9, 1},
{3, UPB_SIZE(24, 24), 3, 0, 5, 1},
{4, UPB_SIZE(8, 8), 1, 0, 14, 1},
{5, UPB_SIZE(16, 16), 2, 0, 14, 1},
- {6, UPB_SIZE(48, 64), 7, 0, 9, 1},
- {7, UPB_SIZE(56, 80), 8, 0, 9, 1},
- {8, UPB_SIZE(72, 112), 10, 0, 11, 1},
+ {6, UPB_SIZE(52, 72), 8, 0, 9, 1},
+ {7, UPB_SIZE(60, 88), 9, 0, 9, 1},
+ {8, UPB_SIZE(76, 120), 11, 0, 11, 1},
{9, UPB_SIZE(28, 28), 4, 0, 5, 1},
- {10, UPB_SIZE(64, 96), 9, 0, 9, 1},
+ {10, UPB_SIZE(68, 104), 10, 0, 9, 1},
+ {17, UPB_SIZE(32, 32), 5, 0, 8, 1},
};
const upb_msglayout google_protobuf_FieldDescriptorProto_msginit = {
&google_protobuf_FieldDescriptorProto_submsgs[0],
&google_protobuf_FieldDescriptorProto__fields[0],
- UPB_SIZE(80, 128), 10, false,
+ UPB_SIZE(80, 128), 11, false,
};
static const upb_msglayout *const google_protobuf_OneofDescriptorProto_submsgs[1] = {
@@ -2869,8 +2923,8 @@
};
static const upb_msglayout_field google_protobuf_SourceCodeInfo_Location__fields[5] = {
- {1, UPB_SIZE(20, 40), 0, 0, 5, 3},
- {2, UPB_SIZE(24, 48), 0, 0, 5, 3},
+ {1, UPB_SIZE(20, 40), 0, 0, 5, _UPB_LABEL_PACKED},
+ {2, UPB_SIZE(24, 48), 0, 0, 5, _UPB_LABEL_PACKED},
{3, UPB_SIZE(4, 8), 1, 0, 9, 1},
{4, UPB_SIZE(12, 24), 2, 0, 9, 1},
{6, UPB_SIZE(28, 56), 0, 0, 9, 3},
@@ -2897,7 +2951,7 @@
};
static const upb_msglayout_field google_protobuf_GeneratedCodeInfo_Annotation__fields[4] = {
- {1, UPB_SIZE(20, 32), 0, 0, 5, 3},
+ {1, UPB_SIZE(20, 32), 0, 0, 5, _UPB_LABEL_PACKED},
{2, UPB_SIZE(12, 16), 3, 0, 9, 1},
{3, UPB_SIZE(4, 4), 1, 0, 5, 1},
{4, UPB_SIZE(8, 8), 2, 0, 5, 1},
@@ -2936,6 +2990,7 @@
const upb_filedef *file;
const upb_msgdef *msgdef;
const char *full_name;
+ const char *json_name;
union {
int64_t sint;
uint64_t uint;
@@ -2951,16 +3006,19 @@
const google_protobuf_FieldDescriptorProto *unresolved;
} sub;
uint32_t number_;
- uint32_t index_;
+ uint16_t index_;
+ uint16_t layout_index;
uint32_t selector_base; /* Used to index into a upb::Handlers table. */
bool is_extension_;
bool lazy_;
bool packed_;
+ bool proto3_optional_;
upb_descriptortype_t type_;
upb_label_t label_;
};
struct upb_msgdef {
+ const upb_msglayout *layout;
const upb_filedef *file;
const char *full_name;
uint32_t selector_count;
@@ -2974,6 +3032,7 @@
const upb_oneofdef *oneofs;
int field_count;
int oneof_count;
+ int real_oneof_count;
/* Is this a map-entry message? */
bool map_entry;
@@ -3024,10 +3083,15 @@
/* Inside a symtab we store tagged pointers to specific def types. */
typedef enum {
- UPB_DEFTYPE_MSG = 0,
- UPB_DEFTYPE_ENUM = 1,
- UPB_DEFTYPE_FIELD = 2,
- UPB_DEFTYPE_ONEOF = 3
+ UPB_DEFTYPE_FIELD = 0,
+
+ /* Only inside symtab table. */
+ UPB_DEFTYPE_MSG = 1,
+ UPB_DEFTYPE_ENUM = 2,
+
+ /* Only inside message table. */
+ UPB_DEFTYPE_ONEOF = 1,
+ UPB_DEFTYPE_FIELD_JSONNAME = 2
} upb_deftype_t;
static const void *unpack_def(upb_value v, upb_deftype_t type) {
@@ -3140,11 +3204,14 @@
return ret;
}
+static void upb_status_setoom(upb_status *status) {
+ upb_status_seterrmsg(status, "out of memory");
+}
+
static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
/* Sort fields. upb internally relies on UPB_TYPE_MESSAGE fields having the
* lowest indexes, but we do not publicly guarantee this. */
upb_msg_field_iter j;
- upb_msg_oneof_iter k;
int i;
uint32_t selector;
int n = upb_msgdef_numfields(m);
@@ -3185,14 +3252,38 @@
}
m->selector_count = selector;
- for(upb_msg_oneof_begin(&k, m), i = 0;
- !upb_msg_oneof_done(&k);
- upb_msg_oneof_next(&k), i++) {
- upb_oneofdef *o = (upb_oneofdef*)upb_msg_iter_oneof(&k);
- o->index = i;
+ upb_gfree(fields);
+ return true;
+}
+
+static bool check_oneofs(upb_msgdef *m, upb_status *s) {
+ int i;
+ int first_synthetic = -1;
+ upb_oneofdef *mutable_oneofs = (upb_oneofdef*)m->oneofs;
+
+ for (i = 0; i < m->oneof_count; i++) {
+ mutable_oneofs[i].index = i;
+
+ if (upb_oneofdef_issynthetic(&mutable_oneofs[i])) {
+ if (first_synthetic == -1) {
+ first_synthetic = i;
+ }
+ } else {
+ if (first_synthetic != -1) {
+ upb_status_seterrf(
+ s, "Synthetic oneofs must be after all other oneofs: %s",
+ upb_oneofdef_name(&mutable_oneofs[i]));
+ return false;
+ }
+ }
}
- upb_gfree(fields);
+ if (first_synthetic == -1) {
+ m->real_oneof_count = m->oneof_count;
+ } else {
+ m->real_oneof_count = first_synthetic;
+ }
+
return true;
}
@@ -3260,7 +3351,7 @@
}
int upb_enumdef_numvals(const upb_enumdef *e) {
- return upb_strtable_count(&e->ntoi);
+ return (int)upb_strtable_count(&e->ntoi);
}
void upb_enum_begin(upb_enum_iter *i, const upb_enumdef *e) {
@@ -3288,7 +3379,7 @@
}
const char *upb_enum_iter_name(upb_enum_iter *iter) {
- return upb_strtable_iter_key(iter);
+ return upb_strtable_iter_key(iter).data;
}
int32_t upb_enum_iter_number(upb_enum_iter *iter) {
@@ -3369,47 +3460,16 @@
return shortdefname(f->full_name);
}
+const char *upb_fielddef_jsonname(const upb_fielddef *f) {
+ return f->json_name;
+}
+
uint32_t upb_fielddef_selectorbase(const upb_fielddef *f) {
return f->selector_base;
}
-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_filedef *upb_fielddef_file(const upb_fielddef *f) {
+ return f->file;
}
const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
@@ -3420,6 +3480,11 @@
return f->oneof;
}
+const upb_oneofdef *upb_fielddef_realcontainingoneof(const upb_fielddef *f) {
+ if (!f->oneof || upb_oneofdef_issynthetic(f->oneof)) return NULL;
+ return f->oneof;
+}
+
static void chkdefaulttype(const upb_fielddef *f, int ctype) {
UPB_UNUSED(f);
UPB_UNUSED(ctype);
@@ -3432,7 +3497,7 @@
int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
chkdefaulttype(f, UPB_TYPE_INT32);
- return f->defaultval.sint;
+ return (int32_t)f->defaultval.sint;
}
uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f) {
@@ -3442,7 +3507,7 @@
uint32_t upb_fielddef_defaultuint32(const upb_fielddef *f) {
chkdefaulttype(f, UPB_TYPE_UINT32);
- return f->defaultval.uint;
+ return (uint32_t)f->defaultval.uint;
}
bool upb_fielddef_defaultbool(const upb_fielddef *f) {
@@ -3484,6 +3549,10 @@
return f->sub.enumdef;
}
+const upb_msglayout_field *upb_fielddef_layout(const upb_fielddef *f) {
+ return &f->msgdef->layout->fields[f->layout_index];
+}
+
bool upb_fielddef_issubmsg(const upb_fielddef *f) {
return upb_fielddef_type(f) == UPB_TYPE_MESSAGE;
}
@@ -3512,8 +3581,8 @@
bool upb_fielddef_haspresence(const upb_fielddef *f) {
if (upb_fielddef_isseq(f)) return false;
- if (upb_fielddef_issubmsg(f)) return true;
- return f->file->syntax == UPB_SYNTAX_PROTO2;
+ return upb_fielddef_issubmsg(f) || upb_fielddef_containingoneof(f) ||
+ f->file->syntax == UPB_SYNTAX_PROTO2;
}
static bool between(int32_t x, int32_t low, int32_t high) {
@@ -3592,18 +3661,43 @@
*o = unpack_def(val, UPB_DEFTYPE_ONEOF);
*f = unpack_def(val, UPB_DEFTYPE_FIELD);
- UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
- return true;
+ return *o || *f; /* False if this was a JSON name. */
+}
+
+const upb_fielddef *upb_msgdef_lookupjsonname(const upb_msgdef *m,
+ const char *name, size_t len) {
+ upb_value val;
+ const upb_fielddef* f;
+
+ if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
+ return NULL;
+ }
+
+ f = unpack_def(val, UPB_DEFTYPE_FIELD);
+ if (!f) f = unpack_def(val, UPB_DEFTYPE_FIELD_JSONNAME);
+
+ return f;
}
int upb_msgdef_numfields(const upb_msgdef *m) {
- /* The number table contains only fields. */
- return upb_inttable_count(&m->itof);
+ return m->field_count;
}
int upb_msgdef_numoneofs(const upb_msgdef *m) {
- /* The name table includes oneofs, and the number table does not. */
- return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
+ return m->oneof_count;
+}
+
+int upb_msgdef_numrealoneofs(const upb_msgdef *m) {
+ return m->real_oneof_count;
+}
+
+const upb_msglayout *upb_msgdef_layout(const upb_msgdef *m) {
+ return m->layout;
+}
+
+const upb_fielddef *_upb_msgdef_field(const upb_msgdef *m, int i) {
+ if (i >= m->field_count) return NULL;
+ return &m->fields[i];
}
bool upb_msgdef_mapentry(const upb_msgdef *m) {
@@ -3688,13 +3782,23 @@
}
int upb_oneofdef_numfields(const upb_oneofdef *o) {
- return upb_strtable_count(&o->ntof);
+ return (int)upb_strtable_count(&o->ntof);
}
uint32_t upb_oneofdef_index(const upb_oneofdef *o) {
return o->index;
}
+bool upb_oneofdef_issynthetic(const upb_oneofdef *o) {
+ upb_inttable_iter iter;
+ const upb_fielddef *f;
+ upb_inttable_begin(&iter, &o->itof);
+ if (upb_oneofdef_numfields(o) != 1) return false;
+ f = upb_value_getptr(upb_inttable_iter_value(&iter));
+ UPB_ASSERT(f);
+ return f->proto3_optional_;
+}
+
const upb_fielddef *upb_oneofdef_ntof(const upb_oneofdef *o,
const char *name, size_t length) {
upb_value val;
@@ -3728,6 +3832,224 @@
upb_inttable_iter_setdone(iter);
}
+/* Dynamic Layout Generation. *************************************************/
+
+static bool is_power_of_two(size_t val) {
+ return (val & (val - 1)) == 0;
+}
+
+/* Align up to the given power of 2. */
+static size_t align_up(size_t val, size_t align) {
+ UPB_ASSERT(is_power_of_two(align));
+ return (val + align - 1) & ~(align - 1);
+}
+
+static size_t div_round_up(size_t n, size_t d) {
+ return (n + d - 1) / d;
+}
+
+static size_t upb_msgval_sizeof(upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_DOUBLE:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ return 8;
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_FLOAT:
+ return 4;
+ case UPB_TYPE_BOOL:
+ return 1;
+ case UPB_TYPE_MESSAGE:
+ return sizeof(void*);
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_STRING:
+ return sizeof(upb_strview);
+ }
+ UPB_UNREACHABLE();
+}
+
+static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
+ if (upb_msgdef_mapentry(upb_fielddef_containingtype(f))) {
+ upb_map_entry ent;
+ UPB_ASSERT(sizeof(ent.k) == sizeof(ent.v));
+ return sizeof(ent.k);
+ } else if (upb_fielddef_isseq(f)) {
+ return sizeof(void*);
+ } else {
+ return upb_msgval_sizeof(upb_fielddef_type(f));
+ }
+}
+
+static uint32_t upb_msglayout_place(upb_msglayout *l, size_t size) {
+ uint32_t ret;
+
+ l->size = align_up(l->size, size);
+ ret = l->size;
+ l->size += size;
+ return ret;
+}
+
+/* This function is the dynamic equivalent of message_layout.{cc,h} in upbc.
+ * It computes a dynamic layout for all of the fields in |m|. */
+static bool make_layout(const upb_symtab *symtab, const upb_msgdef *m) {
+ upb_msglayout *l = (upb_msglayout*)m->layout;
+ upb_msg_field_iter it;
+ upb_msg_oneof_iter oit;
+ size_t hasbit;
+ size_t submsg_count = m->submsg_field_count;
+ const upb_msglayout **submsgs;
+ upb_msglayout_field *fields;
+ upb_alloc *alloc = upb_arena_alloc(symtab->arena);
+
+ memset(l, 0, sizeof(*l));
+
+ fields = upb_malloc(alloc, upb_msgdef_numfields(m) * sizeof(*fields));
+ submsgs = upb_malloc(alloc, submsg_count * sizeof(*submsgs));
+
+ if ((!fields && upb_msgdef_numfields(m)) ||
+ (!submsgs && submsg_count)) {
+ /* OOM. */
+ return false;
+ }
+
+ l->field_count = upb_msgdef_numfields(m);
+ l->fields = fields;
+ l->submsgs = submsgs;
+
+ if (upb_msgdef_mapentry(m)) {
+ /* TODO(haberman): refactor this method so this special case is more
+ * elegant. */
+ const upb_fielddef *key = upb_msgdef_itof(m, 1);
+ const upb_fielddef *val = upb_msgdef_itof(m, 2);
+ fields[0].number = 1;
+ fields[1].number = 2;
+ fields[0].label = UPB_LABEL_OPTIONAL;
+ fields[1].label = UPB_LABEL_OPTIONAL;
+ fields[0].presence = 0;
+ fields[1].presence = 0;
+ fields[0].descriptortype = upb_fielddef_descriptortype(key);
+ fields[1].descriptortype = upb_fielddef_descriptortype(val);
+ fields[0].offset = 0;
+ fields[1].offset = sizeof(upb_strview);
+ fields[1].submsg_index = 0;
+
+ if (upb_fielddef_type(val) == UPB_TYPE_MESSAGE) {
+ submsgs[0] = upb_fielddef_msgsubdef(val)->layout;
+ }
+
+ l->field_count = 2;
+ l->size = 2 * sizeof(upb_strview);align_up(l->size, 8);
+ return true;
+ }
+
+ /* Allocate data offsets in three stages:
+ *
+ * 1. hasbits.
+ * 2. regular fields.
+ * 3. oneof fields.
+ *
+ * OPT: There is a lot of room for optimization here to minimize the size.
+ */
+
+ /* Allocate hasbits and set basic field attributes. */
+ submsg_count = 0;
+ for (upb_msg_field_begin(&it, m), hasbit = 0;
+ !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ upb_fielddef* f = upb_msg_iter_field(&it);
+ upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
+
+ field->number = upb_fielddef_number(f);
+ field->descriptortype = upb_fielddef_descriptortype(f);
+ field->label = upb_fielddef_label(f);
+
+ if (upb_fielddef_ismap(f)) {
+ field->label = _UPB_LABEL_MAP;
+ } else if (upb_fielddef_packed(f)) {
+ field->label = _UPB_LABEL_PACKED;
+ }
+
+ /* TODO: we probably should sort the fields by field number to match the
+ * output of upbc, and to improve search speed for the table parser. */
+ f->layout_index = f->index_;
+
+ if (upb_fielddef_issubmsg(f)) {
+ const upb_msgdef *subm = upb_fielddef_msgsubdef(f);
+ field->submsg_index = submsg_count++;
+ submsgs[field->submsg_index] = subm->layout;
+ }
+
+ if (upb_fielddef_haspresence(f) && !upb_fielddef_realcontainingoneof(f)) {
+ /* We don't use hasbit 0, so that 0 can indicate "no presence" in the
+ * table. This wastes one hasbit, but we don't worry about it for now. */
+ field->presence = ++hasbit;
+ } else {
+ field->presence = 0;
+ }
+ }
+
+ /* Account for space used by hasbits. */
+ l->size = div_round_up(hasbit, 8);
+
+ /* Allocate non-oneof fields. */
+ for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
+ upb_msg_field_next(&it)) {
+ const upb_fielddef* f = upb_msg_iter_field(&it);
+ size_t field_size = upb_msg_fielddefsize(f);
+ size_t index = upb_fielddef_index(f);
+
+ if (upb_fielddef_realcontainingoneof(f)) {
+ /* Oneofs are handled separately below. */
+ continue;
+ }
+
+ fields[index].offset = upb_msglayout_place(l, field_size);
+ }
+
+ /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
+ * and space for the actual data. */
+ for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
+ upb_msg_oneof_next(&oit)) {
+ const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
+ upb_oneof_iter fit;
+
+ if (upb_oneofdef_issynthetic(o)) continue;
+
+ size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
+ size_t field_size = 0;
+ uint32_t case_offset;
+ uint32_t data_offset;
+
+ /* Calculate field size: the max of all field sizes. */
+ for (upb_oneof_begin(&fit, o);
+ !upb_oneof_done(&fit);
+ upb_oneof_next(&fit)) {
+ const upb_fielddef* f = upb_oneof_iter_field(&fit);
+ field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
+ }
+
+ /* Align and allocate case offset. */
+ case_offset = upb_msglayout_place(l, case_size);
+ data_offset = upb_msglayout_place(l, field_size);
+
+ for (upb_oneof_begin(&fit, o);
+ !upb_oneof_done(&fit);
+ upb_oneof_next(&fit)) {
+ const upb_fielddef* f = upb_oneof_iter_field(&fit);
+ fields[upb_fielddef_index(f)].offset = data_offset;
+ fields[upb_fielddef_index(f)].presence = ~case_offset;
+ }
+ }
+
+ /* Size of the entire structure should be a multiple of its greatest
+ * alignment. TODO: track overall alignment for real? */
+ l->size = align_up(l->size, 8);
+
+ return true;
+}
+
/* Code to build defs from descriptor protos. *********************************/
/* There is a question of how much validation to do here. It will be difficult
@@ -3740,11 +4062,12 @@
typedef struct {
const upb_symtab *symtab;
- upb_filedef *file; /* File we are building. */
- upb_alloc *alloc; /* Allocate defs here. */
- upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
- upb_strtable *addtab; /* full_name -> packed def ptr for new defs. */
- upb_status *status; /* Record errors here. */
+ upb_filedef *file; /* File we are building. */
+ upb_alloc *alloc; /* Allocate defs here. */
+ upb_alloc *tmp; /* Alloc for addtab and any other tmp data. */
+ upb_strtable *addtab; /* full_name -> packed def ptr for new defs */
+ const upb_msglayout **layouts; /* NULL if we should build layouts. */
+ upb_status *status; /* Record errors here. */
} symtab_addctx;
static char* strviewdup(const symtab_addctx *ctx, upb_strview view) {
@@ -3776,6 +4099,51 @@
}
}
+size_t getjsonname(const char *name, char *buf, size_t len) {
+ 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
+}
+
+static char* makejsonname(const char* name, upb_alloc *alloc) {
+ size_t size = getjsonname(name, NULL, 0);
+ char* json_name = upb_malloc(alloc, size);
+ getjsonname(name, json_name, size);
+ return json_name;
+}
+
static bool symtab_add(const symtab_addctx *ctx, const char *name,
upb_value v) {
upb_value tmp;
@@ -3899,7 +4267,7 @@
}
case UPB_TYPE_INT64: {
/* XXX: Need to write our own strtoll, since it's not available in c89. */
- long long val = strtol(str, &end, 0);
+ int64_t val = strtol(str, &end, 0);
CHK(val <= INT64_MAX && val >= INT64_MIN && errno != ERANGE && !*end);
f->defaultval.sint = val;
break;
@@ -3912,7 +4280,7 @@
}
case UPB_TYPE_UINT64: {
/* XXX: Need to write our own strtoull, since it's not available in c89. */
- unsigned long long val = strtoul(str, &end, 0);
+ uint64_t val = strtoul(str, &end, 0);
CHK(val <= UINT64_MAX && errno != ERANGE && !*end);
f->defaultval.uint = val;
break;
@@ -3989,6 +4357,7 @@
const google_protobuf_FieldOptions *options;
upb_strview name;
const char *full_name;
+ const char *json_name;
const char *shortname;
uint32_t field_number;
@@ -4002,6 +4371,13 @@
full_name = makefullname(ctx, prefix, name);
shortname = shortdefname(full_name);
+ if (google_protobuf_FieldDescriptorProto_has_json_name(field_proto)) {
+ json_name = strviewdup(
+ ctx, google_protobuf_FieldDescriptorProto_json_name(field_proto));
+ } else {
+ json_name = makejsonname(shortname, ctx->alloc);
+ }
+
field_number = google_protobuf_FieldDescriptorProto_number(field_proto);
if (field_number == 0 || field_number > UPB_MAX_FIELDNUMBER) {
@@ -4011,38 +4387,72 @@
if (m) {
/* direct message field. */
- upb_value v, packed_v;
+ upb_value v, field_v, json_v;
+ size_t json_size;
f = (upb_fielddef*)&m->fields[m->field_count++];
f->msgdef = m;
f->is_extension_ = false;
- packed_v = pack_def(f, UPB_DEFTYPE_FIELD);
- v = upb_value_constptr(f);
-
- if (!upb_strtable_insert3(&m->ntof, name.data, name.size, packed_v, alloc)) {
+ if (upb_strtable_lookup(&m->ntof, shortname, NULL)) {
upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname);
return false;
}
- if (!upb_inttable_insert2(&m->itof, field_number, v, alloc)) {
+ if (upb_strtable_lookup(&m->ntof, json_name, NULL)) {
+ upb_status_seterrf(ctx->status, "duplicate json_name (%s)", json_name);
+ return false;
+ }
+
+ if (upb_inttable_lookup(&m->itof, field_number, NULL)) {
upb_status_seterrf(ctx->status, "duplicate field number (%u)",
field_number);
return false;
}
+
+ field_v = pack_def(f, UPB_DEFTYPE_FIELD);
+ json_v = pack_def(f, UPB_DEFTYPE_FIELD_JSONNAME);
+ v = upb_value_constptr(f);
+ json_size = strlen(json_name);
+
+ CHK_OOM(
+ upb_strtable_insert3(&m->ntof, name.data, name.size, field_v, alloc));
+ CHK_OOM(upb_inttable_insert2(&m->itof, field_number, v, alloc));
+
+ if (strcmp(shortname, json_name) != 0) {
+ upb_strtable_insert3(&m->ntof, json_name, json_size, json_v, alloc);
+ }
+
+ if (ctx->layouts) {
+ const upb_msglayout_field *fields = m->layout->fields;
+ int count = m->layout->field_count;
+ bool found = false;
+ int i;
+ for (i = 0; i < count; i++) {
+ if (fields[i].number == field_number) {
+ f->layout_index = i;
+ found = true;
+ break;
+ }
+ }
+ UPB_ASSERT(found);
+ }
} else {
/* extension field. */
- f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count];
+ f = (upb_fielddef*)&ctx->file->exts[ctx->file->ext_count++];
f->is_extension_ = true;
CHK_OOM(symtab_add(ctx, full_name, pack_def(f, UPB_DEFTYPE_FIELD)));
}
f->full_name = full_name;
+ f->json_name = json_name;
f->file = ctx->file;
f->type_ = (int)google_protobuf_FieldDescriptorProto_type(field_proto);
f->label_ = (int)google_protobuf_FieldDescriptorProto_label(field_proto);
f->number_ = field_number;
f->oneof = NULL;
+ f->proto3_optional_ =
+ google_protobuf_FieldDescriptorProto_proto3_optional(field_proto);
/* We can't resolve the subdef or (in the case of extensions) the containing
* message yet, because it may not have been defined yet. We stash a pointer
@@ -4166,7 +4576,7 @@
return true;
}
-static bool create_msgdef(const symtab_addctx *ctx, const char *prefix,
+static bool create_msgdef(symtab_addctx *ctx, const char *prefix,
const google_protobuf_DescriptorProto *msg_proto) {
upb_msgdef *m;
const google_protobuf_MessageOptions *options;
@@ -4196,6 +4606,14 @@
m->map_entry = google_protobuf_MessageOptions_map_entry(options);
}
+ if (ctx->layouts) {
+ m->layout = *ctx->layouts;
+ ctx->layouts++;
+ } else {
+ /* Allocate now (to allow cross-linking), populate later. */
+ m->layout = upb_malloc(ctx->alloc, sizeof(*m->layout));
+ }
+
oneofs = google_protobuf_DescriptorProto_oneof_decl(msg_proto, &n);
m->oneof_count = 0;
m->oneofs = upb_malloc(ctx->alloc, sizeof(*m->oneofs) * n);
@@ -4211,6 +4629,7 @@
}
CHK(assign_msg_indices(m, ctx->status));
+ CHK(check_oneofs(m, ctx->status));
assign_msg_wellknowntype(m);
upb_inttable_compact2(&m->itof, ctx->alloc);
@@ -4342,7 +4761,7 @@
}
static bool build_filedef(
- const symtab_addctx *ctx, upb_filedef *file,
+ symtab_addctx *ctx, upb_filedef *file,
const google_protobuf_FileDescriptorProto *file_proto) {
upb_alloc *alloc = ctx->alloc;
const google_protobuf_FileOptions *file_options_proto;
@@ -4396,7 +4815,8 @@
} else if (streql_view(syntax, "proto3")) {
file->syntax = UPB_SYNTAX_PROTO3;
} else {
- upb_status_seterrf(ctx->status, "Invalid syntax '%s'", syntax);
+ upb_status_seterrf(ctx->status, "Invalid syntax '" UPB_STRVIEW_FORMAT "'",
+ UPB_STRVIEW_ARGS(syntax));
return false;
}
} else {
@@ -4456,7 +4876,7 @@
CHK(create_fielddef(ctx, file->package, NULL, exts[i]));
}
- /* Now that all names are in the table, resolve references. */
+ /* Now that all names are in the table, build layouts and resolve refs. */
for (i = 0; i < file->ext_count; i++) {
CHK(resolve_fielddef(ctx, file->package, (upb_fielddef*)&file->exts[i]));
}
@@ -4469,6 +4889,13 @@
}
}
+ if (!ctx->layouts) {
+ for (i = 0; i < file->msg_count; i++) {
+ const upb_msgdef *m = &file->msgs[i];
+ make_layout(ctx->symtab, m);
+ }
+ }
+
return true;
}
@@ -4483,10 +4910,9 @@
upb_strtable_begin(&iter, ctx->addtab);
for (; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- const char *key = upb_strtable_iter_key(&iter);
- size_t keylen = upb_strtable_iter_keylength(&iter);
+ upb_strview key = upb_strtable_iter_key(&iter);
upb_value value = upb_strtable_iter_value(&iter);
- CHK_OOM(upb_strtable_insert3(&s->syms, key, keylen, value, alloc));
+ CHK_OOM(upb_strtable_insert3(&s->syms, key.data, key.size, value, alloc));
}
return true;
@@ -4588,9 +5014,13 @@
: NULL;
}
-const upb_filedef *upb_symtab_addfile(
+int upb_symtab_filecount(const upb_symtab *s) {
+ return (int)upb_strtable_count(&s->files);
+}
+
+static const upb_filedef *_upb_symtab_addfile(
upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
- upb_status *status) {
+ const upb_msglayout **layouts, upb_status *status) {
upb_arena *tmparena = upb_arena_new();
upb_strtable addtab;
upb_alloc *alloc = upb_arena_alloc(s->arena);
@@ -4603,6 +5033,7 @@
ctx.alloc = alloc;
ctx.tmp = upb_arena_alloc(tmparena);
ctx.addtab = &addtab;
+ ctx.layouts = layouts;
ctx.status = status;
ok = file &&
@@ -4614,6 +5045,12 @@
return ok ? file : NULL;
}
+const upb_filedef *upb_symtab_addfile(
+ upb_symtab *s, const google_protobuf_FileDescriptorProto *file_proto,
+ upb_status *status) {
+ return _upb_symtab_addfile(s, file_proto, NULL, status);
+}
+
/* Include here since we want most of this file to be stdio-free. */
#include <stdio.h>
@@ -4649,7 +5086,7 @@
goto err;
}
- if (!upb_symtab_addfile(s, file, &status)) goto err;
+ if (!_upb_symtab_addfile(s, file, init->layouts, &status)) goto err;
upb_arena_free(arena);
return true;
@@ -4665,250 +5102,311 @@
#undef CHK_OOM
+#include <string.h>
-static bool is_power_of_two(size_t val) {
- return (val & (val - 1)) == 0;
+
+static char field_size[] = {
+ 0,/* 0 */
+ 8, /* UPB_DESCRIPTOR_TYPE_DOUBLE */
+ 4, /* UPB_DESCRIPTOR_TYPE_FLOAT */
+ 8, /* UPB_DESCRIPTOR_TYPE_INT64 */
+ 8, /* UPB_DESCRIPTOR_TYPE_UINT64 */
+ 4, /* UPB_DESCRIPTOR_TYPE_INT32 */
+ 8, /* UPB_DESCRIPTOR_TYPE_FIXED64 */
+ 4, /* UPB_DESCRIPTOR_TYPE_FIXED32 */
+ 1, /* UPB_DESCRIPTOR_TYPE_BOOL */
+ sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_STRING */
+ sizeof(void*), /* UPB_DESCRIPTOR_TYPE_GROUP */
+ sizeof(void*), /* UPB_DESCRIPTOR_TYPE_MESSAGE */
+ sizeof(upb_strview), /* UPB_DESCRIPTOR_TYPE_BYTES */
+ 4, /* UPB_DESCRIPTOR_TYPE_UINT32 */
+ 4, /* UPB_DESCRIPTOR_TYPE_ENUM */
+ 4, /* UPB_DESCRIPTOR_TYPE_SFIXED32 */
+ 8, /* UPB_DESCRIPTOR_TYPE_SFIXED64 */
+ 4, /* UPB_DESCRIPTOR_TYPE_SINT32 */
+ 8, /* UPB_DESCRIPTOR_TYPE_SINT64 */
+};
+
+/* Strings/bytes are special-cased in maps. */
+static char _upb_fieldtype_to_mapsize[12] = {
+ 0,
+ 1, /* UPB_TYPE_BOOL */
+ 4, /* UPB_TYPE_FLOAT */
+ 4, /* UPB_TYPE_INT32 */
+ 4, /* UPB_TYPE_UINT32 */
+ 4, /* UPB_TYPE_ENUM */
+ sizeof(void*), /* UPB_TYPE_MESSAGE */
+ 8, /* UPB_TYPE_DOUBLE */
+ 8, /* UPB_TYPE_INT64 */
+ 8, /* UPB_TYPE_UINT64 */
+ 0, /* UPB_TYPE_STRING */
+ 0, /* UPB_TYPE_BYTES */
+};
+
+/** upb_msg *******************************************************************/
+
+upb_msg *upb_msg_new(const upb_msgdef *m, upb_arena *a) {
+ return _upb_msg_new(upb_msgdef_layout(m), a);
}
-/* Align up to the given power of 2. */
-static size_t align_up(size_t val, size_t align) {
- UPB_ASSERT(is_power_of_two(align));
- return (val + align - 1) & ~(align - 1);
+static bool in_oneof(const upb_msglayout_field *field) {
+ return field->presence < 0;
}
-static size_t div_round_up(size_t n, size_t d) {
- return (n + d - 1) / d;
+static uint32_t *oneofcase(const upb_msg *msg,
+ const upb_msglayout_field *field) {
+ UPB_ASSERT(in_oneof(field));
+ return UPB_PTR_AT(msg, -field->presence, uint32_t);
}
-static size_t upb_msgval_sizeof2(upb_fieldtype_t type) {
- switch (type) {
- case UPB_TYPE_DOUBLE:
- case UPB_TYPE_INT64:
- case UPB_TYPE_UINT64:
- return 8;
- case UPB_TYPE_ENUM:
- case UPB_TYPE_INT32:
- case UPB_TYPE_UINT32:
- case UPB_TYPE_FLOAT:
- return 4;
- case UPB_TYPE_BOOL:
- return 1;
- case UPB_TYPE_MESSAGE:
- return sizeof(void*);
- case UPB_TYPE_BYTES:
- case UPB_TYPE_STRING:
- return sizeof(upb_strview);
- }
- UPB_UNREACHABLE();
+static upb_msgval _upb_msg_getraw(const upb_msg *msg, const upb_fielddef *f) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ const char *mem = UPB_PTR_AT(msg, field->offset, char);
+ upb_msgval val = {0};
+ int size = upb_fielddef_isseq(f) ? sizeof(void *)
+ : field_size[field->descriptortype];
+ memcpy(&val, mem, size);
+ return val;
}
-static uint8_t upb_msg_fielddefsize(const upb_fielddef *f) {
- if (upb_fielddef_isseq(f)) {
- return sizeof(void*);
+bool upb_msg_has(const upb_msg *msg, const upb_fielddef *f) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ if (in_oneof(field)) {
+ return *oneofcase(msg, field) == field->number;
+ } else if (field->presence > 0) {
+ uint32_t hasbit = field->presence;
+ return *UPB_PTR_AT(msg, hasbit / 8, uint8_t) & (1 << (hasbit % 8));
} else {
- return upb_msgval_sizeof2(upb_fielddef_type(f));
+ UPB_ASSERT(field->descriptortype == UPB_DESCRIPTOR_TYPE_MESSAGE ||
+ field->descriptortype == UPB_DESCRIPTOR_TYPE_GROUP);
+ return _upb_msg_getraw(msg, f).msg_val != NULL;
}
}
+bool upb_msg_hasoneof(const upb_msg *msg, const upb_oneofdef *o) {
+ upb_oneof_iter i;
+ const upb_fielddef *f;
+ const upb_msglayout_field *field;
-/** upb_msglayout *************************************************************/
-
-static void upb_msglayout_free(upb_msglayout *l) {
- upb_gfree(l);
+ upb_oneof_begin(&i, o);
+ if (upb_oneof_done(&i)) return false;
+ f = upb_oneof_iter_field(&i);
+ field = upb_fielddef_layout(f);
+ return *oneofcase(msg, field) != 0;
}
-static size_t upb_msglayout_place(upb_msglayout *l, size_t size) {
- size_t ret;
+upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f) {
+ if (!upb_fielddef_haspresence(f) || upb_msg_has(msg, f)) {
+ return _upb_msg_getraw(msg, f);
+ } else {
+ /* TODO(haberman): change upb_fielddef to not require this switch(). */
+ upb_msgval val = {0};
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_ENUM:
+ val.int32_val = upb_fielddef_defaultint32(f);
+ break;
+ case UPB_TYPE_INT64:
+ val.int64_val = upb_fielddef_defaultint64(f);
+ break;
+ case UPB_TYPE_UINT32:
+ val.uint32_val = upb_fielddef_defaultuint32(f);
+ break;
+ case UPB_TYPE_UINT64:
+ val.uint64_val = upb_fielddef_defaultuint64(f);
+ break;
+ case UPB_TYPE_FLOAT:
+ val.float_val = upb_fielddef_defaultfloat(f);
+ break;
+ case UPB_TYPE_DOUBLE:
+ val.double_val = upb_fielddef_defaultdouble(f);
+ break;
+ case UPB_TYPE_BOOL:
+ val.double_val = upb_fielddef_defaultbool(f);
+ break;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ val.str_val.data = upb_fielddef_defaultstr(f, &val.str_val.size);
+ break;
+ case UPB_TYPE_MESSAGE:
+ val.msg_val = NULL;
+ break;
+ }
+ return val;
+ }
+}
- l->size = align_up(l->size, size);
- ret = l->size;
- l->size += size;
+upb_mutmsgval upb_msg_mutable(upb_msg *msg, const upb_fielddef *f,
+ upb_arena *a) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ upb_mutmsgval ret;
+ char *mem = UPB_PTR_AT(msg, field->offset, char);
+ bool wrong_oneof = in_oneof(field) && *oneofcase(msg, field) != field->number;
+
+ memcpy(&ret, mem, sizeof(void*));
+
+ if (a && (!ret.msg || wrong_oneof)) {
+ if (upb_fielddef_ismap(f)) {
+ const upb_msgdef *entry = upb_fielddef_msgsubdef(f);
+ const upb_fielddef *key = upb_msgdef_itof(entry, UPB_MAPENTRY_KEY);
+ const upb_fielddef *value = upb_msgdef_itof(entry, UPB_MAPENTRY_VALUE);
+ ret.map = upb_map_new(a, upb_fielddef_type(key), upb_fielddef_type(value));
+ } else if (upb_fielddef_isseq(f)) {
+ ret.array = upb_array_new(a, upb_fielddef_type(f));
+ } else {
+ UPB_ASSERT(upb_fielddef_issubmsg(f));
+ ret.msg = upb_msg_new(upb_fielddef_msgsubdef(f), a);
+ }
+
+ memcpy(mem, &ret, sizeof(void*));
+
+ if (wrong_oneof) {
+ *oneofcase(msg, field) = field->number;
+ }
+ }
return ret;
}
-static bool upb_msglayout_init(const upb_msgdef *m,
- upb_msglayout *l,
- upb_msgfactory *factory) {
- upb_msg_field_iter it;
- upb_msg_oneof_iter oit;
- size_t hasbit;
- size_t submsg_count = 0;
- const upb_msglayout **submsgs;
- upb_msglayout_field *fields;
-
- for (upb_msg_field_begin(&it, m);
- !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* f = upb_msg_iter_field(&it);
- if (upb_fielddef_issubmsg(f)) {
- submsg_count++;
- }
+void upb_msg_set(upb_msg *msg, const upb_fielddef *f, upb_msgval val,
+ upb_arena *a) {
+ const upb_msglayout_field *field = upb_fielddef_layout(f);
+ char *mem = UPB_PTR_AT(msg, field->offset, char);
+ int size = upb_fielddef_isseq(f) ? sizeof(void *)
+ : field_size[field->descriptortype];
+ memcpy(mem, &val, size);
+ if (in_oneof(field)) {
+ *oneofcase(msg, field) = field->number;
}
+}
- memset(l, 0, sizeof(*l));
+bool upb_msg_next(const upb_msg *msg, const upb_msgdef *m,
+ const upb_symtab *ext_pool, const upb_fielddef **out_f,
+ upb_msgval *out_val, size_t *iter) {
+ size_t i = *iter;
+ const upb_msgval zero = {0};
+ const upb_fielddef *f;
+ while ((f = _upb_msgdef_field(m, (int)++i)) != NULL) {
+ upb_msgval val = _upb_msg_getraw(msg, f);
- fields = upb_gmalloc(upb_msgdef_numfields(m) * sizeof(*fields));
- submsgs = upb_gmalloc(submsg_count * sizeof(*submsgs));
+ /* Skip field if unset or empty. */
+ if (upb_fielddef_haspresence(f)) {
+ if (!upb_msg_has(msg, f)) continue;
+ } else {
+ upb_msgval test = val;
+ if (upb_fielddef_isstring(f) && !upb_fielddef_isseq(f)) {
+ /* Clear string pointer, only size matters (ptr could be non-NULL). */
+ test.str_val.data = NULL;
+ }
+ /* Continue if NULL or 0. */
+ if (memcmp(&test, &zero, sizeof(test)) == 0) continue;
- if ((!fields && upb_msgdef_numfields(m)) ||
- (!submsgs && submsg_count)) {
- /* OOM. */
- upb_gfree(fields);
- upb_gfree(submsgs);
+ /* Continue on empty array or map. */
+ if (upb_fielddef_ismap(f)) {
+ if (upb_map_size(test.map_val) == 0) continue;
+ } else if (upb_fielddef_isseq(f)) {
+ if (upb_array_size(test.array_val) == 0) continue;
+ }
+ }
+
+ *out_val = val;
+ *out_f = f;
+ *iter = i;
+ return true;
+ }
+ *iter = i;
+ return false;
+}
+
+/** upb_array *****************************************************************/
+
+upb_array *upb_array_new(upb_arena *a, upb_fieldtype_t type) {
+ return _upb_array_new(a, type);
+}
+
+size_t upb_array_size(const upb_array *arr) {
+ return arr->len;
+}
+
+upb_msgval upb_array_get(const upb_array *arr, size_t i) {
+ upb_msgval ret;
+ const char* data = _upb_array_constptr(arr);
+ int lg2 = arr->data & 7;
+ UPB_ASSERT(i < arr->len);
+ memcpy(&ret, data + (i << lg2), 1 << lg2);
+ return ret;
+}
+
+void upb_array_set(upb_array *arr, size_t i, upb_msgval val) {
+ char* data = _upb_array_ptr(arr);
+ int lg2 = arr->data & 7;
+ UPB_ASSERT(i < arr->len);
+ memcpy(data + (i << lg2), &val, 1 << lg2);
+}
+
+bool upb_array_append(upb_array *arr, upb_msgval val, upb_arena *arena) {
+ if (!_upb_array_realloc(arr, arr->len + 1, arena)) {
return false;
}
-
- l->field_count = upb_msgdef_numfields(m);
- l->fields = fields;
- l->submsgs = submsgs;
-
- /* Allocate data offsets in three stages:
- *
- * 1. hasbits.
- * 2. regular fields.
- * 3. oneof fields.
- *
- * OPT: There is a lot of room for optimization here to minimize the size.
- */
-
- /* Allocate hasbits and set basic field attributes. */
- submsg_count = 0;
- for (upb_msg_field_begin(&it, m), hasbit = 0;
- !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* f = upb_msg_iter_field(&it);
- upb_msglayout_field *field = &fields[upb_fielddef_index(f)];
-
- field->number = upb_fielddef_number(f);
- field->descriptortype = upb_fielddef_descriptortype(f);
- field->label = upb_fielddef_label(f);
-
- if (upb_fielddef_issubmsg(f)) {
- const upb_msglayout *sub_layout =
- upb_msgfactory_getlayout(factory, upb_fielddef_msgsubdef(f));
- field->submsg_index = submsg_count++;
- submsgs[field->submsg_index] = sub_layout;
- }
-
- if (upb_fielddef_haspresence(f) && !upb_fielddef_containingoneof(f)) {
- field->presence = (hasbit++);
- } else {
- field->presence = 0;
- }
- }
-
- /* Account for space used by hasbits. */
- l->size = div_round_up(hasbit, 8);
-
- /* Allocate non-oneof fields. */
- for (upb_msg_field_begin(&it, m); !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* f = upb_msg_iter_field(&it);
- size_t field_size = upb_msg_fielddefsize(f);
- size_t index = upb_fielddef_index(f);
-
- if (upb_fielddef_containingoneof(f)) {
- /* Oneofs are handled separately below. */
- continue;
- }
-
- fields[index].offset = upb_msglayout_place(l, field_size);
- }
-
- /* Allocate oneof fields. Each oneof field consists of a uint32 for the case
- * and space for the actual data. */
- for (upb_msg_oneof_begin(&oit, m); !upb_msg_oneof_done(&oit);
- upb_msg_oneof_next(&oit)) {
- const upb_oneofdef* o = upb_msg_iter_oneof(&oit);
- upb_oneof_iter fit;
-
- size_t case_size = sizeof(uint32_t); /* Could potentially optimize this. */
- size_t field_size = 0;
- uint32_t case_offset;
- uint32_t data_offset;
-
- /* Calculate field size: the max of all field sizes. */
- for (upb_oneof_begin(&fit, o);
- !upb_oneof_done(&fit);
- upb_oneof_next(&fit)) {
- const upb_fielddef* f = upb_oneof_iter_field(&fit);
- field_size = UPB_MAX(field_size, upb_msg_fielddefsize(f));
- }
-
- /* Align and allocate case offset. */
- case_offset = upb_msglayout_place(l, case_size);
- data_offset = upb_msglayout_place(l, field_size);
-
- for (upb_oneof_begin(&fit, o);
- !upb_oneof_done(&fit);
- upb_oneof_next(&fit)) {
- const upb_fielddef* f = upb_oneof_iter_field(&fit);
- fields[upb_fielddef_index(f)].offset = data_offset;
- fields[upb_fielddef_index(f)].presence = ~case_offset;
- }
- }
-
- /* Size of the entire structure should be a multiple of its greatest
- * alignment. TODO: track overall alignment for real? */
- l->size = align_up(l->size, 8);
-
+ arr->len++;
+ upb_array_set(arr, arr->len - 1, val);
return true;
}
+/* Resizes the array to the given size, reallocating if necessary, and returns a
+ * pointer to the new array elements. */
+bool upb_array_resize(upb_array *arr, size_t size, upb_arena *arena) {
+ return _upb_array_realloc(arr, size, arena);
+}
-/** upb_msgfactory ************************************************************/
+/** upb_map *******************************************************************/
-struct upb_msgfactory {
- const upb_symtab *symtab; /* We own a ref. */
- upb_inttable layouts;
-};
+upb_map *upb_map_new(upb_arena *a, upb_fieldtype_t key_type,
+ upb_fieldtype_t value_type) {
+ return _upb_map_new(a, _upb_fieldtype_to_mapsize[key_type],
+ _upb_fieldtype_to_mapsize[value_type]);
+}
-upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab) {
- upb_msgfactory *ret = upb_gmalloc(sizeof(*ret));
+size_t upb_map_size(const upb_map *map) {
+ return _upb_map_size(map);
+}
- ret->symtab = symtab;
- upb_inttable_init(&ret->layouts, UPB_CTYPE_PTR);
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val) {
+ return _upb_map_get(map, &key, map->key_size, val, map->val_size);
+}
+bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
+ upb_arena *arena) {
+ return _upb_map_set(map, &key, map->key_size, &val, map->val_size, arena);
+}
+
+bool upb_map_delete(upb_map *map, upb_msgval key) {
+ return _upb_map_delete(map, &key, map->key_size);
+}
+
+bool upb_mapiter_next(const upb_map *map, size_t *iter) {
+ return _upb_map_next(map, iter);
+}
+
+/* Returns the key and value for this entry of the map. */
+upb_msgval upb_mapiter_key(const upb_map *map, size_t iter) {
+ upb_strtable_iter i;
+ upb_msgval ret;
+ i.t = &map->table;
+ i.index = iter;
+ _upb_map_fromkey(upb_strtable_iter_key(&i), &ret, map->key_size);
return ret;
}
-void upb_msgfactory_free(upb_msgfactory *f) {
- upb_inttable_iter i;
- upb_inttable_begin(&i, &f->layouts);
- for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
- upb_msglayout *l = upb_value_getptr(upb_inttable_iter_value(&i));
- upb_msglayout_free(l);
- }
-
- upb_inttable_uninit(&f->layouts);
- upb_gfree(f);
+upb_msgval upb_mapiter_value(const upb_map *map, size_t iter) {
+ upb_strtable_iter i;
+ upb_msgval ret;
+ i.t = &map->table;
+ i.index = iter;
+ _upb_map_fromvalue(upb_strtable_iter_value(&i), &ret, map->val_size);
+ return ret;
}
-const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f) {
- return f->symtab;
-}
-
-const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
- const upb_msgdef *m) {
- upb_value v;
- UPB_ASSERT(upb_symtab_lookupmsg(f->symtab, upb_msgdef_fullname(m)) == m);
- UPB_ASSERT(!upb_msgdef_mapentry(m));
-
- if (upb_inttable_lookupptr(&f->layouts, m, &v)) {
- UPB_ASSERT(upb_value_getptr(v));
- return upb_value_getptr(v);
- } else {
- /* In case of circular dependency, layout has to be inserted first. */
- upb_msglayout *l = upb_gmalloc(sizeof(*l));
- upb_msgfactory *mutable_f = (void*)f;
- upb_inttable_insertptr(&mutable_f->layouts, m, upb_value_ptr(l));
- UPB_ASSERT(l);
- if (!upb_msglayout_init(m, l, f)) {
- upb_msglayout_free(l);
- }
- return l;
- }
-}
+/* void upb_mapiter_setvalue(upb_map *map, size_t iter, upb_msgval value); */
/*
** TODO(haberman): it's unclear whether a lot of the consistency checks should
** UPB_ASSERT() or return false.
@@ -5088,7 +5586,8 @@
int extra;
upb_handlers *h;
- extra = sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1);
+ extra =
+ (int)(sizeof(upb_handlers_tabent) * (upb_msgdef_selectorcount(md) - 1));
h = upb_calloc(arena, sizeof(*h) + extra);
if (!h) return NULL;
@@ -5489,6 +5988,31 @@
}
return ret;
}
+
+
+#ifdef UPB_MSVC_VSNPRINTF
+/* Visual C++ earlier than 2015 doesn't have standard C99 snprintf and
+ * vsnprintf. To support them, missing functions are manually implemented
+ * using the existing secure functions. */
+int msvc_vsnprintf(char* s, size_t n, const char* format, va_list arg) {
+ if (!s) {
+ return _vscprintf(format, arg);
+ }
+ int ret = _vsnprintf_s(s, n, _TRUNCATE, format, arg);
+ if (ret < 0) {
+ ret = _vscprintf(format, arg);
+ }
+ return ret;
+}
+
+int msvc_snprintf(char* s, size_t n, const char* format, ...) {
+ va_list arg;
+ va_start(arg, format);
+ int ret = msvc_vsnprintf(s, n, format, arg);
+ va_end(arg);
+ return ret;
+}
+#endif
/*
** protobuf decoder bytecode compiler
**
@@ -5644,7 +6168,9 @@
UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
}
-static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
+static uint32_t pcofs(compiler *c) {
+ return (uint32_t)(c->pc - c->group->bytecode);
+}
/* Defines a local label at the current PC location. All previous forward
* references are updated to point to this location. The location is noted
@@ -5658,7 +6184,7 @@
codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
while (codep) {
int ofs = getofs(*codep);
- setofs(codep, c->pc - codep - instruction_len(*codep));
+ setofs(codep, (int32_t)(c->pc - codep - instruction_len(*codep)));
codep = ofs ? codep + ofs : NULL;
}
c->fwd_labels[label] = EMPTYLABEL;
@@ -5680,7 +6206,7 @@
return 0;
} else if (label < 0) {
/* Backward local label. Relative to the next instruction. */
- uint32_t from = (c->pc + 1) - c->group->bytecode;
+ uint32_t from = (uint32_t)((c->pc + 1) - c->group->bytecode);
return c->back_labels[-label] - from;
} else {
/* Forward local label: prepend to (possibly-empty) linked list. */
@@ -5714,7 +6240,7 @@
case OP_SETDISPATCH: {
uintptr_t ptr = (uintptr_t)va_arg(ap, void*);
put32(c, OP_SETDISPATCH);
- put32(c, ptr);
+ put32(c, (uint32_t)ptr);
if (sizeof(uintptr_t) > sizeof(uint32_t))
put32(c, (uint64_t)ptr >> 32);
break;
@@ -5773,7 +6299,7 @@
case OP_TAG2: {
int label = va_arg(ap, int);
uint64_t tag = va_arg(ap, uint64_t);
- uint32_t instruction = op | (tag << 16);
+ uint32_t instruction = (uint32_t)(op | (tag << 16));
UPB_ASSERT(tag <= 0xffff);
setofs(&instruction, labelref(c, label));
put32(c, instruction);
@@ -5785,7 +6311,7 @@
uint32_t instruction = op | (upb_value_size(tag) << 16);
setofs(&instruction, labelref(c, label));
put32(c, instruction);
- put32(c, tag);
+ put32(c, (uint32_t)tag);
put32(c, tag >> 32);
break;
}
@@ -6398,11 +6924,11 @@
} else {
g = mgroup_new(h, c->lazy);
ok = upb_inttable_insertptr(&c->groups, md, upb_value_constptr(g));
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
}
ok = upb_inttable_lookupptr(&g->methods, h, &v);
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
return upb_value_getptr(v);
}
/*
@@ -6589,7 +7115,7 @@
UPB_ASSERT(d->skip == 0);
if (bytes > delim_remaining(d)) {
seterr(d, "Skipped value extended beyond enclosing submessage.");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
} else if (bufleft(d) >= bytes) {
/* Skipped data is all in current buffer, and more is still available. */
advance(d, bytes);
@@ -6602,7 +7128,7 @@
d->bufstart_ofs += (d->end - d->buf);
d->residual_end = d->residual;
switchtobuf(d, d->residual, d->residual_end);
- return d->size_param + d->skip;
+ return (int32_t)(d->size_param + d->skip);
}
}
@@ -6642,7 +7168,7 @@
/* 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);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
if (d->residual_end > d->residual) {
@@ -6752,9 +7278,9 @@
return DECODE_OK;
} else if (d->data_end == d->delim_end) {
seterr(d, "Submessage ended in the middle of a value or group");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
} else {
- return suspend_save(d);
+ return (int32_t)suspend_save(d);
}
}
@@ -6810,7 +7336,7 @@
}
if(bitpos == 70 && (byte & 0x80)) {
seterr(d, kUnterminatedVarint);
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
return DECODE_OK;
}
@@ -6827,7 +7353,7 @@
upb_decoderet r = upb_vdecode_fast(d->ptr);
if (r.p == NULL) {
seterr(d, kUnterminatedVarint);
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
advance(d, r.p - d->ptr);
*u64 = r.val;
@@ -6851,9 +7377,9 @@
* Right now the size_t -> int32_t can overflow and produce negative values.
*/
*u32 = 0;
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
- *u32 = u64;
+ *u32 = (uint32_t)u64;
return DECODE_OK;
}
@@ -6929,7 +7455,7 @@
UPB_ASSERT(ok < 0);
return DECODE_OK;
} else if (read < bytes && memcmp(&data, &expected, read) == 0) {
- return suspend_save(d);
+ return (int32_t)suspend_save(d);
} else {
return DECODE_MISMATCH;
}
@@ -6949,7 +7475,7 @@
have_tag:
if (fieldnum == 0) {
seterr(d, "Saw invalid field number (0)");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
switch (wire_type) {
@@ -6971,7 +7497,9 @@
break;
}
case UPB_WIRE_TYPE_START_GROUP:
- CHECK_SUSPEND(pushtagdelim(d, -fieldnum));
+ if (!pushtagdelim(d, -fieldnum)) {
+ return (int32_t)upb_pbdecoder_suspend(d);
+ }
break;
case UPB_WIRE_TYPE_END_GROUP:
if (fieldnum == -d->top->groupnum) {
@@ -6980,12 +7508,12 @@
return DECODE_ENDGROUP;
} else {
seterr(d, "Unmatched ENDGROUP tag.");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
break;
default:
seterr(d, "Invalid wire type");
- return upb_pbdecoder_suspend(d);
+ return (int32_t)upb_pbdecoder_suspend(d);
}
if (d->top->groupnum >= 0) {
@@ -7153,10 +7681,11 @@
CHECK_SUSPEND(upb_sink_startsubmsg(outer->sink, arg, &d->top->sink));
)
VMCASE(OP_ENDSUBMSG,
- CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, arg));
+ upb_sink subsink = (d->top + 1)->sink;
+ CHECK_SUSPEND(upb_sink_endsubmsg(d->top->sink, subsink, arg));
)
VMCASE(OP_STARTSTR,
- uint32_t len = delim_remaining(d);
+ uint32_t len = (uint32_t)delim_remaining(d);
upb_pbdecoder_frame *outer = outer_frame(d);
CHECK_SUSPEND(upb_sink_startstr(outer->sink, arg, len, &d->top->sink));
if (len == 0) {
@@ -7164,7 +7693,7 @@
}
)
VMCASE(OP_STRING,
- uint32_t len = curbufleft(d);
+ uint32_t len = (uint32_t)curbufleft(d);
size_t n = upb_sink_putstring(d->top->sink, arg, d->ptr, len, handle);
if (n > len) {
if (n > delim_remaining(d)) {
@@ -7699,7 +8228,7 @@
e->runbegin = e->ptr;
}
- *e->top = e->segptr - e->segbuf;
+ *e->top = (int)(e->segptr - e->segbuf);
e->segptr->seglen = 0;
e->segptr->msglen = 0;
@@ -8819,7 +9348,7 @@
upb_handlertype_t type) {
upb_selector_t sel;
bool ok = upb_handlers_getselector(p->top->f, type, &sel);
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
return sel;
}
@@ -8844,7 +9373,7 @@
const upb_json_parsermethod *method;
ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
- UPB_ASSERT(ok);
+ UPB_ASSUME(ok);
method = upb_value_getconstptr(v);
frame->name_table = &method->name_table;
@@ -9163,7 +9692,7 @@
/* Note: this invalidates the accumulate buffer! Call only after reading its
* contents. */
static void multipart_end(upb_json_parser *p) {
- UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
+ /* UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE); */
p->multipart_state = MULTIPART_INACTIVE;
accumulate_clear(p);
}
@@ -9398,7 +9927,7 @@
} else if (val > INT32_MAX || val < INT32_MIN) {
return false;
} else {
- upb_sink_putint32(p->top->sink, parser_getsel(p), val);
+ upb_sink_putint32(p->top->sink, parser_getsel(p), (int32_t)val);
return true;
}
}
@@ -9409,7 +9938,7 @@
} else if (val > UINT32_MAX || errno == ERANGE) {
return false;
} else {
- upb_sink_putuint32(p->top->sink, parser_getsel(p), val);
+ upb_sink_putuint32(p->top->sink, parser_getsel(p), (uint32_t)val);
return true;
}
}
@@ -10117,14 +10646,18 @@
capture_begin(p, ptr);
}
+static int div_round_up2(int n, int d) {
+ return (n + d - 1) / d;
+}
+
/* epoch_days(1970, 1, 1) == 1970-01-01 == 0. */
static int epoch_days(int year, int month, int day) {
static const uint16_t month_yday[12] = {0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334};
int febs_since_0 = month > 2 ? year + 1 : year;
- int leap_days_since_0 = div_round_up(febs_since_0, 4) -
- div_round_up(febs_since_0, 100) +
- div_round_up(febs_since_0, 400);
+ int leap_days_since_0 = div_round_up2(febs_since_0, 4) -
+ div_round_up2(febs_since_0, 100) +
+ div_round_up2(febs_since_0, 400);
int days_since_0 =
365 * year + month_yday[month - 1] + (day - 1) + leap_days_since_0;
@@ -10445,8 +10978,8 @@
/* send ENDSUBMSG in repeated-field-of-mapentries frame. */
p->top--;
ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
- UPB_ASSERT(ok);
- upb_sink_endsubmsg(p->top->sink, sel);
+ UPB_ASSUME(ok);
+ upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
}
p->top->f = NULL;
@@ -10560,7 +11093,7 @@
p->top--;
if (!is_unknown) {
sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
- upb_sink_endsubmsg(p->top->sink, sel);
+ upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
}
}
}
@@ -10999,11 +11532,11 @@
* final state once, when the closing '"' is seen. */
-#line 2794 "upb/json/parser.rl"
+#line 2780 "upb/json/parser.rl"
-#line 2597 "upb/json/parser.c"
+#line 2583 "upb/json/parser.c"
static const char _json_actions[] = {
0, 1, 0, 1, 1, 1, 3, 1,
4, 1, 6, 1, 7, 1, 8, 1,
@@ -11258,7 +11791,7 @@
static const int json_en_main = 1;
-#line 2797 "upb/json/parser.rl"
+#line 2783 "upb/json/parser.rl"
size_t parse(void *closure, const void *hd, const char *buf, size_t size,
const upb_bufhandle *handle) {
@@ -11281,7 +11814,7 @@
capture_resume(parser, buf);
-#line 2875 "upb/json/parser.c"
+#line 2861 "upb/json/parser.c"
{
int _klen;
unsigned int _trans;
@@ -11356,147 +11889,147 @@
switch ( *_acts++ )
{
case 1:
-#line 2602 "upb/json/parser.rl"
+#line 2588 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 2:
-#line 2604 "upb/json/parser.rl"
+#line 2590 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 23;goto _again;} }
break;
case 3:
-#line 2608 "upb/json/parser.rl"
+#line 2594 "upb/json/parser.rl"
{ start_text(parser, p); }
break;
case 4:
-#line 2609 "upb/json/parser.rl"
+#line 2595 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_text(parser, p)); }
break;
case 5:
-#line 2615 "upb/json/parser.rl"
+#line 2601 "upb/json/parser.rl"
{ start_hex(parser); }
break;
case 6:
-#line 2616 "upb/json/parser.rl"
+#line 2602 "upb/json/parser.rl"
{ hexdigit(parser, p); }
break;
case 7:
-#line 2617 "upb/json/parser.rl"
+#line 2603 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_hex(parser)); }
break;
case 8:
-#line 2623 "upb/json/parser.rl"
+#line 2609 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(escape(parser, p)); }
break;
case 9:
-#line 2629 "upb/json/parser.rl"
+#line 2615 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 10:
-#line 2634 "upb/json/parser.rl"
+#line 2620 "upb/json/parser.rl"
{ start_year(parser, p); }
break;
case 11:
-#line 2635 "upb/json/parser.rl"
+#line 2621 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_year(parser, p)); }
break;
case 12:
-#line 2639 "upb/json/parser.rl"
+#line 2625 "upb/json/parser.rl"
{ start_month(parser, p); }
break;
case 13:
-#line 2640 "upb/json/parser.rl"
+#line 2626 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_month(parser, p)); }
break;
case 14:
-#line 2644 "upb/json/parser.rl"
+#line 2630 "upb/json/parser.rl"
{ start_day(parser, p); }
break;
case 15:
-#line 2645 "upb/json/parser.rl"
+#line 2631 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_day(parser, p)); }
break;
case 16:
-#line 2649 "upb/json/parser.rl"
+#line 2635 "upb/json/parser.rl"
{ start_hour(parser, p); }
break;
case 17:
-#line 2650 "upb/json/parser.rl"
+#line 2636 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_hour(parser, p)); }
break;
case 18:
-#line 2654 "upb/json/parser.rl"
+#line 2640 "upb/json/parser.rl"
{ start_minute(parser, p); }
break;
case 19:
-#line 2655 "upb/json/parser.rl"
+#line 2641 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_minute(parser, p)); }
break;
case 20:
-#line 2659 "upb/json/parser.rl"
+#line 2645 "upb/json/parser.rl"
{ start_second(parser, p); }
break;
case 21:
-#line 2660 "upb/json/parser.rl"
+#line 2646 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_second(parser, p)); }
break;
case 22:
-#line 2665 "upb/json/parser.rl"
+#line 2651 "upb/json/parser.rl"
{ start_duration_base(parser, p); }
break;
case 23:
-#line 2666 "upb/json/parser.rl"
+#line 2652 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_duration_base(parser, p)); }
break;
case 24:
-#line 2668 "upb/json/parser.rl"
+#line 2654 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 25:
-#line 2673 "upb/json/parser.rl"
+#line 2659 "upb/json/parser.rl"
{ start_timestamp_base(parser); }
break;
case 26:
-#line 2675 "upb/json/parser.rl"
+#line 2661 "upb/json/parser.rl"
{ start_timestamp_fraction(parser, p); }
break;
case 27:
-#line 2676 "upb/json/parser.rl"
+#line 2662 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
break;
case 28:
-#line 2678 "upb/json/parser.rl"
+#line 2664 "upb/json/parser.rl"
{ start_timestamp_zone(parser, p); }
break;
case 29:
-#line 2679 "upb/json/parser.rl"
+#line 2665 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
break;
case 30:
-#line 2681 "upb/json/parser.rl"
+#line 2667 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 31:
-#line 2686 "upb/json/parser.rl"
+#line 2672 "upb/json/parser.rl"
{ start_fieldmask_path_text(parser, p); }
break;
case 32:
-#line 2687 "upb/json/parser.rl"
+#line 2673 "upb/json/parser.rl"
{ end_fieldmask_path_text(parser, p); }
break;
case 33:
-#line 2692 "upb/json/parser.rl"
+#line 2678 "upb/json/parser.rl"
{ start_fieldmask_path(parser); }
break;
case 34:
-#line 2693 "upb/json/parser.rl"
+#line 2679 "upb/json/parser.rl"
{ end_fieldmask_path(parser); }
break;
case 35:
-#line 2699 "upb/json/parser.rl"
+#line 2685 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 36:
-#line 2704 "upb/json/parser.rl"
+#line 2690 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
{stack[top++] = cs; cs = 47;goto _again;}
@@ -11510,11 +12043,11 @@
}
break;
case 37:
-#line 2717 "upb/json/parser.rl"
+#line 2703 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 78;goto _again;} }
break;
case 38:
-#line 2722 "upb/json/parser.rl"
+#line 2708 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
start_any_member(parser, p);
@@ -11524,11 +12057,11 @@
}
break;
case 39:
-#line 2729 "upb/json/parser.rl"
+#line 2715 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_membername(parser)); }
break;
case 40:
-#line 2732 "upb/json/parser.rl"
+#line 2718 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
end_any_member(parser, p);
@@ -11538,7 +12071,7 @@
}
break;
case 41:
-#line 2743 "upb/json/parser.rl"
+#line 2729 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
start_any_object(parser, p);
@@ -11548,7 +12081,7 @@
}
break;
case 42:
-#line 2752 "upb/json/parser.rl"
+#line 2738 "upb/json/parser.rl"
{
if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
CHECK_RETURN_TOP(end_any_object(parser, p));
@@ -11558,54 +12091,54 @@
}
break;
case 43:
-#line 2764 "upb/json/parser.rl"
+#line 2750 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_array(parser)); }
break;
case 44:
-#line 2768 "upb/json/parser.rl"
+#line 2754 "upb/json/parser.rl"
{ end_array(parser); }
break;
case 45:
-#line 2773 "upb/json/parser.rl"
+#line 2759 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_number(parser, p)); }
break;
case 46:
-#line 2774 "upb/json/parser.rl"
+#line 2760 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 47:
-#line 2776 "upb/json/parser.rl"
+#line 2762 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_stringval(parser)); }
break;
case 48:
-#line 2777 "upb/json/parser.rl"
+#line 2763 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_stringval(parser)); }
break;
case 49:
-#line 2779 "upb/json/parser.rl"
+#line 2765 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, true)); }
break;
case 50:
-#line 2781 "upb/json/parser.rl"
+#line 2767 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, false)); }
break;
case 51:
-#line 2783 "upb/json/parser.rl"
+#line 2769 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_null(parser)); }
break;
case 52:
-#line 2785 "upb/json/parser.rl"
+#line 2771 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_subobject_full(parser)); }
break;
case 53:
-#line 2786 "upb/json/parser.rl"
+#line 2772 "upb/json/parser.rl"
{ end_subobject_full(parser); }
break;
case 54:
-#line 2791 "upb/json/parser.rl"
+#line 2777 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
-#line 3199 "upb/json/parser.c"
+#line 3185 "upb/json/parser.c"
}
}
@@ -11622,32 +12155,32 @@
while ( __nacts-- > 0 ) {
switch ( *__acts++ ) {
case 0:
-#line 2600 "upb/json/parser.rl"
+#line 2586 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; if ( p == pe )
goto _test_eof;
goto _again;} }
break;
case 46:
-#line 2774 "upb/json/parser.rl"
+#line 2760 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 49:
-#line 2779 "upb/json/parser.rl"
+#line 2765 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, true)); }
break;
case 50:
-#line 2781 "upb/json/parser.rl"
+#line 2767 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_bool(parser, false)); }
break;
case 51:
-#line 2783 "upb/json/parser.rl"
+#line 2769 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_null(parser)); }
break;
case 53:
-#line 2786 "upb/json/parser.rl"
+#line 2772 "upb/json/parser.rl"
{ end_subobject_full(parser); }
break;
-#line 3241 "upb/json/parser.c"
+#line 3227 "upb/json/parser.c"
}
}
}
@@ -11655,7 +12188,7 @@
_out: {}
}
-#line 2819 "upb/json/parser.rl"
+#line 2805 "upb/json/parser.rl"
if (p != pe) {
upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
@@ -11698,13 +12231,13 @@
/* Emit Ragel initialization of the parser. */
-#line 3292 "upb/json/parser.c"
+#line 3278 "upb/json/parser.c"
{
cs = json_start;
top = 0;
}
-#line 2861 "upb/json/parser.rl"
+#line 2847 "upb/json/parser.rl"
p->current_state = cs;
p->parser_top = top;
accumulate_clear(p);
@@ -11735,15 +12268,13 @@
upb_msg_field_next(&i)) {
const upb_fielddef *f = upb_msg_iter_field(&i);
upb_value v = upb_value_constptr(f);
- char *buf;
+ const char *name;
/* Add an entry for the JSON name. */
- size_t len = upb_fielddef_getjsonname(f, NULL, 0);
- buf = upb_malloc(alloc, len);
- upb_fielddef_getjsonname(f, buf, len);
- upb_strtable_insert3(&m->name_table, buf, strlen(buf), v, alloc);
+ name = upb_fielddef_jsonname(f);
+ upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
- if (strcmp(buf, upb_fielddef_name(f)) != 0) {
+ if (strcmp(name, 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). */
@@ -11869,6 +12400,7 @@
#include <ctype.h>
+#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
@@ -11926,12 +12458,8 @@
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 */
+ ret->ptr = upb_gstrdup(upb_fielddef_jsonname(f));
+ ret->len = strlen(ret->ptr);
}
upb_handlers_addcleanup(h, ret, freestrpc);
@@ -11950,7 +12478,7 @@
/* ------------ JSON string printing: values, maps, arrays ------------------ */
static void print_data(
- upb_json_printer *p, const char *buf, unsigned int len) {
+ upb_json_printer *p, const char *buf, size_t 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(n == len);
@@ -11990,7 +12518,7 @@
/* Write a properly escaped string chunk. The surrounding quotes are *not*
* printed; this is so that the caller has the option of emitting the string
* content in chunks. */
-static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
+static void putstring(upb_json_printer *p, const char *buf, size_t len) {
const char* unescaped_run = NULL;
unsigned int i;
for (i = 0; i < len; i++) {
@@ -12070,28 +12598,26 @@
return n;
}
-static size_t fmt_int64_as_number(long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "%lld", val);
+static size_t fmt_int64_as_number(int64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "%" PRId64, val);
CHKLENGTH(n > 0 && n < length);
return n;
}
-static size_t fmt_uint64_as_number(
- unsigned long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "%llu", val);
+static size_t fmt_uint64_as_number(uint64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "%" PRIu64, val);
CHKLENGTH(n > 0 && n < length);
return n;
}
-static size_t fmt_int64_as_string(long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "\"%lld\"", val);
+static size_t fmt_int64_as_string(int64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "\"%" PRId64 "\"", val);
CHKLENGTH(n > 0 && n < length);
return n;
}
-static size_t fmt_uint64_as_string(
- unsigned long long val, char* buf, size_t length) {
- size_t n = _upb_snprintf(buf, length, "\"%llu\"", val);
+static size_t fmt_uint64_as_string(uint64_t val, char* buf, size_t length) {
+ size_t n = _upb_snprintf(buf, length, "\"%" PRIu64 "\"", val);
CHKLENGTH(n > 0 && n < length);
return n;
}
@@ -13268,8 +13794,9 @@
}
/* See port_def.inc. This should #undef all macros #defined there. */
+#undef UPB_MAPTYPE_STRING
#undef UPB_SIZE
-#undef UPB_FIELD_AT
+#undef UPB_PTR_AT
#undef UPB_READ_ONEOF
#undef UPB_WRITE_ONEOF
#undef UPB_INLINE
@@ -13279,6 +13806,7 @@
#undef UPB_MAX
#undef UPB_MIN
#undef UPB_UNUSED
+#undef UPB_ASSUME
#undef UPB_ASSERT
#undef UPB_ASSERT_DEBUGVAR
#undef UPB_UNREACHABLE
diff --git a/ruby/ext/google/protobuf_c/upb.h b/ruby/ext/google/protobuf_c/upb.h
index e49c7de..bdc20eb 100644
--- a/ruby/ext/google/protobuf_c/upb.h
+++ b/ruby/ext/google/protobuf_c/upb.h
@@ -21,9 +21,7 @@
*
* This file is private and must not be included by users!
*/
-#ifndef UINTPTR_MAX
-#error must include stdint.h first
-#endif
+#include <stdint.h>
#if UINTPTR_MAX == 0xffffffff
#define UPB_SIZE(size32, size64) size32
@@ -31,17 +29,21 @@
#define UPB_SIZE(size32, size64) size64
#endif
-#define UPB_FIELD_AT(msg, fieldtype, offset) \
- *(fieldtype*)((const char*)(msg) + offset)
+/* If we always read/write as a consistent type to each address, this shouldn't
+ * violate aliasing.
+ */
+#define UPB_PTR_AT(msg, ofs, type) ((type*)((char*)(msg) + (ofs)))
#define UPB_READ_ONEOF(msg, fieldtype, offset, case_offset, case_val, default) \
- UPB_FIELD_AT(msg, int, case_offset) == case_val \
- ? UPB_FIELD_AT(msg, fieldtype, offset) \
+ *UPB_PTR_AT(msg, case_offset, int) == case_val \
+ ? *UPB_PTR_AT(msg, offset, fieldtype) \
: default
#define UPB_WRITE_ONEOF(msg, fieldtype, offset, value, case_offset, case_val) \
- UPB_FIELD_AT(msg, int, case_offset) = case_val; \
- UPB_FIELD_AT(msg, fieldtype, offset) = value;
+ *UPB_PTR_AT(msg, case_offset, int) = case_val; \
+ *UPB_PTR_AT(msg, offset, fieldtype) = value;
+
+#define UPB_MAPTYPE_STRING 0
/* UPB_INLINE: inline if possible, emit standalone code if required. */
#ifdef __cplusplus
@@ -115,7 +117,7 @@
#ifdef __cplusplus
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) || \
(defined(_MSC_VER) && _MSC_VER >= 1900)
-// C++11 is present
+/* C++11 is present */
#else
#error upb requires C++11 for C++ support
#endif
@@ -126,6 +128,18 @@
#define UPB_UNUSED(var) (void)var
+/* UPB_ASSUME(): in release mode, we tell the compiler to assume this is true.
+ */
+#ifdef NDEBUG
+#ifdef __GNUC__
+#define UPB_ASSUME(expr) if (!(expr)) __builtin_unreachable()
+#else
+#define UPB_ASSUME(expr) do {} if (false && (expr))
+#endif
+#else
+#define UPB_ASSUME(expr) assert(expr)
+#endif
+
/* UPB_ASSERT(): in release mode, we use the expression without letting it be
* evaluated. This prevents "unused variable" warnings. */
#ifdef NDEBUG
@@ -152,10 +166,51 @@
#define UPB_INFINITY (1.0 / 0.0)
#endif
/*
-** This file contains shared definitions that are widely used across upb.
+** upb_decode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_DECODE_H_
+#define UPB_DECODE_H_
+
+/*
+** Our memory representation for parsing tables and messages themselves.
+** Functions in this file are used by generated code and possibly reflection.
**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
+** The definitions in this file are internal to upb.
+**/
+
+#ifndef UPB_MSG_H_
+#define UPB_MSG_H_
+
+#include <stdint.h>
+#include <string.h>
+
+/*
+** upb_table
+**
+** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
+** This file defines very fast int->upb_value (inttable) and string->upb_value
+** (strtable) hash tables.
+**
+** The table uses chained scatter with Brent's variation (inspired by the Lua
+** implementation of hash tables). The hash function for strings is Austin
+** Appleby's "MurmurHash."
+**
+** The inttable uses uintptr_t as its key, which guarantees it can be used to
+** store pointers or integers of at least 32 bits (upb isn't really useful on
+** systems where sizeof(void*) < 4).
+**
+** The table must be homogenous (all values of the same type). In debug
+** mode, we check this on insert and lookup.
+*/
+
+#ifndef UPB_TABLE_H_
+#define UPB_TABLE_H_
+
+#include <stdint.h>
+#include <string.h>
+/*
+** This file contains shared definitions that are widely used across upb.
*/
#ifndef UPB_H_
@@ -168,23 +223,13 @@
#include <stdint.h>
#include <string.h>
-#ifdef __cplusplus
-#include <memory>
-namespace upb {
-class Arena;
-class Status;
-template <int N> class InlinedArena;
-}
-#endif
+#ifdef __cplusplus
+extern "C" {
+#endif
/* upb_status *****************************************************************/
-/* 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. */
-
-/* The maximum length of an error message before it will get truncated. */
#define UPB_STATUS_MAX_MESSAGE 127
typedef struct {
@@ -192,59 +237,15 @@
char msg[UPB_STATUS_MAX_MESSAGE]; /* Error message; NULL-terminated. */
} upb_status;
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_status_errmsg(const upb_status *status);
bool upb_ok(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. */
+/* These are no-op if |status| is NULL. */
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);
-UPB_INLINE void upb_status_setoom(upb_status *status) {
- upb_status_seterrmsg(status, "out of memory");
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-
-class upb::Status {
- public:
- Status() { upb_status_clear(&status_); }
-
- upb_status* ptr() { return &status_; }
-
- /* Returns true if there is no error. */
- bool ok() const { return upb_ok(&status_); }
-
- /* Guaranteed to be NULL-terminated. */
- const char *error_message() const { return upb_status_errmsg(&status_); }
-
- /* The error message will be truncated if it is longer than
- * UPB_STATUS_MAX_MESSAGE-4. */
- void SetErrorMessage(const char *msg) { upb_status_seterrmsg(&status_, msg); }
- void SetFormattedErrorMessage(const char *fmt, ...) {
- va_list args;
- va_start(args, fmt);
- upb_status_vseterrf(&status_, fmt, args);
- va_end(args);
- }
-
- /* Resets the status to a successful state with no message. */
- void Clear() { upb_status_clear(&status_); }
-
- private:
- upb_status status_;
-};
-
-#endif /* __cplusplus */
-
/** upb_strview ************************************************************/
typedef struct {
@@ -311,16 +312,8 @@
/* The global allocator used by upb. Uses the standard malloc()/free(). */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
extern upb_alloc upb_alloc_global;
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
/* Functions that hard-code the global malloc.
*
* We still get benefit because we can put custom logic into our global
@@ -357,9 +350,18 @@
struct upb_arena;
typedef struct upb_arena upb_arena;
-#ifdef __cplusplus
-extern "C" {
-#endif
+typedef struct {
+ /* We implement the allocator interface.
+ * This must be the first member of upb_arena! */
+ upb_alloc alloc;
+
+ char *ptr, *end;
+} _upb_arena_head;
+
+UPB_INLINE size_t _upb_arena_alignup(size_t size) {
+ const size_t maxalign = 16;
+ return ((size + maxalign - 1) / maxalign) * maxalign;
+}
/* Creates an arena from the given initial block (if any -- n may be 0).
* Additional blocks will be allocated from |alloc|. If |alloc| is NULL, this
@@ -368,82 +370,35 @@
void upb_arena_free(upb_arena *a);
bool upb_arena_addcleanup(upb_arena *a, void *ud, upb_cleanup_func *func);
size_t upb_arena_bytesallocated(const upb_arena *a);
+void *_upb_arena_slowmalloc(upb_arena *a, size_t size);
UPB_INLINE upb_alloc *upb_arena_alloc(upb_arena *a) { return (upb_alloc*)a; }
-/* Convenience wrappers around upb_alloc functions. */
-
UPB_INLINE void *upb_arena_malloc(upb_arena *a, size_t size) {
- return upb_malloc(upb_arena_alloc(a), size);
+ _upb_arena_head *h = (_upb_arena_head*)a;
+ size = _upb_arena_alignup(size);
+ if (UPB_LIKELY((size_t)(h->end - h->ptr) >= size)) {
+ void* ret = h->ptr;
+ h->ptr += size;
+ return ret;
+ } else {
+ return _upb_arena_slowmalloc(a, size);
+ }
}
UPB_INLINE void *upb_arena_realloc(upb_arena *a, void *ptr, size_t oldsize,
size_t size) {
- return upb_realloc(upb_arena_alloc(a), ptr, oldsize, size);
+ if (oldsize == 0) {
+ return upb_arena_malloc(a, size);
+ } else {
+ return upb_realloc(upb_arena_alloc(a), ptr, oldsize, size);
+ }
}
UPB_INLINE upb_arena *upb_arena_new(void) {
return upb_arena_init(NULL, 0, &upb_alloc_global);
}
-#ifdef __cplusplus
-} /* extern "C" */
-
-class upb::Arena {
- public:
- /* A simple arena with no initial memory block and the default allocator. */
- Arena() : ptr_(upb_arena_new(), upb_arena_free) {}
-
- upb_arena* ptr() { return ptr_.get(); }
-
- /* 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. */
- upb_alloc *allocator() { return upb_arena_alloc(ptr_.get()); }
-
- /* Add a cleanup function to run when the arena is destroyed.
- * Returns false on out-of-memory. */
- bool AddCleanup(void *ud, upb_cleanup_func* func) {
- return upb_arena_addcleanup(ptr_.get(), ud, func);
- }
-
- /* Total number of bytes that have been allocated. It is undefined what
- * Realloc() does to &arena_ counter. */
- size_t BytesAllocated() const { return upb_arena_bytesallocated(ptr_.get()); }
-
- private:
- std::unique_ptr<upb_arena, decltype(&upb_arena_free)> ptr_;
-};
-
-#endif
-
-/* upb::InlinedArena **********************************************************/
-
-/* upb::InlinedArena seeds the 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
-
-template <int N> class upb::InlinedArena : public upb::Arena {
- public:
- InlinedArena() : ptr_(upb_arena_new(&initial_block_, N, &upb_alloc_global)) {}
-
- upb_arena* ptr() { return ptr_.get(); }
-
- private:
- InlinedArena(const InlinedArena*) = delete;
- InlinedArena& operator=(const InlinedArena*) = delete;
-
- std::unique_ptr<upb_arena, decltype(&upb_arena_free)> ptr_;
- char initial_block_[N];
-};
-
-#endif /* __cplusplus */
-
/* Constants ******************************************************************/
/* Generic function type. */
@@ -463,21 +418,17 @@
* types defined in descriptor.proto, which gives INT32 and SINT32 separate
* types (we distinguish the two with the "integer encoding" enum below). */
typedef enum {
- /* Types stored in 1 byte. */
UPB_TYPE_BOOL = 1,
- /* Types stored in 4 bytes. */
UPB_TYPE_FLOAT = 2,
UPB_TYPE_INT32 = 3,
UPB_TYPE_UINT32 = 4,
UPB_TYPE_ENUM = 5, /* Enum values are int32. */
- /* Types stored as pointers (probably 4 or 8 bytes). */
- UPB_TYPE_STRING = 6,
- UPB_TYPE_BYTES = 7,
- UPB_TYPE_MESSAGE = 8,
- /* Types stored as 8 bytes. */
- UPB_TYPE_DOUBLE = 9,
- UPB_TYPE_INT64 = 10,
- UPB_TYPE_UINT64 = 11
+ UPB_TYPE_MESSAGE = 6,
+ UPB_TYPE_DOUBLE = 7,
+ UPB_TYPE_INT64 = 8,
+ UPB_TYPE_UINT64 = 9,
+ UPB_TYPE_STRING = 10,
+ UPB_TYPE_BYTES = 11
} upb_fieldtype_t;
/* The repeated-ness of each field; this matches descriptor.proto. */
@@ -489,6 +440,7 @@
/* Descriptor types, as defined in descriptor.proto. */
typedef enum {
+ /* Old (long) names. TODO(haberman): remove */
UPB_DESCRIPTOR_TYPE_DOUBLE = 1,
UPB_DESCRIPTOR_TYPE_FLOAT = 2,
UPB_DESCRIPTOR_TYPE_INT64 = 3,
@@ -506,145 +458,36 @@
UPB_DESCRIPTOR_TYPE_SFIXED32 = 15,
UPB_DESCRIPTOR_TYPE_SFIXED64 = 16,
UPB_DESCRIPTOR_TYPE_SINT32 = 17,
- UPB_DESCRIPTOR_TYPE_SINT64 = 18
+ UPB_DESCRIPTOR_TYPE_SINT64 = 18,
+
+ UPB_DTYPE_DOUBLE = 1,
+ UPB_DTYPE_FLOAT = 2,
+ UPB_DTYPE_INT64 = 3,
+ UPB_DTYPE_UINT64 = 4,
+ UPB_DTYPE_INT32 = 5,
+ UPB_DTYPE_FIXED64 = 6,
+ UPB_DTYPE_FIXED32 = 7,
+ UPB_DTYPE_BOOL = 8,
+ UPB_DTYPE_STRING = 9,
+ UPB_DTYPE_GROUP = 10,
+ UPB_DTYPE_MESSAGE = 11,
+ UPB_DTYPE_BYTES = 12,
+ UPB_DTYPE_UINT32 = 13,
+ UPB_DTYPE_ENUM = 14,
+ UPB_DTYPE_SFIXED32 = 15,
+ UPB_DTYPE_SFIXED64 = 16,
+ UPB_DTYPE_SINT32 = 17,
+ UPB_DTYPE_SINT64 = 18
} upb_descriptortype_t;
-extern const uint8_t upb_desctype_to_fieldtype[];
+#define UPB_MAP_BEGIN -1
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
#endif /* UPB_H_ */
-/*
-** upb_decode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_DECODE_H_
-#define UPB_DECODE_H_
-
-/*
-** Data structures for message tables, used for parsing and serialization.
-** This are much lighter-weight than full reflection, but they are do not
-** have enough information to convert to text format, JSON, etc.
-**
-** The definitions in this file are internal to upb.
-**/
-
-#ifndef UPB_MSG_H_
-#define UPB_MSG_H_
-
-#include <stdint.h>
-#include <string.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef void upb_msg;
-
-/** upb_msglayout *************************************************************/
-
-/* upb_msglayout represents the memory layout of a given upb_msgdef. The
- * members are public so generated code can initialize them, but users MUST NOT
- * read or write any of its members. */
-
-typedef struct {
- uint32_t number;
- uint16_t offset;
- int16_t presence; /* If >0, hasbit_index+1. If <0, oneof_index+1. */
- uint16_t submsg_index; /* undefined if descriptortype != MESSAGE or GROUP. */
- uint8_t descriptortype;
- uint8_t label;
-} upb_msglayout_field;
-
-typedef struct upb_msglayout {
- const struct upb_msglayout *const* submsgs;
- const upb_msglayout_field *fields;
- /* Must be aligned to sizeof(void*). Doesn't include internal members like
- * unknown fields, extension dict, pointer to msglayout, etc. */
- uint16_t size;
- uint16_t field_count;
- bool extendable;
-} upb_msglayout;
-
-/** Message internal representation *******************************************/
-
-/* Our internal representation for repeated fields. */
-typedef struct {
- void *data; /* Each element is element_size. */
- size_t len; /* Measured in elements. */
- size_t size; /* Measured in elements. */
-} upb_array;
-
-upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a);
-upb_msg *upb_msg_new(const upb_msglayout *l, upb_arena *a);
-
-void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
- upb_arena *arena);
-const char *upb_msg_getunknown(const upb_msg *msg, size_t *len);
-
-upb_array *upb_array_new(upb_arena *a);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_MSG_H_ */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-bool upb_decode(const char *buf, size_t size, upb_msg *msg,
- const upb_msglayout *l, upb_arena *arena);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_DECODE_H_ */
-/*
-** upb_encode: parsing into a upb_msg using a upb_msglayout.
-*/
-
-#ifndef UPB_ENCODE_H_
-#define UPB_ENCODE_H_
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-char *upb_encode(const void *msg, const upb_msglayout *l, upb_arena *arena,
- size_t *size);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* UPB_ENCODE_H_ */
-/*
-** upb_table
-**
-** This header is INTERNAL-ONLY! Its interfaces are not public or stable!
-** This file defines very fast int->upb_value (inttable) and string->upb_value
-** (strtable) hash tables.
-**
-** The table uses chained scatter with Brent's variation (inspired by the Lua
-** implementation of hash tables). The hash function for strings is Austin
-** Appleby's "MurmurHash."
-**
-** The inttable uses uintptr_t as its key, which guarantees it can be used to
-** store pointers or integers of at least 32 bits (upb isn't really useful on
-** systems where sizeof(void*) < 4).
-**
-** The table must be homogenous (all values of the same type). In debug
-** mode, we check this on insert and lookup.
-*/
-
-#ifndef UPB_TABLE_H_
-#define UPB_TABLE_H_
-
-#include <stdint.h>
-#include <string.h>
#ifdef __cplusplus
@@ -673,19 +516,8 @@
typedef struct {
uint64_t val;
-#ifndef NDEBUG
- /* In debug mode we carry the value type around also so we can check accesses
- * to be sure the right member is being read. */
- upb_ctype_t ctype;
-#endif
} upb_value;
-#ifdef NDEBUG
-#define SET_TYPE(dest, val) UPB_UNUSED(val)
-#else
-#define SET_TYPE(dest, val) dest = val
-#endif
-
/* Like strdup(), which isn't always available since it's not ANSI C. */
char *upb_strdup(const char *s, upb_alloc *a);
/* Variant that works with a length-delimited rather than NULL-delimited string,
@@ -696,15 +528,13 @@
return upb_strdup(s, &upb_alloc_global);
}
-UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val,
- upb_ctype_t ctype) {
+UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val) {
v->val = val;
- SET_TYPE(v->ctype, ctype);
}
-UPB_INLINE upb_value _upb_value_val(uint64_t val, upb_ctype_t ctype) {
+UPB_INLINE upb_value _upb_value_val(uint64_t val) {
upb_value ret;
- _upb_value_setval(&ret, val, ctype);
+ _upb_value_setval(&ret, val);
return ret;
}
@@ -719,7 +549,6 @@
#define FUNCS(name, membername, type_t, converter, proto_type) \
UPB_INLINE void upb_value_set ## name(upb_value *val, type_t cval) { \
val->val = (converter)cval; \
- SET_TYPE(val->ctype, proto_type); \
} \
UPB_INLINE upb_value upb_value_ ## name(type_t val) { \
upb_value ret; \
@@ -727,7 +556,6 @@
return ret; \
} \
UPB_INLINE type_t upb_value_get ## name(upb_value val) { \
- UPB_ASSERT_DEBUGVAR(val.ctype == proto_type); \
return (type_t)(converter)val.val; \
}
@@ -745,12 +573,10 @@
UPB_INLINE void upb_value_setfloat(upb_value *val, float cval) {
memcpy(&val->val, &cval, sizeof(cval));
- SET_TYPE(val->ctype, UPB_CTYPE_FLOAT);
}
UPB_INLINE void upb_value_setdouble(upb_value *val, double cval) {
memcpy(&val->val, &cval, sizeof(cval));
- SET_TYPE(val->ctype, UPB_CTYPE_DOUBLE);
}
UPB_INLINE upb_value upb_value_float(float cval) {
@@ -794,7 +620,6 @@
#define UPB_TABVALUE_EMPTY_INIT {-1}
-
/* upb_table ******************************************************************/
typedef struct _upb_tabent {
@@ -811,7 +636,6 @@
typedef struct {
size_t count; /* Number of entries in the hash part. */
size_t mask; /* Mask to turn hash value -> bucket. */
- upb_ctype_t ctype; /* Type of all values. */
uint8_t size_lg2; /* Size of the hashtable part is 2^size_lg2 entries. */
/* Hash table entries.
@@ -821,17 +645,6 @@
* 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;
typedef struct {
@@ -845,12 +658,6 @@
size_t array_count; /* Array part number of elements. */
} upb_inttable;
-#define UPB_INTTABLE_INIT(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)
-
#define UPB_ARRAY_EMPTYENT -1
UPB_INLINE size_t upb_table_size(const upb_table *t) {
@@ -919,6 +726,7 @@
size_t size);
upb_strtable *upb_strtable_pack(const upb_strtable *t, void *p, size_t *ofs,
size_t size);
+void upb_strtable_clear(upb_strtable *t);
/* Inserts the given key into the hashtable with the given value. The key must
* not already exist in the hash table. For string tables, the key must be
@@ -1020,7 +828,7 @@
if (key < t->array_size) {
upb_tabval arrval = t->array[key];
if (upb_arrhas(arrval)) {
- _upb_value_setval(v, arrval.val, t->t.ctype);
+ _upb_value_setval(v, arrval.val);
return true;
} else {
return false;
@@ -1030,7 +838,7 @@
if (t->t.entries == NULL) return false;
for (e = upb_getentry(&t->t, upb_inthash(key)); true; e = e->next) {
if ((uint32_t)e->key == key) {
- _upb_value_setval(v, e->val.val, t->t.ctype);
+ _upb_value_setval(v, e->val.val);
return true;
}
if (e->next == NULL) return false;
@@ -1084,8 +892,7 @@
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(const upb_strtable_iter *i);
-size_t upb_strtable_iter_keylength(const upb_strtable_iter *i);
+upb_strview upb_strtable_iter_key(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,
@@ -1109,6 +916,10 @@
bool array_part;
} upb_inttable_iter;
+UPB_INLINE const upb_tabent *str_tabent(const upb_strtable_iter *i) {
+ return &i->t->t.entries[i->index];
+}
+
void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t);
void upb_inttable_next(upb_inttable_iter *i);
bool upb_inttable_done(const upb_inttable_iter *i);
@@ -1125,98 +936,80 @@
#endif /* UPB_TABLE_H_ */
-/* This file was generated by upbc (the upb compiler) from the input
- * file:
- *
- * google/protobuf/descriptor.proto
- *
- * Do not edit -- your changes will be discarded when the file is
- * regenerated. */
-#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
-#define GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
-/*
-** Functions for use by generated code. These are not public and users must
-** not call them directly.
-*/
-
-#ifndef UPB_GENERATED_UTIL_H_
-#define UPB_GENERATED_UTIL_H_
-
-#include <stdint.h>
-
+#ifdef __cplusplus
+extern "C" {
+#endif
#define PTR_AT(msg, ofs, type) (type*)((const char*)msg + ofs)
-UPB_INLINE const void *_upb_array_accessor(const void *msg, size_t ofs,
- size_t *size) {
- const upb_array *arr = *PTR_AT(msg, ofs, const upb_array*);
- if (arr) {
- if (size) *size = arr->len;
- return arr->data;
- } else {
- if (size) *size = 0;
- return NULL;
- }
-}
+typedef void upb_msg;
-UPB_INLINE void *_upb_array_mutable_accessor(void *msg, size_t ofs,
- size_t *size) {
- upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
- if (arr) {
- if (size) *size = arr->len;
- return arr->data;
- } else {
- if (size) *size = 0;
- return NULL;
- }
-}
+/** upb_msglayout *************************************************************/
-/* TODO(haberman): this is a mess. It will improve when upb_array no longer
- * carries reflective state (type, elem_size). */
-UPB_INLINE void *_upb_array_resize_accessor(void *msg, size_t ofs, size_t size,
- size_t elem_size,
- upb_fieldtype_t type,
- upb_arena *arena) {
- upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
+/* upb_msglayout represents the memory layout of a given upb_msgdef. The
+ * members are public so generated code can initialize them, but users MUST NOT
+ * read or write any of its members. */
- if (!arr) {
- arr = upb_array_new(arena);
- if (!arr) return NULL;
- *PTR_AT(msg, ofs, upb_array*) = arr;
- }
+/* These aren't real labels according to descriptor.proto, but in the table we
+ * use these for map/packed fields instead of UPB_LABEL_REPEATED. */
+enum {
+ _UPB_LABEL_MAP = 4,
+ _UPB_LABEL_PACKED = 7 /* Low 3 bits are common with UPB_LABEL_REPEATED. */
+};
- if (size > arr->size) {
- size_t new_size = UPB_MAX(arr->size, 4);
- size_t old_bytes = arr->size * elem_size;
- size_t new_bytes;
- while (new_size < size) new_size *= 2;
- new_bytes = new_size * elem_size;
- arr->data = upb_arena_realloc(arena, arr->data, old_bytes, new_bytes);
- if (!arr->data) {
- return NULL;
- }
- arr->size = new_size;
- }
+typedef struct {
+ uint32_t number;
+ uint16_t offset;
+ int16_t presence; /* If >0, hasbit_index. If <0, -oneof_index. */
+ uint16_t submsg_index; /* undefined if descriptortype != MESSAGE or GROUP. */
+ uint8_t descriptortype;
+ uint8_t label;
+} upb_msglayout_field;
- arr->len = size;
- return arr->data;
-}
+typedef struct upb_msglayout {
+ const struct upb_msglayout *const* submsgs;
+ const upb_msglayout_field *fields;
+ /* Must be aligned to sizeof(void*). Doesn't include internal members like
+ * unknown fields, extension dict, pointer to msglayout, etc. */
+ uint16_t size;
+ uint16_t field_count;
+ bool extendable;
+} upb_msglayout;
-UPB_INLINE bool _upb_array_append_accessor(void *msg, size_t ofs,
- size_t elem_size,
- upb_fieldtype_t type,
- const void *value,
- upb_arena *arena) {
- upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
- size_t i = arr ? arr->len : 0;
- void *data =
- _upb_array_resize_accessor(msg, ofs, i + 1, elem_size, type, arena);
- if (!data) return false;
- memcpy(PTR_AT(data, i * elem_size, char), value, elem_size);
- return true;
-}
+/** upb_msg *******************************************************************/
+
+/* Internal members of a upb_msg. We can change this without breaking binary
+ * compatibility. We put these before the user's data. The user's upb_msg*
+ * points after the upb_msg_internal. */
+
+/* Used when a message is not extendable. */
+typedef struct {
+ char *unknown;
+ size_t unknown_len;
+ size_t unknown_size;
+} upb_msg_internal;
+
+/* Used when a message is extendable. */
+typedef struct {
+ upb_inttable *extdict;
+ upb_msg_internal base;
+} upb_msg_internal_withext;
+
+/* Maps upb_fieldtype_t -> memory size. */
+extern char _upb_fieldtype_to_size[12];
+
+/* Creates a new messages with the given layout on the given arena. */
+upb_msg *_upb_msg_new(const upb_msglayout *l, upb_arena *a);
+
+/* Adds unknown data (serialized protobuf data) to the given message. The data
+ * is copied into the message instance. */
+bool _upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
+ upb_arena *arena);
+
+/* Returns a reference to the message's unknown data. */
+const char *upb_msg_getunknown(const upb_msg *msg, size_t *len);
UPB_INLINE bool _upb_has_field(const void *msg, size_t idx) {
return (*PTR_AT(msg, idx / 8, const char) & (1 << (idx % 8))) != 0;
@@ -1234,10 +1027,349 @@
return *PTR_AT(msg, case_ofs, int32_t) == num;
}
+UPB_INLINE bool _upb_has_submsg_nohasbit(const void *msg, size_t ofs) {
+ return *PTR_AT(msg, ofs, const void*) != NULL;
+}
+
+UPB_INLINE bool _upb_isrepeated(const upb_msglayout_field *field) {
+ return (field->label & 3) == UPB_LABEL_REPEATED;
+}
+
+/** upb_array *****************************************************************/
+
+/* Our internal representation for repeated fields. */
+typedef struct {
+ uintptr_t data; /* Tagged ptr: low 3 bits of ptr are lg2(elem size). */
+ size_t len; /* Measured in elements. */
+ size_t size; /* Measured in elements. */
+} upb_array;
+
+UPB_INLINE const void *_upb_array_constptr(const upb_array *arr) {
+ return (void*)(arr->data & ~(uintptr_t)7);
+}
+
+UPB_INLINE void *_upb_array_ptr(upb_array *arr) {
+ return (void*)_upb_array_constptr(arr);
+}
+
+/* Creates a new array on the given arena. */
+upb_array *_upb_array_new(upb_arena *a, upb_fieldtype_t type);
+
+/* Resizes the capacity of the array to be at least min_size. */
+bool _upb_array_realloc(upb_array *arr, size_t min_size, upb_arena *arena);
+
+/* Fallback functions for when the accessors require a resize. */
+void *_upb_array_resize_fallback(upb_array **arr_ptr, size_t size,
+ upb_fieldtype_t type, upb_arena *arena);
+bool _upb_array_append_fallback(upb_array **arr_ptr, const void *value,
+ upb_fieldtype_t type, upb_arena *arena);
+
+UPB_INLINE const void *_upb_array_accessor(const void *msg, size_t ofs,
+ size_t *size) {
+ const upb_array *arr = *PTR_AT(msg, ofs, const upb_array*);
+ if (arr) {
+ if (size) *size = arr->len;
+ return _upb_array_constptr(arr);
+ } else {
+ if (size) *size = 0;
+ return NULL;
+ }
+}
+
+UPB_INLINE void *_upb_array_mutable_accessor(void *msg, size_t ofs,
+ size_t *size) {
+ upb_array *arr = *PTR_AT(msg, ofs, upb_array*);
+ if (arr) {
+ if (size) *size = arr->len;
+ return _upb_array_ptr(arr);
+ } else {
+ if (size) *size = 0;
+ return NULL;
+ }
+}
+
+UPB_INLINE void *_upb_array_resize_accessor(void *msg, size_t ofs, size_t size,
+ upb_fieldtype_t type,
+ upb_arena *arena) {
+ upb_array **arr_ptr = PTR_AT(msg, ofs, upb_array*);
+ upb_array *arr = *arr_ptr;
+ if (!arr || arr->size < size) {
+ return _upb_array_resize_fallback(arr_ptr, size, type, arena);
+ }
+ arr->len = size;
+ return _upb_array_ptr(arr);
+}
+
+
+UPB_INLINE bool _upb_array_append_accessor(void *msg, size_t ofs,
+ size_t elem_size,
+ upb_fieldtype_t type,
+ const void *value,
+ upb_arena *arena) {
+ upb_array **arr_ptr = PTR_AT(msg, ofs, upb_array*);
+ upb_array *arr = *arr_ptr;
+ void* ptr;
+ if (!arr || arr->len == arr->size) {
+ return _upb_array_append_fallback(arr_ptr, value, type, arena);
+ }
+ ptr = _upb_array_ptr(arr);
+ memcpy(PTR_AT(ptr, arr->len * elem_size, char), value, elem_size);
+ arr->len++;
+ return true;
+}
+
+/** upb_map *******************************************************************/
+
+/* Right now we use strmaps for everything. We'll likely want to use
+ * integer-specific maps for integer-keyed maps.*/
+typedef struct {
+ /* Size of key and val, based on the map type. Strings are represented as '0'
+ * because they must be handled specially. */
+ char key_size;
+ char val_size;
+
+ upb_strtable table;
+} upb_map;
+
+/* Map entries aren't actually stored, they are only used during parsing. For
+ * parsing, it helps a lot if all map entry messages have the same layout.
+ * The compiler and def.c must ensure that all map entries have this layout. */
+typedef struct {
+ upb_msg_internal internal;
+ union {
+ upb_strview str; /* For str/bytes. */
+ upb_value val; /* For all other types. */
+ } k;
+ union {
+ upb_strview str; /* For str/bytes. */
+ upb_value val; /* For all other types. */
+ } v;
+} upb_map_entry;
+
+/* Creates a new map on the given arena with this key/value type. */
+upb_map *_upb_map_new(upb_arena *a, size_t key_size, size_t value_size);
+
+/* Converting between internal table representation and user values.
+ *
+ * _upb_map_tokey() and _upb_map_fromkey() are inverses.
+ * _upb_map_tovalue() and _upb_map_fromvalue() are inverses.
+ *
+ * These functions account for the fact that strings are treated differently
+ * from other types when stored in a map.
+ */
+
+UPB_INLINE upb_strview _upb_map_tokey(const void *key, size_t size) {
+ if (size == UPB_MAPTYPE_STRING) {
+ return *(upb_strview*)key;
+ } else {
+ return upb_strview_make((const char*)key, size);
+ }
+}
+
+UPB_INLINE void _upb_map_fromkey(upb_strview key, void* out, size_t size) {
+ if (size == UPB_MAPTYPE_STRING) {
+ memcpy(out, &key, sizeof(key));
+ } else {
+ memcpy(out, key.data, size);
+ }
+}
+
+UPB_INLINE upb_value _upb_map_tovalue(const void *val, size_t size,
+ upb_arena *a) {
+ upb_value ret = {0};
+ if (size == UPB_MAPTYPE_STRING) {
+ upb_strview *strp = (upb_strview*)upb_arena_malloc(a, sizeof(*strp));
+ *strp = *(upb_strview*)val;
+ memcpy(&ret, &strp, sizeof(strp));
+ } else {
+ memcpy(&ret, val, size);
+ }
+ return ret;
+}
+
+UPB_INLINE void _upb_map_fromvalue(upb_value val, void* out, size_t size) {
+ if (size == UPB_MAPTYPE_STRING) {
+ const upb_strview *strp = (const upb_strview*)upb_value_getptr(val);
+ memcpy(out, strp, sizeof(upb_strview));
+ } else {
+ memcpy(out, &val, size);
+ }
+}
+
+/* Map operations, shared by reflection and generated code. */
+
+UPB_INLINE size_t _upb_map_size(const upb_map *map) {
+ return map->table.t.count;
+}
+
+UPB_INLINE bool _upb_map_get(const upb_map *map, const void *key,
+ size_t key_size, void *val, size_t val_size) {
+ upb_value tabval;
+ upb_strview k = _upb_map_tokey(key, key_size);
+ bool ret = upb_strtable_lookup2(&map->table, k.data, k.size, &tabval);
+ if (ret) {
+ _upb_map_fromvalue(tabval, val, val_size);
+ }
+ return ret;
+}
+
+UPB_INLINE void* _upb_map_next(const upb_map *map, size_t *iter) {
+ upb_strtable_iter it;
+ it.t = &map->table;
+ it.index = *iter;
+ upb_strtable_next(&it);
+ if (upb_strtable_done(&it)) return NULL;
+ *iter = it.index;
+ return (void*)str_tabent(&it);
+}
+
+UPB_INLINE bool _upb_map_set(upb_map *map, const void *key, size_t key_size,
+ void *val, size_t val_size, upb_arena *arena) {
+ upb_strview strkey = _upb_map_tokey(key, key_size);
+ upb_value tabval = _upb_map_tovalue(val, val_size, arena);
+ upb_alloc *a = upb_arena_alloc(arena);
+
+ /* TODO(haberman): add overwrite operation to minimize number of lookups. */
+ upb_strtable_remove3(&map->table, strkey.data, strkey.size, NULL, a);
+ return upb_strtable_insert3(&map->table, strkey.data, strkey.size, tabval, a);
+}
+
+UPB_INLINE bool _upb_map_delete(upb_map *map, const void *key, size_t key_size) {
+ upb_strview k = _upb_map_tokey(key, key_size);
+ return upb_strtable_remove3(&map->table, k.data, k.size, NULL, NULL);
+}
+
+UPB_INLINE void _upb_map_clear(upb_map *map) {
+ upb_strtable_clear(&map->table);
+}
+
+/* Message map operations, these get the map from the message first. */
+
+UPB_INLINE size_t _upb_msg_map_size(const upb_msg *msg, size_t ofs) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ return map ? _upb_map_size(map) : 0;
+}
+
+UPB_INLINE bool _upb_msg_map_get(const upb_msg *msg, size_t ofs,
+ const void *key, size_t key_size, void *val,
+ size_t val_size) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return false;
+ return _upb_map_get(map, key, key_size, val, val_size);
+}
+
+UPB_INLINE void *_upb_msg_map_next(const upb_msg *msg, size_t ofs,
+ size_t *iter) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return NULL;
+ return _upb_map_next(map, iter);
+}
+
+UPB_INLINE bool _upb_msg_map_set(upb_msg *msg, size_t ofs, const void *key,
+ size_t key_size, void *val, size_t val_size,
+ upb_arena *arena) {
+ upb_map **map = PTR_AT(msg, ofs, upb_map *);
+ if (!*map) {
+ *map = _upb_map_new(arena, key_size, val_size);
+ }
+ return _upb_map_set(*map, key, key_size, val, val_size, arena);
+}
+
+UPB_INLINE bool _upb_msg_map_delete(upb_msg *msg, size_t ofs, const void *key,
+ size_t key_size) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return false;
+ return _upb_map_delete(map, key, key_size);
+}
+
+UPB_INLINE void _upb_msg_map_clear(upb_msg *msg, size_t ofs) {
+ upb_map *map = *UPB_PTR_AT(msg, ofs, upb_map *);
+ if (!map) return;
+ _upb_map_clear(map);
+}
+
+/* Accessing map key/value from a pointer, used by generated code only. */
+
+UPB_INLINE void _upb_msg_map_key(const void* msg, void* key, size_t size) {
+ const upb_tabent *ent = (const upb_tabent*)msg;
+ uint32_t u32len;
+ upb_strview k;
+ k.data = upb_tabstr(ent->key, &u32len);
+ k.size = u32len;
+ _upb_map_fromkey(k, key, size);
+}
+
+UPB_INLINE void _upb_msg_map_value(const void* msg, void* val, size_t size) {
+ const upb_tabent *ent = (const upb_tabent*)msg;
+ upb_value v;
+ _upb_value_setval(&v, ent->val.val);
+ _upb_map_fromvalue(v, val, size);
+}
+
+UPB_INLINE void _upb_msg_map_set_value(void* msg, const void* val, size_t size) {
+ upb_tabent *ent = (upb_tabent*)msg;
+ /* This is like _upb_map_tovalue() except the entry already exists so we can
+ * reuse the allocated upb_strview for string fields. */
+ if (size == UPB_MAPTYPE_STRING) {
+ upb_strview *strp = (upb_strview*)ent->val.val;
+ memcpy(strp, val, sizeof(*strp));
+ } else {
+ memcpy(&ent->val.val, val, size);
+ }
+}
+
#undef PTR_AT
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
-#endif /* UPB_GENERATED_UTIL_H_ */
+
+#endif /* UPB_MSG_H_ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+bool upb_decode(const char *buf, size_t size, upb_msg *msg,
+ const upb_msglayout *l, upb_arena *arena);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* UPB_DECODE_H_ */
+/*
+** upb_encode: parsing into a upb_msg using a upb_msglayout.
+*/
+
+#ifndef UPB_ENCODE_H_
+#define UPB_ENCODE_H_
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+char *upb_encode(const void *msg, const upb_msglayout *l, upb_arena *arena,
+ size_t *size);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* UPB_ENCODE_H_ */
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * google/protobuf/descriptor.proto
+ *
+ * Do not edit -- your changes will be discarded when the file is
+ * regenerated. */
+
+#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+#define GOOGLE_PROTOBUF_DESCRIPTOR_PROTO_UPB_H_
+
#ifdef __cplusplus
@@ -1381,7 +1513,7 @@
/* google.protobuf.FileDescriptorSet */
UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_new(upb_arena *arena) {
- return (google_protobuf_FileDescriptorSet *)upb_msg_new(&google_protobuf_FileDescriptorSet_msginit, arena);
+ return (google_protobuf_FileDescriptorSet *)_upb_msg_new(&google_protobuf_FileDescriptorSet_msginit, arena);
}
UPB_INLINE google_protobuf_FileDescriptorSet *google_protobuf_FileDescriptorSet_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1392,16 +1524,17 @@
return upb_encode(msg, &google_protobuf_FileDescriptorSet_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_FileDescriptorSet_has_file(const google_protobuf_FileDescriptorSet *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_FileDescriptorProto* const* google_protobuf_FileDescriptorSet_file(const google_protobuf_FileDescriptorSet *msg, size_t *len) { return (const google_protobuf_FileDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_mutable_file(google_protobuf_FileDescriptorSet *msg, size_t *len) {
return (google_protobuf_FileDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_FileDescriptorProto** google_protobuf_FileDescriptorSet_resize_file(google_protobuf_FileDescriptorSet *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FileDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FileDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FileDescriptorProto* google_protobuf_FileDescriptorSet_add_file(google_protobuf_FileDescriptorSet *msg, upb_arena *arena) {
- struct google_protobuf_FileDescriptorProto* sub = (struct google_protobuf_FileDescriptorProto*)upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
+ struct google_protobuf_FileDescriptorProto* sub = (struct google_protobuf_FileDescriptorProto*)_upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1411,7 +1544,7 @@
/* google.protobuf.FileDescriptorProto */
UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_FileDescriptorProto *)upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
+ return (google_protobuf_FileDescriptorProto *)_upb_msg_new(&google_protobuf_FileDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_FileDescriptorProto *google_protobuf_FileDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1423,49 +1556,53 @@
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_name(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_name(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_name(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_package(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_package(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)); }
+UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_package(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
UPB_INLINE upb_strview const* google_protobuf_FileDescriptorProto_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_message_type(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(40, 80)); }
UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_FileDescriptorProto_message_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_enum_type(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(44, 88)); }
UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_FileDescriptorProto_enum_type(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_service(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(48, 96)); }
UPB_INLINE const google_protobuf_ServiceDescriptorProto* const* google_protobuf_FileDescriptorProto_service(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_ServiceDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(48, 96), len); }
+UPB_INLINE bool google_protobuf_FileDescriptorProto_has_extension(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(52, 104)); }
UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_FileDescriptorProto_extension(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(52, 104), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_options(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE const google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_options(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_FileOptions*, UPB_SIZE(28, 56)); }
+UPB_INLINE const google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_options(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 56), const google_protobuf_FileOptions*); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE const google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_SourceCodeInfo*, UPB_SIZE(32, 64)); }
+UPB_INLINE const google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_source_code_info(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 64), const google_protobuf_SourceCodeInfo*); }
UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_public_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(56, 112), len); }
UPB_INLINE int32_t const* google_protobuf_FileDescriptorProto_weak_dependency(const google_protobuf_FileDescriptorProto *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(60, 120), len); }
UPB_INLINE bool google_protobuf_FileDescriptorProto_has_syntax(const google_protobuf_FileDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_syntax(const google_protobuf_FileDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)); }
+UPB_INLINE upb_strview google_protobuf_FileDescriptorProto_syntax(const google_protobuf_FileDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview); }
UPB_INLINE void google_protobuf_FileDescriptorProto_set_name(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_package(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
}
UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_mutable_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
}
UPB_INLINE upb_strview* google_protobuf_FileDescriptorProto_resize_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_add_dependency(google_protobuf_FileDescriptorProto *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(36, 72), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(36, 72), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_mutable_message_type(google_protobuf_FileDescriptorProto *msg, size_t *len) {
return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
}
UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_FileDescriptorProto_resize_message_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_FileDescriptorProto_add_message_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
+ struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1475,10 +1612,10 @@
return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
}
UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_FileDescriptorProto_resize_enum_type(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_FileDescriptorProto_add_enum_type(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
+ struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(44, 88), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1488,10 +1625,10 @@
return (google_protobuf_ServiceDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(48, 96), len);
}
UPB_INLINE google_protobuf_ServiceDescriptorProto** google_protobuf_FileDescriptorProto_resize_service(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_ServiceDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(48, 96), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_ServiceDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(48, 96), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_ServiceDescriptorProto* google_protobuf_FileDescriptorProto_add_service(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_ServiceDescriptorProto* sub = (struct google_protobuf_ServiceDescriptorProto*)upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
+ struct google_protobuf_ServiceDescriptorProto* sub = (struct google_protobuf_ServiceDescriptorProto*)_upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(48, 96), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1501,10 +1638,10 @@
return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(52, 104), len);
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_FileDescriptorProto_resize_extension(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(52, 104), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(52, 104), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_FileDescriptorProto_add_extension(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(52, 104), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1512,12 +1649,12 @@
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_options(google_protobuf_FileDescriptorProto *msg, google_protobuf_FileOptions* value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, google_protobuf_FileOptions*, UPB_SIZE(28, 56)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 56), google_protobuf_FileOptions*) = value;
}
UPB_INLINE struct google_protobuf_FileOptions* google_protobuf_FileDescriptorProto_mutable_options(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_FileOptions* sub = (struct google_protobuf_FileOptions*)google_protobuf_FileDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_FileOptions*)upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
+ sub = (struct google_protobuf_FileOptions*)_upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_FileDescriptorProto_set_options(msg, sub);
}
@@ -1525,12 +1662,12 @@
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_source_code_info(google_protobuf_FileDescriptorProto *msg, google_protobuf_SourceCodeInfo* value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, google_protobuf_SourceCodeInfo*, UPB_SIZE(32, 64)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(32, 64), google_protobuf_SourceCodeInfo*) = value;
}
UPB_INLINE struct google_protobuf_SourceCodeInfo* google_protobuf_FileDescriptorProto_mutable_source_code_info(google_protobuf_FileDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_SourceCodeInfo* sub = (struct google_protobuf_SourceCodeInfo*)google_protobuf_FileDescriptorProto_source_code_info(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_SourceCodeInfo*)upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
+ sub = (struct google_protobuf_SourceCodeInfo*)_upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
if (!sub) return NULL;
google_protobuf_FileDescriptorProto_set_source_code_info(msg, sub);
}
@@ -1540,31 +1677,31 @@
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 112), len);
}
UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_public_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(56, 112), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(56, 112), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_add_public_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(56, 112), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(56, 112), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_mutable_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(60, 120), len);
}
UPB_INLINE int32_t* google_protobuf_FileDescriptorProto_resize_weak_dependency(google_protobuf_FileDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(60, 120), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(60, 120), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_FileDescriptorProto_add_weak_dependency(google_protobuf_FileDescriptorProto *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(60, 120), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(60, 120), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE void google_protobuf_FileDescriptorProto_set_syntax(google_protobuf_FileDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview) = value;
}
/* google.protobuf.DescriptorProto */
UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_DescriptorProto *)upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
+ return (google_protobuf_DescriptorProto *)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_DescriptorProto *google_protobuf_DescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1576,30 +1713,37 @@
}
UPB_INLINE bool google_protobuf_DescriptorProto_has_name(const google_protobuf_DescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_DescriptorProto_name(const google_protobuf_DescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_DescriptorProto_name(const google_protobuf_DescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_field(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_field(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_nested_type(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40)); }
UPB_INLINE const google_protobuf_DescriptorProto* const* google_protobuf_DescriptorProto_nested_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_enum_type(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(24, 48)); }
UPB_INLINE const google_protobuf_EnumDescriptorProto* const* google_protobuf_DescriptorProto_enum_type(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_extension_range(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 56)); }
UPB_INLINE const google_protobuf_DescriptorProto_ExtensionRange* const* google_protobuf_DescriptorProto_extension_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ExtensionRange* const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_extension(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(32, 64)); }
UPB_INLINE const google_protobuf_FieldDescriptorProto* const* google_protobuf_DescriptorProto_extension(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_FieldDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(32, 64), len); }
UPB_INLINE bool google_protobuf_DescriptorProto_has_options(const google_protobuf_DescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_MessageOptions* google_protobuf_DescriptorProto_options(const google_protobuf_DescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_MessageOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_MessageOptions* google_protobuf_DescriptorProto_options(const google_protobuf_DescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_MessageOptions*); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_oneof_decl(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(36, 72)); }
UPB_INLINE const google_protobuf_OneofDescriptorProto* const* google_protobuf_DescriptorProto_oneof_decl(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_OneofDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(36, 72), len); }
+UPB_INLINE bool google_protobuf_DescriptorProto_has_reserved_range(const google_protobuf_DescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(40, 80)); }
UPB_INLINE const google_protobuf_DescriptorProto_ReservedRange* const* google_protobuf_DescriptorProto_reserved_range(const google_protobuf_DescriptorProto *msg, size_t *len) { return (const google_protobuf_DescriptorProto_ReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(40, 80), len); }
UPB_INLINE upb_strview const* google_protobuf_DescriptorProto_reserved_name(const google_protobuf_DescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(44, 88), len); }
UPB_INLINE void google_protobuf_DescriptorProto_set_name(google_protobuf_DescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_mutable_field(google_protobuf_DescriptorProto *msg, size_t *len) {
return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_field(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_field(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1609,10 +1753,10 @@
return (google_protobuf_DescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE google_protobuf_DescriptorProto** google_protobuf_DescriptorProto_resize_nested_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto* google_protobuf_DescriptorProto_add_nested_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
+ struct google_protobuf_DescriptorProto* sub = (struct google_protobuf_DescriptorProto*)_upb_msg_new(&google_protobuf_DescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1622,10 +1766,10 @@
return (google_protobuf_EnumDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE google_protobuf_EnumDescriptorProto** google_protobuf_DescriptorProto_resize_enum_type(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumDescriptorProto* google_protobuf_DescriptorProto_add_enum_type(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
+ struct google_protobuf_EnumDescriptorProto* sub = (struct google_protobuf_EnumDescriptorProto*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(24, 48), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1635,10 +1779,10 @@
return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
}
UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange** google_protobuf_DescriptorProto_resize_extension_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto_ExtensionRange**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto_ExtensionRange* google_protobuf_DescriptorProto_add_extension_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto_ExtensionRange* sub = (struct google_protobuf_DescriptorProto_ExtensionRange*)upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
+ struct google_protobuf_DescriptorProto_ExtensionRange* sub = (struct google_protobuf_DescriptorProto_ExtensionRange*)_upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(28, 56), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1648,10 +1792,10 @@
return (google_protobuf_FieldDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(32, 64), len);
}
UPB_INLINE google_protobuf_FieldDescriptorProto** google_protobuf_DescriptorProto_resize_extension(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(32, 64), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_FieldDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(32, 64), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_FieldDescriptorProto* google_protobuf_DescriptorProto_add_extension(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ struct google_protobuf_FieldDescriptorProto* sub = (struct google_protobuf_FieldDescriptorProto*)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(32, 64), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1659,12 +1803,12 @@
}
UPB_INLINE void google_protobuf_DescriptorProto_set_options(google_protobuf_DescriptorProto *msg, google_protobuf_MessageOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_MessageOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_MessageOptions*) = value;
}
UPB_INLINE struct google_protobuf_MessageOptions* google_protobuf_DescriptorProto_mutable_options(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_MessageOptions* sub = (struct google_protobuf_MessageOptions*)google_protobuf_DescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_MessageOptions*)upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
+ sub = (struct google_protobuf_MessageOptions*)_upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_DescriptorProto_set_options(msg, sub);
}
@@ -1674,10 +1818,10 @@
return (google_protobuf_OneofDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(36, 72), len);
}
UPB_INLINE google_protobuf_OneofDescriptorProto** google_protobuf_DescriptorProto_resize_oneof_decl(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_OneofDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_OneofDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(36, 72), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_OneofDescriptorProto* google_protobuf_DescriptorProto_add_oneof_decl(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_OneofDescriptorProto* sub = (struct google_protobuf_OneofDescriptorProto*)upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
+ struct google_protobuf_OneofDescriptorProto* sub = (struct google_protobuf_OneofDescriptorProto*)_upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(36, 72), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1687,10 +1831,10 @@
return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(40, 80), len);
}
UPB_INLINE google_protobuf_DescriptorProto_ReservedRange** google_protobuf_DescriptorProto_resize_reserved_range(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_DescriptorProto_ReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(40, 80), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_DescriptorProto_ReservedRange* google_protobuf_DescriptorProto_add_reserved_range(google_protobuf_DescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_DescriptorProto_ReservedRange* sub = (struct google_protobuf_DescriptorProto_ReservedRange*)upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
+ struct google_protobuf_DescriptorProto_ReservedRange* sub = (struct google_protobuf_DescriptorProto_ReservedRange*)_upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(40, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1700,17 +1844,17 @@
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(44, 88), len);
}
UPB_INLINE upb_strview* google_protobuf_DescriptorProto_resize_reserved_name(google_protobuf_DescriptorProto *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(44, 88), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_DescriptorProto_add_reserved_name(google_protobuf_DescriptorProto *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(44, 88), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(44, 88), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
/* google.protobuf.DescriptorProto.ExtensionRange */
UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_new(upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ExtensionRange *)upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
+ return (google_protobuf_DescriptorProto_ExtensionRange *)_upb_msg_new(&google_protobuf_DescriptorProto_ExtensionRange_msginit, arena);
}
UPB_INLINE google_protobuf_DescriptorProto_ExtensionRange *google_protobuf_DescriptorProto_ExtensionRange_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1722,28 +1866,28 @@
}
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_start(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ExtensionRange_end(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ExtensionRange_has_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE const google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return UPB_FIELD_AT(msg, const google_protobuf_ExtensionRangeOptions*, UPB_SIZE(12, 16)); }
+UPB_INLINE const google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_options(const google_protobuf_DescriptorProto_ExtensionRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 16), const google_protobuf_ExtensionRangeOptions*); }
UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_start(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_end(google_protobuf_DescriptorProto_ExtensionRange *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_DescriptorProto_ExtensionRange_set_options(google_protobuf_DescriptorProto_ExtensionRange *msg, google_protobuf_ExtensionRangeOptions* value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, google_protobuf_ExtensionRangeOptions*, UPB_SIZE(12, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 16), google_protobuf_ExtensionRangeOptions*) = value;
}
UPB_INLINE struct google_protobuf_ExtensionRangeOptions* google_protobuf_DescriptorProto_ExtensionRange_mutable_options(google_protobuf_DescriptorProto_ExtensionRange *msg, upb_arena *arena) {
struct google_protobuf_ExtensionRangeOptions* sub = (struct google_protobuf_ExtensionRangeOptions*)google_protobuf_DescriptorProto_ExtensionRange_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_ExtensionRangeOptions*)upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
+ sub = (struct google_protobuf_ExtensionRangeOptions*)_upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_DescriptorProto_ExtensionRange_set_options(msg, sub);
}
@@ -1753,7 +1897,7 @@
/* google.protobuf.DescriptorProto.ReservedRange */
UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_new(upb_arena *arena) {
- return (google_protobuf_DescriptorProto_ReservedRange *)upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
+ return (google_protobuf_DescriptorProto_ReservedRange *)_upb_msg_new(&google_protobuf_DescriptorProto_ReservedRange_msginit, arena);
}
UPB_INLINE google_protobuf_DescriptorProto_ReservedRange *google_protobuf_DescriptorProto_ReservedRange_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1765,23 +1909,23 @@
}
UPB_INLINE bool google_protobuf_DescriptorProto_ReservedRange_has_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_start(const google_protobuf_DescriptorProto_ReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_DescriptorProto_ReservedRange_has_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_DescriptorProto_ReservedRange_end(const google_protobuf_DescriptorProto_ReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_start(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_DescriptorProto_ReservedRange_set_end(google_protobuf_DescriptorProto_ReservedRange *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
/* google.protobuf.ExtensionRangeOptions */
UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_new(upb_arena *arena) {
- return (google_protobuf_ExtensionRangeOptions *)upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
+ return (google_protobuf_ExtensionRangeOptions *)_upb_msg_new(&google_protobuf_ExtensionRangeOptions_msginit, arena);
}
UPB_INLINE google_protobuf_ExtensionRangeOptions *google_protobuf_ExtensionRangeOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1792,16 +1936,17 @@
return upb_encode(msg, &google_protobuf_ExtensionRangeOptions_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_ExtensionRangeOptions_has_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ExtensionRangeOptions_uninterpreted_option(const google_protobuf_ExtensionRangeOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_mutable_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ExtensionRangeOptions_resize_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ExtensionRangeOptions_add_uninterpreted_option(google_protobuf_ExtensionRangeOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1811,7 +1956,7 @@
/* google.protobuf.FieldDescriptorProto */
UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_FieldDescriptorProto *)upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
+ return (google_protobuf_FieldDescriptorProto *)_upb_msg_new(&google_protobuf_FieldDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_FieldDescriptorProto *google_protobuf_FieldDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1822,63 +1967,65 @@
return upb_encode(msg, &google_protobuf_FieldDescriptorProto_msginit, arena, len);
}
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_name(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_extendee(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_extendee(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 6); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(36, 40), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_extendee(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 7); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_extendee(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(44, 56), upb_strview); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_number(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_number(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(24, 24)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_number(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), int32_t); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_label(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_label(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_label(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_type(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_type(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_type_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 7); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_type_name(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_default_value(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 8); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_default_value(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(56, 80)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_options(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 10); }
-UPB_INLINE const google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_options(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_FieldOptions*, UPB_SIZE(72, 112)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_type(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_type_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 8); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_type_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(52, 72), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_default_value(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 9); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_default_value(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(60, 88), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_options(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 11); }
+UPB_INLINE const google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_options(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(76, 120), const google_protobuf_FieldOptions*); }
UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_oneof_index(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_oneof_index(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(28, 28)); }
-UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_json_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 9); }
-UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_json_name(const google_protobuf_FieldDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(64, 96)); }
+UPB_INLINE int32_t google_protobuf_FieldDescriptorProto_oneof_index(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 28), int32_t); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_json_name(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 10); }
+UPB_INLINE upb_strview google_protobuf_FieldDescriptorProto_json_name(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(68, 104), upb_strview); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_has_proto3_optional(const google_protobuf_FieldDescriptorProto *msg) { return _upb_has_field(msg, 5); }
+UPB_INLINE bool google_protobuf_FieldDescriptorProto_proto3_optional(const google_protobuf_FieldDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), bool); }
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)) = value;
+ _upb_sethas(msg, 6);
+ *UPB_PTR_AT(msg, UPB_SIZE(36, 40), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_extendee(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)) = value;
+ _upb_sethas(msg, 7);
+ *UPB_PTR_AT(msg, UPB_SIZE(44, 56), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_number(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_label(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_type_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 7);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)) = value;
+ _upb_sethas(msg, 8);
+ *UPB_PTR_AT(msg, UPB_SIZE(52, 72), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_default_value(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 8);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(56, 80)) = value;
+ _upb_sethas(msg, 9);
+ *UPB_PTR_AT(msg, UPB_SIZE(60, 88), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_options(google_protobuf_FieldDescriptorProto *msg, google_protobuf_FieldOptions* value) {
- _upb_sethas(msg, 10);
- UPB_FIELD_AT(msg, google_protobuf_FieldOptions*, UPB_SIZE(72, 112)) = value;
+ _upb_sethas(msg, 11);
+ *UPB_PTR_AT(msg, UPB_SIZE(76, 120), google_protobuf_FieldOptions*) = value;
}
UPB_INLINE struct google_protobuf_FieldOptions* google_protobuf_FieldDescriptorProto_mutable_options(google_protobuf_FieldDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_FieldOptions* sub = (struct google_protobuf_FieldOptions*)google_protobuf_FieldDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_FieldOptions*)upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
+ sub = (struct google_protobuf_FieldOptions*)_upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_FieldDescriptorProto_set_options(msg, sub);
}
@@ -1886,17 +2033,21 @@
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_oneof_index(google_protobuf_FieldDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(28, 28)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 28), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldDescriptorProto_set_json_name(google_protobuf_FieldDescriptorProto *msg, upb_strview value) {
- _upb_sethas(msg, 9);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(64, 96)) = value;
+ _upb_sethas(msg, 10);
+ *UPB_PTR_AT(msg, UPB_SIZE(68, 104), upb_strview) = value;
+}
+UPB_INLINE void google_protobuf_FieldDescriptorProto_set_proto3_optional(google_protobuf_FieldDescriptorProto *msg, bool value) {
+ _upb_sethas(msg, 5);
+ *UPB_PTR_AT(msg, UPB_SIZE(32, 32), bool) = value;
}
/* google.protobuf.OneofDescriptorProto */
UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_OneofDescriptorProto *)upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
+ return (google_protobuf_OneofDescriptorProto *)_upb_msg_new(&google_protobuf_OneofDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_OneofDescriptorProto *google_protobuf_OneofDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1908,22 +2059,22 @@
}
UPB_INLINE bool google_protobuf_OneofDescriptorProto_has_name(const google_protobuf_OneofDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_OneofDescriptorProto_name(const google_protobuf_OneofDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_OneofDescriptorProto_name(const google_protobuf_OneofDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_OneofDescriptorProto_has_options(const google_protobuf_OneofDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_options(const google_protobuf_OneofDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_OneofOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_options(const google_protobuf_OneofDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_OneofOptions*); }
UPB_INLINE void google_protobuf_OneofDescriptorProto_set_name(google_protobuf_OneofDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_OneofDescriptorProto_set_options(google_protobuf_OneofDescriptorProto *msg, google_protobuf_OneofOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_OneofOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_OneofOptions*) = value;
}
UPB_INLINE struct google_protobuf_OneofOptions* google_protobuf_OneofDescriptorProto_mutable_options(google_protobuf_OneofDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_OneofOptions* sub = (struct google_protobuf_OneofOptions*)google_protobuf_OneofDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_OneofOptions*)upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
+ sub = (struct google_protobuf_OneofOptions*)_upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_OneofDescriptorProto_set_options(msg, sub);
}
@@ -1933,7 +2084,7 @@
/* google.protobuf.EnumDescriptorProto */
UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto *)upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
+ return (google_protobuf_EnumDescriptorProto *)_upb_msg_new(&google_protobuf_EnumDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_EnumDescriptorProto *google_protobuf_EnumDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -1945,25 +2096,27 @@
}
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_name(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_EnumDescriptorProto_name(const google_protobuf_EnumDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_EnumDescriptorProto_name(const google_protobuf_EnumDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
+UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_value(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
UPB_INLINE const google_protobuf_EnumValueDescriptorProto* const* google_protobuf_EnumDescriptorProto_value(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumValueDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_options(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_options(const google_protobuf_EnumDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_EnumOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_options(const google_protobuf_EnumDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_EnumOptions*); }
+UPB_INLINE bool google_protobuf_EnumDescriptorProto_has_reserved_range(const google_protobuf_EnumDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40)); }
UPB_INLINE const google_protobuf_EnumDescriptorProto_EnumReservedRange* const* google_protobuf_EnumDescriptorProto_reserved_range(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (const google_protobuf_EnumDescriptorProto_EnumReservedRange* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
UPB_INLINE upb_strview const* google_protobuf_EnumDescriptorProto_reserved_name(const google_protobuf_EnumDescriptorProto *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE void google_protobuf_EnumDescriptorProto_set_name(google_protobuf_EnumDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_mutable_value(google_protobuf_EnumDescriptorProto *msg, size_t *len) {
return (google_protobuf_EnumValueDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
}
UPB_INLINE google_protobuf_EnumValueDescriptorProto** google_protobuf_EnumDescriptorProto_resize_value(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumValueDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumValueDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumValueDescriptorProto* google_protobuf_EnumDescriptorProto_add_value(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumValueDescriptorProto* sub = (struct google_protobuf_EnumValueDescriptorProto*)upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
+ struct google_protobuf_EnumValueDescriptorProto* sub = (struct google_protobuf_EnumValueDescriptorProto*)_upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1971,12 +2124,12 @@
}
UPB_INLINE void google_protobuf_EnumDescriptorProto_set_options(google_protobuf_EnumDescriptorProto *msg, google_protobuf_EnumOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_EnumOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_EnumOptions*) = value;
}
UPB_INLINE struct google_protobuf_EnumOptions* google_protobuf_EnumDescriptorProto_mutable_options(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumOptions* sub = (struct google_protobuf_EnumOptions*)google_protobuf_EnumDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_EnumOptions*)upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
+ sub = (struct google_protobuf_EnumOptions*)_upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_EnumDescriptorProto_set_options(msg, sub);
}
@@ -1986,10 +2139,10 @@
return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange** google_protobuf_EnumDescriptorProto_resize_reserved_range(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_EnumDescriptorProto_EnumReservedRange**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_EnumDescriptorProto_EnumReservedRange* google_protobuf_EnumDescriptorProto_add_reserved_range(google_protobuf_EnumDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_EnumDescriptorProto_EnumReservedRange* sub = (struct google_protobuf_EnumDescriptorProto_EnumReservedRange*)upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
+ struct google_protobuf_EnumDescriptorProto_EnumReservedRange* sub = (struct google_protobuf_EnumDescriptorProto_EnumReservedRange*)_upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(20, 40), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -1999,17 +2152,17 @@
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE upb_strview* google_protobuf_EnumDescriptorProto_resize_reserved_name(google_protobuf_EnumDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_EnumDescriptorProto_add_reserved_name(google_protobuf_EnumDescriptorProto *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(24, 48), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(24, 48), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
/* google.protobuf.EnumDescriptorProto.EnumReservedRange */
UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_new(upb_arena *arena) {
- return (google_protobuf_EnumDescriptorProto_EnumReservedRange *)upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
+ return (google_protobuf_EnumDescriptorProto_EnumReservedRange *)_upb_msg_new(&google_protobuf_EnumDescriptorProto_EnumReservedRange_msginit, arena);
}
UPB_INLINE google_protobuf_EnumDescriptorProto_EnumReservedRange *google_protobuf_EnumDescriptorProto_EnumReservedRange_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2021,23 +2174,23 @@
}
UPB_INLINE bool google_protobuf_EnumDescriptorProto_EnumReservedRange_has_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_start(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_EnumDescriptorProto_EnumReservedRange_has_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_EnumDescriptorProto_EnumReservedRange_end(const google_protobuf_EnumDescriptorProto_EnumReservedRange *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_start(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_EnumDescriptorProto_EnumReservedRange_set_end(google_protobuf_EnumDescriptorProto_EnumReservedRange *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
/* google.protobuf.EnumValueDescriptorProto */
UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_EnumValueDescriptorProto *)upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
+ return (google_protobuf_EnumValueDescriptorProto *)_upb_msg_new(&google_protobuf_EnumValueDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_EnumValueDescriptorProto *google_protobuf_EnumValueDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2049,28 +2202,28 @@
}
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_name(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_EnumValueDescriptorProto_name(const google_protobuf_EnumValueDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(8, 8)); }
+UPB_INLINE upb_strview google_protobuf_EnumValueDescriptorProto_name(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview); }
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_number(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_EnumValueDescriptorProto_number(const google_protobuf_EnumValueDescriptorProto *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_EnumValueDescriptorProto_number(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_EnumValueDescriptorProto_has_options(const google_protobuf_EnumValueDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE const google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_options(const google_protobuf_EnumValueDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_EnumValueOptions*, UPB_SIZE(16, 24)); }
+UPB_INLINE const google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_options(const google_protobuf_EnumValueDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 24), const google_protobuf_EnumValueOptions*); }
UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_name(google_protobuf_EnumValueDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_number(google_protobuf_EnumValueDescriptorProto *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_EnumValueDescriptorProto_set_options(google_protobuf_EnumValueDescriptorProto *msg, google_protobuf_EnumValueOptions* value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, google_protobuf_EnumValueOptions*, UPB_SIZE(16, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 24), google_protobuf_EnumValueOptions*) = value;
}
UPB_INLINE struct google_protobuf_EnumValueOptions* google_protobuf_EnumValueDescriptorProto_mutable_options(google_protobuf_EnumValueDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_EnumValueOptions* sub = (struct google_protobuf_EnumValueOptions*)google_protobuf_EnumValueDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_EnumValueOptions*)upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
+ sub = (struct google_protobuf_EnumValueOptions*)_upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_EnumValueDescriptorProto_set_options(msg, sub);
}
@@ -2080,7 +2233,7 @@
/* google.protobuf.ServiceDescriptorProto */
UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_ServiceDescriptorProto *)upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
+ return (google_protobuf_ServiceDescriptorProto *)_upb_msg_new(&google_protobuf_ServiceDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_ServiceDescriptorProto *google_protobuf_ServiceDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2092,23 +2245,24 @@
}
UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_name(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_ServiceDescriptorProto_name(const google_protobuf_ServiceDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_ServiceDescriptorProto_name(const google_protobuf_ServiceDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
+UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_method(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(16, 32)); }
UPB_INLINE const google_protobuf_MethodDescriptorProto* const* google_protobuf_ServiceDescriptorProto_method(const google_protobuf_ServiceDescriptorProto *msg, size_t *len) { return (const google_protobuf_MethodDescriptorProto* const*)_upb_array_accessor(msg, UPB_SIZE(16, 32), len); }
UPB_INLINE bool google_protobuf_ServiceDescriptorProto_has_options(const google_protobuf_ServiceDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE const google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_options(const google_protobuf_ServiceDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_ServiceOptions*, UPB_SIZE(12, 24)); }
+UPB_INLINE const google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_options(const google_protobuf_ServiceDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), const google_protobuf_ServiceOptions*); }
UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_name(google_protobuf_ServiceDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_mutable_method(google_protobuf_ServiceDescriptorProto *msg, size_t *len) {
return (google_protobuf_MethodDescriptorProto**)_upb_array_mutable_accessor(msg, UPB_SIZE(16, 32), len);
}
UPB_INLINE google_protobuf_MethodDescriptorProto** google_protobuf_ServiceDescriptorProto_resize_method(google_protobuf_ServiceDescriptorProto *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_MethodDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_MethodDescriptorProto**)_upb_array_resize_accessor(msg, UPB_SIZE(16, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_MethodDescriptorProto* google_protobuf_ServiceDescriptorProto_add_method(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
- struct google_protobuf_MethodDescriptorProto* sub = (struct google_protobuf_MethodDescriptorProto*)upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
+ struct google_protobuf_MethodDescriptorProto* sub = (struct google_protobuf_MethodDescriptorProto*)_upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(16, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2116,12 +2270,12 @@
}
UPB_INLINE void google_protobuf_ServiceDescriptorProto_set_options(google_protobuf_ServiceDescriptorProto *msg, google_protobuf_ServiceOptions* value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, google_protobuf_ServiceOptions*, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), google_protobuf_ServiceOptions*) = value;
}
UPB_INLINE struct google_protobuf_ServiceOptions* google_protobuf_ServiceDescriptorProto_mutable_options(google_protobuf_ServiceDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_ServiceOptions* sub = (struct google_protobuf_ServiceOptions*)google_protobuf_ServiceDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_ServiceOptions*)upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
+ sub = (struct google_protobuf_ServiceOptions*)_upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_ServiceDescriptorProto_set_options(msg, sub);
}
@@ -2131,7 +2285,7 @@
/* google.protobuf.MethodDescriptorProto */
UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_new(upb_arena *arena) {
- return (google_protobuf_MethodDescriptorProto *)upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
+ return (google_protobuf_MethodDescriptorProto *)_upb_msg_new(&google_protobuf_MethodDescriptorProto_msginit, arena);
}
UPB_INLINE google_protobuf_MethodDescriptorProto *google_protobuf_MethodDescriptorProto_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2143,38 +2297,38 @@
}
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_name(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_name(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_name(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_input_type(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_input_type(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)); }
+UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_input_type(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_output_type(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_output_type(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)); }
+UPB_INLINE upb_strview google_protobuf_MethodDescriptorProto_output_type(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_options(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE const google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_options(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, const google_protobuf_MethodOptions*, UPB_SIZE(28, 56)); }
+UPB_INLINE const google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_options(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 56), const google_protobuf_MethodOptions*); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_client_streaming(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_MethodDescriptorProto_client_streaming(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_MethodDescriptorProto_client_streaming(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_MethodDescriptorProto_has_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_MethodDescriptorProto_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)); }
+UPB_INLINE bool google_protobuf_MethodDescriptorProto_server_streaming(const google_protobuf_MethodDescriptorProto *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_name(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_input_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_output_type(google_protobuf_MethodDescriptorProto *msg, upb_strview value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(20, 40)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(20, 40), upb_strview) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_options(google_protobuf_MethodDescriptorProto *msg, google_protobuf_MethodOptions* value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, google_protobuf_MethodOptions*, UPB_SIZE(28, 56)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 56), google_protobuf_MethodOptions*) = value;
}
UPB_INLINE struct google_protobuf_MethodOptions* google_protobuf_MethodDescriptorProto_mutable_options(google_protobuf_MethodDescriptorProto *msg, upb_arena *arena) {
struct google_protobuf_MethodOptions* sub = (struct google_protobuf_MethodOptions*)google_protobuf_MethodDescriptorProto_options(msg);
if (sub == NULL) {
- sub = (struct google_protobuf_MethodOptions*)upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
+ sub = (struct google_protobuf_MethodOptions*)_upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
if (!sub) return NULL;
google_protobuf_MethodDescriptorProto_set_options(msg, sub);
}
@@ -2182,17 +2336,17 @@
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_client_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE void google_protobuf_MethodDescriptorProto_set_server_streaming(google_protobuf_MethodDescriptorProto *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
}
/* google.protobuf.FileOptions */
UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_new(upb_arena *arena) {
- return (google_protobuf_FileOptions *)upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
+ return (google_protobuf_FileOptions *)_upb_msg_new(&google_protobuf_FileOptions_msginit, arena);
}
UPB_INLINE google_protobuf_FileOptions *google_protobuf_FileOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2204,135 +2358,136 @@
}
UPB_INLINE bool google_protobuf_FileOptions_has_java_package(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 11); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_java_package(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(28, 32)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_java_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(28, 32), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_outer_classname(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 12); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_java_outer_classname(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(36, 48)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_java_outer_classname(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(36, 48), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_optimize_for(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_FileOptions_optimize_for(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_FileOptions_optimize_for(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_multiple_files(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_FileOptions_java_multiple_files(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_multiple_files(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_go_package(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 13); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_go_package(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(44, 64)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_go_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(44, 64), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_cc_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE bool google_protobuf_FileOptions_cc_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(17, 17)); }
+UPB_INLINE bool google_protobuf_FileOptions_cc_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(17, 17), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE bool google_protobuf_FileOptions_java_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(18, 18)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(18, 18), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_py_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE bool google_protobuf_FileOptions_py_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(19, 19)); }
+UPB_INLINE bool google_protobuf_FileOptions_py_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(19, 19), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE bool google_protobuf_FileOptions_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(20, 20)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_generate_equals_and_hash(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(20, 20), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_deprecated(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 7); }
-UPB_INLINE bool google_protobuf_FileOptions_deprecated(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(21, 21)); }
+UPB_INLINE bool google_protobuf_FileOptions_deprecated(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(21, 21), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_java_string_check_utf8(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 8); }
-UPB_INLINE bool google_protobuf_FileOptions_java_string_check_utf8(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(22, 22)); }
+UPB_INLINE bool google_protobuf_FileOptions_java_string_check_utf8(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(22, 22), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_cc_enable_arenas(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 9); }
-UPB_INLINE bool google_protobuf_FileOptions_cc_enable_arenas(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(23, 23)); }
+UPB_INLINE bool google_protobuf_FileOptions_cc_enable_arenas(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(23, 23), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_objc_class_prefix(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 14); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_objc_class_prefix(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(52, 80)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_objc_class_prefix(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(52, 80), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_csharp_namespace(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 15); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_csharp_namespace(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(60, 96)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_csharp_namespace(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(60, 96), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_swift_prefix(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 16); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_swift_prefix(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(68, 112)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_swift_prefix(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(68, 112), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_class_prefix(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 17); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_php_class_prefix(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(76, 128)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_php_class_prefix(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(76, 128), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_namespace(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 18); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_php_namespace(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(84, 144)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_php_namespace(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(84, 144), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_generic_services(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 10); }
-UPB_INLINE bool google_protobuf_FileOptions_php_generic_services(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)); }
+UPB_INLINE bool google_protobuf_FileOptions_php_generic_services(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool); }
UPB_INLINE bool google_protobuf_FileOptions_has_php_metadata_namespace(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 19); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_php_metadata_namespace(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(92, 160)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_php_metadata_namespace(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(92, 160), upb_strview); }
UPB_INLINE bool google_protobuf_FileOptions_has_ruby_package(const google_protobuf_FileOptions *msg) { return _upb_has_field(msg, 20); }
-UPB_INLINE upb_strview google_protobuf_FileOptions_ruby_package(const google_protobuf_FileOptions *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(100, 176)); }
+UPB_INLINE upb_strview google_protobuf_FileOptions_ruby_package(const google_protobuf_FileOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(100, 176), upb_strview); }
+UPB_INLINE bool google_protobuf_FileOptions_has_uninterpreted_option(const google_protobuf_FileOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(108, 192)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FileOptions_uninterpreted_option(const google_protobuf_FileOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(108, 192), len); }
UPB_INLINE void google_protobuf_FileOptions_set_java_package(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 11);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(28, 32)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(28, 32), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_outer_classname(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 12);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(36, 48)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(36, 48), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_optimize_for(google_protobuf_FileOptions *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_multiple_files(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_go_package(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 13);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(44, 64)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(44, 64), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_cc_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(17, 17)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(17, 17), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(18, 18)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(18, 18), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_py_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(19, 19)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(19, 19), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_generate_equals_and_hash(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(20, 20)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(20, 20), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_deprecated(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 7);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(21, 21)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(21, 21), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_java_string_check_utf8(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 8);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(22, 22)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(22, 22), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_cc_enable_arenas(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 9);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(23, 23)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(23, 23), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_objc_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 14);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(52, 80)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(52, 80), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_csharp_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 15);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(60, 96)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(60, 96), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_swift_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 16);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(68, 112)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(68, 112), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_class_prefix(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 17);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(76, 128)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(76, 128), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 18);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(84, 144)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(84, 144), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_generic_services(google_protobuf_FileOptions *msg, bool value) {
_upb_sethas(msg, 10);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_php_metadata_namespace(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 19);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(92, 160)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(92, 160), upb_strview) = value;
}
UPB_INLINE void google_protobuf_FileOptions_set_ruby_package(google_protobuf_FileOptions *msg, upb_strview value) {
_upb_sethas(msg, 20);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(100, 176)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(100, 176), upb_strview) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_mutable_uninterpreted_option(google_protobuf_FileOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(108, 192), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FileOptions_resize_uninterpreted_option(google_protobuf_FileOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(108, 192), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(108, 192), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FileOptions_add_uninterpreted_option(google_protobuf_FileOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(108, 192), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2342,7 +2497,7 @@
/* google.protobuf.MessageOptions */
UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_new(upb_arena *arena) {
- return (google_protobuf_MessageOptions *)upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
+ return (google_protobuf_MessageOptions *)_upb_msg_new(&google_protobuf_MessageOptions_msginit, arena);
}
UPB_INLINE google_protobuf_MessageOptions *google_protobuf_MessageOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2354,39 +2509,40 @@
}
UPB_INLINE bool google_protobuf_MessageOptions_has_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_MessageOptions_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_MessageOptions_message_set_wire_format(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_MessageOptions_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)); }
+UPB_INLINE bool google_protobuf_MessageOptions_no_standard_descriptor_accessor(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_deprecated(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE bool google_protobuf_MessageOptions_deprecated(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(3, 3)); }
+UPB_INLINE bool google_protobuf_MessageOptions_deprecated(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(3, 3), bool); }
UPB_INLINE bool google_protobuf_MessageOptions_has_map_entry(const google_protobuf_MessageOptions *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE bool google_protobuf_MessageOptions_map_entry(const google_protobuf_MessageOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(4, 4)); }
+UPB_INLINE bool google_protobuf_MessageOptions_map_entry(const google_protobuf_MessageOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool); }
+UPB_INLINE bool google_protobuf_MessageOptions_has_uninterpreted_option(const google_protobuf_MessageOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(8, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MessageOptions_uninterpreted_option(const google_protobuf_MessageOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(8, 8), len); }
UPB_INLINE void google_protobuf_MessageOptions_set_message_set_wire_format(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE void google_protobuf_MessageOptions_set_no_standard_descriptor_accessor(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
}
UPB_INLINE void google_protobuf_MessageOptions_set_deprecated(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(3, 3)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(3, 3), bool) = value;
}
UPB_INLINE void google_protobuf_MessageOptions_set_map_entry(google_protobuf_MessageOptions *msg, bool value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_mutable_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(8, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MessageOptions_resize_uninterpreted_option(google_protobuf_MessageOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(8, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(8, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MessageOptions_add_uninterpreted_option(google_protobuf_MessageOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(8, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2396,7 +2552,7 @@
/* google.protobuf.FieldOptions */
UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_new(upb_arena *arena) {
- return (google_protobuf_FieldOptions *)upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
+ return (google_protobuf_FieldOptions *)_upb_msg_new(&google_protobuf_FieldOptions_msginit, arena);
}
UPB_INLINE google_protobuf_FieldOptions *google_protobuf_FieldOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2408,51 +2564,52 @@
}
UPB_INLINE bool google_protobuf_FieldOptions_has_ctype(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_FieldOptions_ctype(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_FieldOptions_ctype(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE bool google_protobuf_FieldOptions_has_packed(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE bool google_protobuf_FieldOptions_packed(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)); }
+UPB_INLINE bool google_protobuf_FieldOptions_packed(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool); }
UPB_INLINE bool google_protobuf_FieldOptions_has_deprecated(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE bool google_protobuf_FieldOptions_deprecated(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(25, 25)); }
+UPB_INLINE bool google_protobuf_FieldOptions_deprecated(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(25, 25), bool); }
UPB_INLINE bool google_protobuf_FieldOptions_has_lazy(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE bool google_protobuf_FieldOptions_lazy(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(26, 26)); }
+UPB_INLINE bool google_protobuf_FieldOptions_lazy(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(26, 26), bool); }
UPB_INLINE bool google_protobuf_FieldOptions_has_jstype(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_FieldOptions_jstype(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)); }
+UPB_INLINE int32_t google_protobuf_FieldOptions_jstype(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t); }
UPB_INLINE bool google_protobuf_FieldOptions_has_weak(const google_protobuf_FieldOptions *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE bool google_protobuf_FieldOptions_weak(const google_protobuf_FieldOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(27, 27)); }
+UPB_INLINE bool google_protobuf_FieldOptions_weak(const google_protobuf_FieldOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(27, 27), bool); }
+UPB_INLINE bool google_protobuf_FieldOptions_has_uninterpreted_option(const google_protobuf_FieldOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(28, 32)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_FieldOptions_uninterpreted_option(const google_protobuf_FieldOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(28, 32), len); }
UPB_INLINE void google_protobuf_FieldOptions_set_ctype(google_protobuf_FieldOptions *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_packed(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), bool) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_deprecated(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(25, 25)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(25, 25), bool) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_lazy(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(26, 26)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(26, 26), bool) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_jstype(google_protobuf_FieldOptions *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int32_t) = value;
}
UPB_INLINE void google_protobuf_FieldOptions_set_weak(google_protobuf_FieldOptions *msg, bool value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(27, 27)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(27, 27), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_mutable_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 32), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_FieldOptions_resize_uninterpreted_option(google_protobuf_FieldOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(28, 32), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_FieldOptions_add_uninterpreted_option(google_protobuf_FieldOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(28, 32), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2462,7 +2619,7 @@
/* google.protobuf.OneofOptions */
UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_new(upb_arena *arena) {
- return (google_protobuf_OneofOptions *)upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
+ return (google_protobuf_OneofOptions *)_upb_msg_new(&google_protobuf_OneofOptions_msginit, arena);
}
UPB_INLINE google_protobuf_OneofOptions *google_protobuf_OneofOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2473,16 +2630,17 @@
return upb_encode(msg, &google_protobuf_OneofOptions_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_OneofOptions_has_uninterpreted_option(const google_protobuf_OneofOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_OneofOptions_uninterpreted_option(const google_protobuf_OneofOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_mutable_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_OneofOptions_resize_uninterpreted_option(google_protobuf_OneofOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_OneofOptions_add_uninterpreted_option(google_protobuf_OneofOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2492,7 +2650,7 @@
/* google.protobuf.EnumOptions */
UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_new(upb_arena *arena) {
- return (google_protobuf_EnumOptions *)upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
+ return (google_protobuf_EnumOptions *)_upb_msg_new(&google_protobuf_EnumOptions_msginit, arena);
}
UPB_INLINE google_protobuf_EnumOptions *google_protobuf_EnumOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2504,27 +2662,28 @@
}
UPB_INLINE bool google_protobuf_EnumOptions_has_allow_alias(const google_protobuf_EnumOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_EnumOptions_allow_alias(const google_protobuf_EnumOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_EnumOptions_allow_alias(const google_protobuf_EnumOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE bool google_protobuf_EnumOptions_has_deprecated(const google_protobuf_EnumOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_EnumOptions_deprecated(const google_protobuf_EnumOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)); }
+UPB_INLINE bool google_protobuf_EnumOptions_deprecated(const google_protobuf_EnumOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); }
+UPB_INLINE bool google_protobuf_EnumOptions_has_uninterpreted_option(const google_protobuf_EnumOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumOptions_uninterpreted_option(const google_protobuf_EnumOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
UPB_INLINE void google_protobuf_EnumOptions_set_allow_alias(google_protobuf_EnumOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE void google_protobuf_EnumOptions_set_deprecated(google_protobuf_EnumOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(2, 2)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_mutable_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumOptions_resize_uninterpreted_option(google_protobuf_EnumOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumOptions_add_uninterpreted_option(google_protobuf_EnumOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2534,7 +2693,7 @@
/* google.protobuf.EnumValueOptions */
UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_new(upb_arena *arena) {
- return (google_protobuf_EnumValueOptions *)upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
+ return (google_protobuf_EnumValueOptions *)_upb_msg_new(&google_protobuf_EnumValueOptions_msginit, arena);
}
UPB_INLINE google_protobuf_EnumValueOptions *google_protobuf_EnumValueOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2546,21 +2705,22 @@
}
UPB_INLINE bool google_protobuf_EnumValueOptions_has_deprecated(const google_protobuf_EnumValueOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_EnumValueOptions_deprecated(const google_protobuf_EnumValueOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_EnumValueOptions_deprecated(const google_protobuf_EnumValueOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
+UPB_INLINE bool google_protobuf_EnumValueOptions_has_uninterpreted_option(const google_protobuf_EnumValueOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_EnumValueOptions_uninterpreted_option(const google_protobuf_EnumValueOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
UPB_INLINE void google_protobuf_EnumValueOptions_set_deprecated(google_protobuf_EnumValueOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_mutable_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_EnumValueOptions_resize_uninterpreted_option(google_protobuf_EnumValueOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_EnumValueOptions_add_uninterpreted_option(google_protobuf_EnumValueOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2570,7 +2730,7 @@
/* google.protobuf.ServiceOptions */
UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_new(upb_arena *arena) {
- return (google_protobuf_ServiceOptions *)upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
+ return (google_protobuf_ServiceOptions *)_upb_msg_new(&google_protobuf_ServiceOptions_msginit, arena);
}
UPB_INLINE google_protobuf_ServiceOptions *google_protobuf_ServiceOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2582,21 +2742,22 @@
}
UPB_INLINE bool google_protobuf_ServiceOptions_has_deprecated(const google_protobuf_ServiceOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_ServiceOptions_deprecated(const google_protobuf_ServiceOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_ServiceOptions_deprecated(const google_protobuf_ServiceOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
+UPB_INLINE bool google_protobuf_ServiceOptions_has_uninterpreted_option(const google_protobuf_ServiceOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(4, 8)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_ServiceOptions_uninterpreted_option(const google_protobuf_ServiceOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); }
UPB_INLINE void google_protobuf_ServiceOptions_set_deprecated(google_protobuf_ServiceOptions *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_mutable_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_ServiceOptions_resize_uninterpreted_option(google_protobuf_ServiceOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(4, 8), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_ServiceOptions_add_uninterpreted_option(google_protobuf_ServiceOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(4, 8), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2606,7 +2767,7 @@
/* google.protobuf.MethodOptions */
UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_new(upb_arena *arena) {
- return (google_protobuf_MethodOptions *)upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
+ return (google_protobuf_MethodOptions *)_upb_msg_new(&google_protobuf_MethodOptions_msginit, arena);
}
UPB_INLINE google_protobuf_MethodOptions *google_protobuf_MethodOptions_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2618,27 +2779,28 @@
}
UPB_INLINE bool google_protobuf_MethodOptions_has_deprecated(const google_protobuf_MethodOptions *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE bool google_protobuf_MethodOptions_deprecated(const google_protobuf_MethodOptions *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)); }
+UPB_INLINE bool google_protobuf_MethodOptions_deprecated(const google_protobuf_MethodOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool); }
UPB_INLINE bool google_protobuf_MethodOptions_has_idempotency_level(const google_protobuf_MethodOptions *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_MethodOptions_idempotency_level(const google_protobuf_MethodOptions *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_MethodOptions_idempotency_level(const google_protobuf_MethodOptions *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
+UPB_INLINE bool google_protobuf_MethodOptions_has_uninterpreted_option(const google_protobuf_MethodOptions *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 24)); }
UPB_INLINE const google_protobuf_UninterpretedOption* const* google_protobuf_MethodOptions_uninterpreted_option(const google_protobuf_MethodOptions *msg, size_t *len) { return (const google_protobuf_UninterpretedOption* const*)_upb_array_accessor(msg, UPB_SIZE(20, 24), len); }
UPB_INLINE void google_protobuf_MethodOptions_set_deprecated(google_protobuf_MethodOptions *msg, bool value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), bool) = value;
}
UPB_INLINE void google_protobuf_MethodOptions_set_idempotency_level(google_protobuf_MethodOptions *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_mutable_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t *len) {
return (google_protobuf_UninterpretedOption**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 24), len);
}
UPB_INLINE google_protobuf_UninterpretedOption** google_protobuf_MethodOptions_resize_uninterpreted_option(google_protobuf_MethodOptions *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 24), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption**)_upb_array_resize_accessor(msg, UPB_SIZE(20, 24), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption* google_protobuf_MethodOptions_add_uninterpreted_option(google_protobuf_MethodOptions *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ struct google_protobuf_UninterpretedOption* sub = (struct google_protobuf_UninterpretedOption*)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(20, 24), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2648,7 +2810,7 @@
/* google.protobuf.UninterpretedOption */
UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_new(upb_arena *arena) {
- return (google_protobuf_UninterpretedOption *)upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
+ return (google_protobuf_UninterpretedOption *)_upb_msg_new(&google_protobuf_UninterpretedOption_msginit, arena);
}
UPB_INLINE google_protobuf_UninterpretedOption *google_protobuf_UninterpretedOption_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2659,28 +2821,29 @@
return upb_encode(msg, &google_protobuf_UninterpretedOption_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_UninterpretedOption_has_name(const google_protobuf_UninterpretedOption *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(56, 80)); }
UPB_INLINE const google_protobuf_UninterpretedOption_NamePart* const* google_protobuf_UninterpretedOption_name(const google_protobuf_UninterpretedOption *msg, size_t *len) { return (const google_protobuf_UninterpretedOption_NamePart* const*)_upb_array_accessor(msg, UPB_SIZE(56, 80), len); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_identifier_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 4); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_identifier_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_identifier_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_positive_int_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE uint64_t google_protobuf_UninterpretedOption_positive_int_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, uint64_t, UPB_SIZE(8, 8)); }
+UPB_INLINE uint64_t google_protobuf_UninterpretedOption_positive_int_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_negative_int_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int64_t google_protobuf_UninterpretedOption_negative_int_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, int64_t, UPB_SIZE(16, 16)); }
+UPB_INLINE int64_t google_protobuf_UninterpretedOption_negative_int_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_double_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE double google_protobuf_UninterpretedOption_double_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, double, UPB_SIZE(24, 24)); }
+UPB_INLINE double google_protobuf_UninterpretedOption_double_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(24, 24), double); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_string_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 5); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_string_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_string_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(40, 48), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_has_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return _upb_has_field(msg, 6); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_aggregate_value(const google_protobuf_UninterpretedOption *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(48, 64), upb_strview); }
UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_mutable_name(google_protobuf_UninterpretedOption *msg, size_t *len) {
return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_mutable_accessor(msg, UPB_SIZE(56, 80), len);
}
UPB_INLINE google_protobuf_UninterpretedOption_NamePart** google_protobuf_UninterpretedOption_resize_name(google_protobuf_UninterpretedOption *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_resize_accessor(msg, UPB_SIZE(56, 80), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_UninterpretedOption_NamePart**)_upb_array_resize_accessor(msg, UPB_SIZE(56, 80), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_UninterpretedOption_NamePart* google_protobuf_UninterpretedOption_add_name(google_protobuf_UninterpretedOption *msg, upb_arena *arena) {
- struct google_protobuf_UninterpretedOption_NamePart* sub = (struct google_protobuf_UninterpretedOption_NamePart*)upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
+ struct google_protobuf_UninterpretedOption_NamePart* sub = (struct google_protobuf_UninterpretedOption_NamePart*)_upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(56, 80), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2688,33 +2851,33 @@
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_identifier_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
_upb_sethas(msg, 4);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(32, 32)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(32, 32), upb_strview) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_positive_int_value(google_protobuf_UninterpretedOption *msg, uint64_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, uint64_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), uint64_t) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_negative_int_value(google_protobuf_UninterpretedOption *msg, int64_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int64_t, UPB_SIZE(16, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(16, 16), int64_t) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_double_value(google_protobuf_UninterpretedOption *msg, double value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, double, UPB_SIZE(24, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(24, 24), double) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_string_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
_upb_sethas(msg, 5);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(40, 48)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(40, 48), upb_strview) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_set_aggregate_value(google_protobuf_UninterpretedOption *msg, upb_strview value) {
_upb_sethas(msg, 6);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(48, 64)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(48, 64), upb_strview) = value;
}
/* google.protobuf.UninterpretedOption.NamePart */
UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_new(upb_arena *arena) {
- return (google_protobuf_UninterpretedOption_NamePart *)upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
+ return (google_protobuf_UninterpretedOption_NamePart *)_upb_msg_new(&google_protobuf_UninterpretedOption_NamePart_msginit, arena);
}
UPB_INLINE google_protobuf_UninterpretedOption_NamePart *google_protobuf_UninterpretedOption_NamePart_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2726,23 +2889,23 @@
}
UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_has_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_UninterpretedOption_NamePart_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_UninterpretedOption_NamePart_name_part(const google_protobuf_UninterpretedOption_NamePart *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_has_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)); }
+UPB_INLINE bool google_protobuf_UninterpretedOption_NamePart_is_extension(const google_protobuf_UninterpretedOption_NamePart *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); }
UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_name_part(google_protobuf_UninterpretedOption_NamePart *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_UninterpretedOption_NamePart_set_is_extension(google_protobuf_UninterpretedOption_NamePart *msg, bool value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, bool, UPB_SIZE(1, 1)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
/* google.protobuf.SourceCodeInfo */
UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_new(upb_arena *arena) {
- return (google_protobuf_SourceCodeInfo *)upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
+ return (google_protobuf_SourceCodeInfo *)_upb_msg_new(&google_protobuf_SourceCodeInfo_msginit, arena);
}
UPB_INLINE google_protobuf_SourceCodeInfo *google_protobuf_SourceCodeInfo_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2753,16 +2916,17 @@
return upb_encode(msg, &google_protobuf_SourceCodeInfo_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_SourceCodeInfo_has_location(const google_protobuf_SourceCodeInfo *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_SourceCodeInfo_Location* const* google_protobuf_SourceCodeInfo_location(const google_protobuf_SourceCodeInfo *msg, size_t *len) { return (const google_protobuf_SourceCodeInfo_Location* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_mutable_location(google_protobuf_SourceCodeInfo *msg, size_t *len) {
return (google_protobuf_SourceCodeInfo_Location**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_SourceCodeInfo_Location** google_protobuf_SourceCodeInfo_resize_location(google_protobuf_SourceCodeInfo *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_SourceCodeInfo_Location**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_SourceCodeInfo_Location**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_SourceCodeInfo_Location* google_protobuf_SourceCodeInfo_add_location(google_protobuf_SourceCodeInfo *msg, upb_arena *arena) {
- struct google_protobuf_SourceCodeInfo_Location* sub = (struct google_protobuf_SourceCodeInfo_Location*)upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
+ struct google_protobuf_SourceCodeInfo_Location* sub = (struct google_protobuf_SourceCodeInfo_Location*)_upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2772,7 +2936,7 @@
/* google.protobuf.SourceCodeInfo.Location */
UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_new(upb_arena *arena) {
- return (google_protobuf_SourceCodeInfo_Location *)upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
+ return (google_protobuf_SourceCodeInfo_Location *)_upb_msg_new(&google_protobuf_SourceCodeInfo_Location_msginit, arena);
}
UPB_INLINE google_protobuf_SourceCodeInfo_Location *google_protobuf_SourceCodeInfo_Location_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2786,54 +2950,54 @@
UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_path(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len); }
UPB_INLINE int32_t const* google_protobuf_SourceCodeInfo_Location_span(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len); }
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_has_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)); }
+UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_leading_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview); }
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_has_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)); }
+UPB_INLINE upb_strview google_protobuf_SourceCodeInfo_Location_trailing_comments(const google_protobuf_SourceCodeInfo_Location *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview); }
UPB_INLINE upb_strview const* google_protobuf_SourceCodeInfo_Location_leading_detached_comments(const google_protobuf_SourceCodeInfo_Location *msg, size_t *len) { return (upb_strview const*)_upb_array_accessor(msg, UPB_SIZE(28, 56), len); }
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_path(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_path(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 40), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_path(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(20, 40), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(20, 40), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_mutable_span(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE int32_t* google_protobuf_SourceCodeInfo_Location_resize_span(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(24, 48), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_span(google_protobuf_SourceCodeInfo_Location *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(24, 48), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(24, 48), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_leading_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(4, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 8), upb_strview) = value;
}
UPB_INLINE void google_protobuf_SourceCodeInfo_Location_set_trailing_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 24)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_strview) = value;
}
UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_mutable_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t *len) {
return (upb_strview*)_upb_array_mutable_accessor(msg, UPB_SIZE(28, 56), len);
}
UPB_INLINE upb_strview* google_protobuf_SourceCodeInfo_Location_resize_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, size_t len, upb_arena *arena) {
- return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_SIZE(8, 16), UPB_TYPE_STRING, arena);
+ return (upb_strview*)_upb_array_resize_accessor(msg, UPB_SIZE(28, 56), len, UPB_TYPE_STRING, arena);
}
UPB_INLINE bool google_protobuf_SourceCodeInfo_Location_add_leading_detached_comments(google_protobuf_SourceCodeInfo_Location *msg, upb_strview val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(28, 56), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(28, 56), UPB_SIZE(8, 16), UPB_TYPE_STRING, &val,
+ arena);
}
/* google.protobuf.GeneratedCodeInfo */
UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_new(upb_arena *arena) {
- return (google_protobuf_GeneratedCodeInfo *)upb_msg_new(&google_protobuf_GeneratedCodeInfo_msginit, arena);
+ return (google_protobuf_GeneratedCodeInfo *)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_msginit, arena);
}
UPB_INLINE google_protobuf_GeneratedCodeInfo *google_protobuf_GeneratedCodeInfo_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2844,16 +3008,17 @@
return upb_encode(msg, &google_protobuf_GeneratedCodeInfo_msginit, arena, len);
}
+UPB_INLINE bool google_protobuf_GeneratedCodeInfo_has_annotation(const google_protobuf_GeneratedCodeInfo *msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(0, 0)); }
UPB_INLINE const google_protobuf_GeneratedCodeInfo_Annotation* const* google_protobuf_GeneratedCodeInfo_annotation(const google_protobuf_GeneratedCodeInfo *msg, size_t *len) { return (const google_protobuf_GeneratedCodeInfo_Annotation* const*)_upb_array_accessor(msg, UPB_SIZE(0, 0), len); }
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_mutable_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t *len) {
return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_mutable_accessor(msg, UPB_SIZE(0, 0), len);
}
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation** google_protobuf_GeneratedCodeInfo_resize_annotation(google_protobuf_GeneratedCodeInfo *msg, size_t len, upb_arena *arena) {
- return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, arena);
+ return (google_protobuf_GeneratedCodeInfo_Annotation**)_upb_array_resize_accessor(msg, UPB_SIZE(0, 0), len, UPB_TYPE_MESSAGE, arena);
}
UPB_INLINE struct google_protobuf_GeneratedCodeInfo_Annotation* google_protobuf_GeneratedCodeInfo_add_annotation(google_protobuf_GeneratedCodeInfo *msg, upb_arena *arena) {
- struct google_protobuf_GeneratedCodeInfo_Annotation* sub = (struct google_protobuf_GeneratedCodeInfo_Annotation*)upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
+ struct google_protobuf_GeneratedCodeInfo_Annotation* sub = (struct google_protobuf_GeneratedCodeInfo_Annotation*)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
bool ok = _upb_array_append_accessor(
msg, UPB_SIZE(0, 0), UPB_SIZE(4, 8), UPB_TYPE_MESSAGE, &sub, arena);
if (!ok) return NULL;
@@ -2863,7 +3028,7 @@
/* google.protobuf.GeneratedCodeInfo.Annotation */
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_new(upb_arena *arena) {
- return (google_protobuf_GeneratedCodeInfo_Annotation *)upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
+ return (google_protobuf_GeneratedCodeInfo_Annotation *)_upb_msg_new(&google_protobuf_GeneratedCodeInfo_Annotation_msginit, arena);
}
UPB_INLINE google_protobuf_GeneratedCodeInfo_Annotation *google_protobuf_GeneratedCodeInfo_Annotation_parse(const char *buf, size_t size,
upb_arena *arena) {
@@ -2876,33 +3041,33 @@
UPB_INLINE int32_t const* google_protobuf_GeneratedCodeInfo_Annotation_path(const google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) { return (int32_t const*)_upb_array_accessor(msg, UPB_SIZE(20, 32), len); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_has_field(msg, 3); }
-UPB_INLINE upb_strview google_protobuf_GeneratedCodeInfo_Annotation_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 16)); }
+UPB_INLINE upb_strview google_protobuf_GeneratedCodeInfo_Annotation_source_file(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_has_field(msg, 1); }
-UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)); }
+UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_begin(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t); }
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_has_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return _upb_has_field(msg, 2); }
-UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)); }
+UPB_INLINE int32_t google_protobuf_GeneratedCodeInfo_Annotation_end(const google_protobuf_GeneratedCodeInfo_Annotation *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t); }
UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_mutable_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t *len) {
return (int32_t*)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 32), len);
}
UPB_INLINE int32_t* google_protobuf_GeneratedCodeInfo_Annotation_resize_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, size_t len, upb_arena *arena) {
- return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 32), len, UPB_SIZE(4, 4), UPB_TYPE_INT32, arena);
+ return (int32_t*)_upb_array_resize_accessor(msg, UPB_SIZE(20, 32), len, UPB_TYPE_INT32, arena);
}
UPB_INLINE bool google_protobuf_GeneratedCodeInfo_Annotation_add_path(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t val, upb_arena *arena) {
- return _upb_array_append_accessor(
- msg, UPB_SIZE(20, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val, arena);
+ return _upb_array_append_accessor(msg, UPB_SIZE(20, 32), UPB_SIZE(4, 4), UPB_TYPE_INT32, &val,
+ arena);
}
UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_source_file(google_protobuf_GeneratedCodeInfo_Annotation *msg, upb_strview value) {
_upb_sethas(msg, 3);
- UPB_FIELD_AT(msg, upb_strview, UPB_SIZE(12, 16)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(12, 16), upb_strview) = value;
}
UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_begin(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
_upb_sethas(msg, 1);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(4, 4)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t) = value;
}
UPB_INLINE void google_protobuf_GeneratedCodeInfo_Annotation_set_end(google_protobuf_GeneratedCodeInfo_Annotation *msg, int32_t value) {
_upb_sethas(msg, 2);
- UPB_FIELD_AT(msg, int32_t, UPB_SIZE(8, 8)) = value;
+ *UPB_PTR_AT(msg, UPB_SIZE(8, 8), int32_t) = value;
}
#ifdef __cplusplus
@@ -2915,38 +3080,23 @@
** Defs are upb's internal representation of the constructs that can appear
** in a .proto file:
**
-** - upb::MessageDefPtr (upb_msgdef): describes a "message" construct.
-** - upb::FieldDefPtr (upb_fielddef): describes a message field.
-** - upb::FileDefPtr (upb_filedef): describes a .proto file and its defs.
-** - upb::EnumDefPtr (upb_enumdef): describes an enum.
-** - upb::OneofDefPtr (upb_oneofdef): describes a oneof.
+** - upb_msgdef: describes a "message" construct.
+** - upb_fielddef: describes a message field.
+** - upb_filedef: describes a .proto file and its defs.
+** - upb_enumdef: describes an enum.
+** - upb_oneofdef: describes a oneof.
**
** TODO: definitions of services.
-**
-** This is a mixed C/C++ interface that offers a full API to both languages.
-** See the top-level README for more information.
*/
#ifndef UPB_DEF_H_
#define UPB_DEF_H_
+
#ifdef __cplusplus
-#include <cstring>
-#include <memory>
-#include <string>
-#include <vector>
-
-namespace upb {
-class EnumDefPtr;
-class FieldDefPtr;
-class FileDefPtr;
-class MessageDefPtr;
-class OneofDefPtr;
-class SymbolTable;
-}
-#endif
-
+extern "C" {
+#endif /* __cplusplus */
struct upb_enumdef;
typedef struct upb_enumdef upb_enumdef;
@@ -2998,22 +3148,20 @@
* protobuf wire format. */
#define UPB_MAX_FIELDNUMBER ((1 << 29) - 1)
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_fielddef_fullname(const upb_fielddef *f);
upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f);
upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f);
upb_label_t upb_fielddef_label(const upb_fielddef *f);
uint32_t upb_fielddef_number(const upb_fielddef *f);
const char *upb_fielddef_name(const upb_fielddef *f);
+const char *upb_fielddef_jsonname(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_filedef *upb_fielddef_file(const upb_fielddef *f);
const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f);
const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f);
+const upb_oneofdef *upb_fielddef_realcontainingoneof(const upb_fielddef *f);
uint32_t upb_fielddef_index(const upb_fielddef *f);
bool upb_fielddef_issubmsg(const upb_fielddef *f);
bool upb_fielddef_isstring(const upb_fielddef *f);
@@ -3032,155 +3180,20 @@
bool upb_fielddef_haspresence(const upb_fielddef *f);
const upb_msgdef *upb_fielddef_msgsubdef(const upb_fielddef *f);
const upb_enumdef *upb_fielddef_enumsubdef(const upb_fielddef *f);
+const upb_msglayout_field *upb_fielddef_layout(const upb_fielddef *f);
/* Internal only. */
uint32_t upb_fielddef_selectorbase(const upb_fielddef *f);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* A upb_fielddef describes a single field in a message. It is most often
- * found as a part of a upb_msgdef, but can also stand alone to represent
- * an extension. */
-class upb::FieldDefPtr {
- public:
- FieldDefPtr() : ptr_(nullptr) {}
- explicit FieldDefPtr(const upb_fielddef *ptr) : ptr_(ptr) {}
-
- const upb_fielddef* ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- typedef upb_fieldtype_t Type;
- typedef upb_label_t Label;
- typedef upb_descriptortype_t DescriptorType;
-
- const char* full_name() const { return upb_fielddef_fullname(ptr_); }
-
- Type type() const { return upb_fielddef_type(ptr_); }
- Label label() const { return upb_fielddef_label(ptr_); }
- const char* name() const { return upb_fielddef_name(ptr_); }
- uint32_t number() const { return upb_fielddef_number(ptr_); }
- bool is_extension() const { return upb_fielddef_isextension(ptr_); }
-
- /* 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 {
- return upb_fielddef_getjsonname(ptr_, buf, len);
- }
-
- /* 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.
- *
- * TODO(haberman): I think we want to move this into a FieldOptions container
- * when we add support for custom options (the FieldOptions struct will
- * contain both regular FieldOptions like "lazy" *and* custom options). */
- bool lazy() const { return upb_fielddef_lazy(ptr_); }
-
- /* For non-string, non-submessage fields, this indicates whether binary
- * protobufs are encoded in packed or non-packed format.
- *
- * TODO(haberman): see note above about putting options like this into a
- * FieldOptions container. */
- bool packed() const { return upb_fielddef_packed(ptr_); }
-
- /* An integer that can be used as an index into an array of fields for
- * 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. */
- uint32_t index() const { return upb_fielddef_index(ptr_); }
-
- /* The MessageDef to which this field belongs.
- *
- * If this field has been added to a MessageDef, that message can be retrieved
- * directly (this is always the case for frozen FieldDefs).
- *
- * If the field has not yet been added to a MessageDef, you can set the name
- * of the containing type symbolically instead. This is mostly useful for
- * extensions, where the extension is declared separately from the message. */
- MessageDefPtr containing_type() const;
-
- /* The OneofDef to which this field belongs, or NULL if this field is not part
- * of a oneof. */
- OneofDefPtr containing_oneof() const;
-
- /* The field's type according to the enum in descriptor.proto. This is not
- * the same as UPB_TYPE_*, because it distinguishes between (for example)
- * INT32 and SINT32, whereas our "type" enum does not. This return of
- * descriptor_type() is a function of type(), integer_format(), and
- * is_tag_delimited(). */
- DescriptorType descriptor_type() const {
- return upb_fielddef_descriptortype(ptr_);
- }
-
- /* Convenient field type tests. */
- bool IsSubMessage() const { return upb_fielddef_issubmsg(ptr_); }
- bool IsString() const { return upb_fielddef_isstring(ptr_); }
- bool IsSequence() const { return upb_fielddef_isseq(ptr_); }
- bool IsPrimitive() const { return upb_fielddef_isprimitive(ptr_); }
- bool IsMap() const { return upb_fielddef_ismap(ptr_); }
-
- /* Returns the non-string default value for this fielddef, which may either
- * be something the client set explicitly or the "default default" (0 for
- * numbers, empty for strings). The field's type indicates the type of the
- * returned value, except for enum fields that are still mutable.
- *
- * Requires that the given function matches the field's current type. */
- int64_t default_int64() const { return upb_fielddef_defaultint64(ptr_); }
- int32_t default_int32() const { return upb_fielddef_defaultint32(ptr_); }
- uint64_t default_uint64() const { return upb_fielddef_defaultuint64(ptr_); }
- uint32_t default_uint32() const { return upb_fielddef_defaultuint32(ptr_); }
- bool default_bool() const { return upb_fielddef_defaultbool(ptr_); }
- float default_float() const { return upb_fielddef_defaultfloat(ptr_); }
- double default_double() const { return upb_fielddef_defaultdouble(ptr_); }
-
- /* The resulting string is always NULL-terminated. If non-NULL, the length
- * will be stored in *len. */
- const char *default_string(size_t * len) const {
- return upb_fielddef_defaultstr(ptr_, len);
- }
-
- /* Returns the enum or submessage def for this field, if any. The field's
- * type must match (ie. you may only call enum_subdef() for fields where
- * type() == UPB_TYPE_ENUM). */
- EnumDefPtr enum_subdef() const;
- MessageDefPtr message_subdef() const;
-
- private:
- const upb_fielddef *ptr_;
-};
-
-#endif /* __cplusplus */
-
/* upb_oneofdef ***************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
typedef upb_inttable_iter upb_oneof_iter;
const char *upb_oneofdef_name(const upb_oneofdef *o);
const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o);
int upb_oneofdef_numfields(const upb_oneofdef *o);
uint32_t upb_oneofdef_index(const upb_oneofdef *o);
+bool upb_oneofdef_issynthetic(const upb_oneofdef *o);
/* Oneof lookups:
* - ntof: look up a field by name.
@@ -3207,92 +3220,6 @@
bool upb_oneof_iter_isequal(const upb_oneof_iter *iter1,
const upb_oneof_iter *iter2);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* Class that represents a oneof. */
-class upb::OneofDefPtr {
- public:
- OneofDefPtr() : ptr_(nullptr) {}
- explicit OneofDefPtr(const upb_oneofdef *ptr) : ptr_(ptr) {}
-
- const upb_oneofdef* ptr() const { return ptr_; }
- explicit operator bool() { return ptr_ != nullptr; }
-
- /* Returns the MessageDef that owns this OneofDef. */
- MessageDefPtr containing_type() const;
-
- /* Returns the name of this oneof. This is the name used to look up the oneof
- * by name once added to a message def. */
- const char* name() const { return upb_oneofdef_name(ptr_); }
-
- /* Returns the number of fields currently defined in the oneof. */
- int field_count() const { return upb_oneofdef_numfields(ptr_); }
-
- /* Looks up by name. */
- FieldDefPtr FindFieldByName(const char *name, size_t len) const {
- return FieldDefPtr(upb_oneofdef_ntof(ptr_, name, len));
- }
- FieldDefPtr FindFieldByName(const char* name) const {
- return FieldDefPtr(upb_oneofdef_ntofz(ptr_, name));
- }
-
- template <class T>
- FieldDefPtr FindFieldByName(const T& str) const {
- return FindFieldByName(str.c_str(), str.size());
- }
-
- /* Looks up by tag number. */
- FieldDefPtr FindFieldByNumber(uint32_t num) const {
- return FieldDefPtr(upb_oneofdef_itof(ptr_, num));
- }
-
- class const_iterator
- : public std::iterator<std::forward_iterator_tag, FieldDefPtr> {
- public:
- void operator++() { upb_oneof_next(&iter_); }
-
- FieldDefPtr operator*() const {
- return FieldDefPtr(upb_oneof_iter_field(&iter_));
- }
-
- bool operator!=(const const_iterator& other) const {
- return !upb_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- bool operator==(const const_iterator& other) const {
- return upb_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- private:
- friend class OneofDefPtr;
-
- const_iterator() {}
- explicit const_iterator(OneofDefPtr o) {
- upb_oneof_begin(&iter_, o.ptr());
- }
- static const_iterator end() {
- const_iterator iter;
- upb_oneof_iter_setdone(&iter.iter_);
- return iter;
- }
-
- upb_oneof_iter iter_;
- };
-
- const_iterator begin() const { return const_iterator(*this); }
- const_iterator end() const { return const_iterator::end(); }
-
- private:
- const upb_oneofdef *ptr_;
-};
-
-inline upb::OneofDefPtr upb::FieldDefPtr::containing_oneof() const {
- return OneofDefPtr(upb_fielddef_containingoneof(ptr_));
-}
-
-#endif /* __cplusplus */
-
/* upb_msgdef *****************************************************************/
typedef upb_inttable_iter upb_msg_field_iter;
@@ -3314,26 +3241,23 @@
#define UPB_TIMESTAMP_SECONDS 1
#define UPB_TIMESTAMP_NANOS 2
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_msgdef_fullname(const upb_msgdef *m);
const upb_filedef *upb_msgdef_file(const upb_msgdef *m);
const char *upb_msgdef_name(const upb_msgdef *m);
+int upb_msgdef_numfields(const upb_msgdef *m);
int upb_msgdef_numoneofs(const upb_msgdef *m);
+int upb_msgdef_numrealoneofs(const upb_msgdef *m);
upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m);
bool upb_msgdef_mapentry(const upb_msgdef *m);
upb_wellknowntype_t upb_msgdef_wellknowntype(const upb_msgdef *m);
bool upb_msgdef_isnumberwrapper(const upb_msgdef *m);
-bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax);
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);
const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
size_t len);
-int upb_msgdef_numfields(const upb_msgdef *m);
-int upb_msgdef_numoneofs(const upb_msgdef *m);
+const upb_msglayout *upb_msgdef_layout(const upb_msgdef *m);
+const upb_fielddef *_upb_msgdef_field(const upb_msgdef *m, int i);
UPB_INLINE const upb_oneofdef *upb_msgdef_ntooz(const upb_msgdef *m,
const char *name) {
@@ -3361,6 +3285,10 @@
return upb_msgdef_lookupname(m, name, strlen(name), f, o);
}
+/* Returns a field by either JSON name or regular proto name. */
+const upb_fielddef *upb_msgdef_lookupjsonname(const upb_msgdef *m,
+ const char *name, size_t len);
+
/* Iteration over fields and oneofs. For example:
*
* upb_msg_field_iter i;
@@ -3392,194 +3320,6 @@
bool upb_msg_oneof_iter_isequal(const upb_msg_oneof_iter *iter1,
const upb_msg_oneof_iter *iter2);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* Structure that describes a single .proto message type. */
-class upb::MessageDefPtr {
- public:
- MessageDefPtr() : ptr_(nullptr) {}
- explicit MessageDefPtr(const upb_msgdef *ptr) : ptr_(ptr) {}
-
- const upb_msgdef *ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- const char* full_name() const { return upb_msgdef_fullname(ptr_); }
- const char* name() const { return upb_msgdef_name(ptr_); }
-
- /* The number of fields that belong to the MessageDef. */
- int field_count() const { return upb_msgdef_numfields(ptr_); }
-
- /* The number of oneofs that belong to the MessageDef. */
- int oneof_count() const { return upb_msgdef_numoneofs(ptr_); }
-
- upb_syntax_t syntax() const { return upb_msgdef_syntax(ptr_); }
-
- /* These return null pointers if the field is not found. */
- FieldDefPtr FindFieldByNumber(uint32_t number) const {
- return FieldDefPtr(upb_msgdef_itof(ptr_, number));
- }
- FieldDefPtr FindFieldByName(const char* name, size_t len) const {
- return FieldDefPtr(upb_msgdef_ntof(ptr_, name, len));
- }
- FieldDefPtr FindFieldByName(const char *name) const {
- return FieldDefPtr(upb_msgdef_ntofz(ptr_, name));
- }
-
- template <class T>
- FieldDefPtr FindFieldByName(const T& str) const {
- return FindFieldByName(str.c_str(), str.size());
- }
-
- OneofDefPtr FindOneofByName(const char* name, size_t len) const {
- return OneofDefPtr(upb_msgdef_ntoo(ptr_, name, len));
- }
-
- OneofDefPtr FindOneofByName(const char *name) const {
- return OneofDefPtr(upb_msgdef_ntooz(ptr_, name));
- }
-
- template <class T>
- OneofDefPtr FindOneofByName(const T &str) const {
- return FindOneofByName(str.c_str(), str.size());
- }
-
- /* Is this message a map entry? */
- bool mapentry() const { return upb_msgdef_mapentry(ptr_); }
-
- /* Return the type of well known type message. UPB_WELLKNOWN_UNSPECIFIED for
- * non-well-known message. */
- upb_wellknowntype_t wellknowntype() const {
- return upb_msgdef_wellknowntype(ptr_);
- }
-
- /* Whether is a number wrapper. */
- bool isnumberwrapper() const { return upb_msgdef_isnumberwrapper(ptr_); }
-
- /* Iteration over fields. The order is undefined. */
- class const_field_iterator
- : public std::iterator<std::forward_iterator_tag, FieldDefPtr> {
- public:
- void operator++() { upb_msg_field_next(&iter_); }
-
- FieldDefPtr operator*() const {
- return FieldDefPtr(upb_msg_iter_field(&iter_));
- }
-
- bool operator!=(const const_field_iterator &other) const {
- return !upb_msg_field_iter_isequal(&iter_, &other.iter_);
- }
-
- bool operator==(const const_field_iterator &other) const {
- return upb_msg_field_iter_isequal(&iter_, &other.iter_);
- }
-
- private:
- friend class MessageDefPtr;
-
- explicit const_field_iterator() {}
-
- explicit const_field_iterator(MessageDefPtr msg) {
- upb_msg_field_begin(&iter_, msg.ptr());
- }
-
- static const_field_iterator end() {
- const_field_iterator iter;
- upb_msg_field_iter_setdone(&iter.iter_);
- return iter;
- }
-
- upb_msg_field_iter iter_;
- };
-
- /* Iteration over oneofs. The order is undefined. */
- class const_oneof_iterator
- : public std::iterator<std::forward_iterator_tag, OneofDefPtr> {
- public:
-
- void operator++() { upb_msg_oneof_next(&iter_); }
-
- OneofDefPtr operator*() const {
- return OneofDefPtr(upb_msg_iter_oneof(&iter_));
- }
-
- bool operator!=(const const_oneof_iterator& other) const {
- return !upb_msg_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- bool operator==(const const_oneof_iterator &other) const {
- return upb_msg_oneof_iter_isequal(&iter_, &other.iter_);
- }
-
- private:
- friend class MessageDefPtr;
-
- const_oneof_iterator() {}
-
- explicit const_oneof_iterator(MessageDefPtr msg) {
- upb_msg_oneof_begin(&iter_, msg.ptr());
- }
-
- static const_oneof_iterator end() {
- const_oneof_iterator iter;
- upb_msg_oneof_iter_setdone(&iter.iter_);
- return iter;
- }
-
- upb_msg_oneof_iter iter_;
- };
-
- class ConstFieldAccessor {
- public:
- explicit ConstFieldAccessor(const upb_msgdef* md) : md_(md) {}
- const_field_iterator begin() { return MessageDefPtr(md_).field_begin(); }
- const_field_iterator end() { return MessageDefPtr(md_).field_end(); }
- private:
- const upb_msgdef* md_;
- };
-
- class ConstOneofAccessor {
- public:
- explicit ConstOneofAccessor(const upb_msgdef* md) : md_(md) {}
- const_oneof_iterator begin() { return MessageDefPtr(md_).oneof_begin(); }
- const_oneof_iterator end() { return MessageDefPtr(md_).oneof_end(); }
- private:
- const upb_msgdef* md_;
- };
-
- const_field_iterator field_begin() const {
- return const_field_iterator(*this);
- }
-
- const_field_iterator field_end() const { return const_field_iterator::end(); }
-
- const_oneof_iterator oneof_begin() const {
- return const_oneof_iterator(*this);
- }
-
- const_oneof_iterator oneof_end() const { return const_oneof_iterator::end(); }
-
- ConstFieldAccessor fields() const { return ConstFieldAccessor(ptr()); }
- ConstOneofAccessor oneofs() const { return ConstOneofAccessor(ptr()); }
-
- private:
- const upb_msgdef* ptr_;
-};
-
-inline upb::MessageDefPtr upb::FieldDefPtr::message_subdef() const {
- return MessageDefPtr(upb_fielddef_msgsubdef(ptr_));
-}
-
-inline upb::MessageDefPtr upb::FieldDefPtr::containing_type() const {
- return MessageDefPtr(upb_fielddef_containingtype(ptr_));
-}
-
-inline upb::MessageDefPtr upb::OneofDefPtr::containing_type() const {
- return MessageDefPtr(upb_oneofdef_containingtype(ptr_));
-}
-
-#endif /* __cplusplus */
-
/* upb_enumdef ****************************************************************/
typedef upb_strtable_iter upb_enum_iter;
@@ -3614,75 +3354,8 @@
const char *upb_enum_iter_name(upb_enum_iter *iter);
int32_t upb_enum_iter_number(upb_enum_iter *iter);
-#ifdef __cplusplus
-
-class upb::EnumDefPtr {
- public:
- EnumDefPtr() : ptr_(nullptr) {}
- explicit EnumDefPtr(const upb_enumdef* ptr) : ptr_(ptr) {}
-
- const upb_enumdef* ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- const char* full_name() const { return upb_enumdef_fullname(ptr_); }
- const char* name() const { return upb_enumdef_name(ptr_); }
-
- /* The value that is used as the default when no field default is specified.
- * If not set explicitly, the first value that was added will be used.
- * The default value must be a member of the enum.
- * Requires that value_count() > 0. */
- int32_t default_value() const { return upb_enumdef_default(ptr_); }
-
- /* Returns the number of values currently defined in the enum. Note that
- * multiple names can refer to the same number, so this may be greater than
- * the total number of unique numbers. */
- int value_count() const { return upb_enumdef_numvals(ptr_); }
-
- /* Lookups from name to integer, returning true if found. */
- bool FindValueByName(const char *name, int32_t *num) const {
- return upb_enumdef_ntoiz(ptr_, name, num);
- }
-
- /* Finds the name corresponding to the given number, or NULL if none was
- * found. If more than one name corresponds to this number, returns the
- * first one that was added. */
- const char *FindValueByNumber(int32_t num) const {
- return upb_enumdef_iton(ptr_, num);
- }
-
- /* Iteration over name/value pairs. The order is undefined.
- * Adding an enum val invalidates any iterators.
- *
- * TODO: make compatible with range-for, with elements as pairs? */
- class Iterator {
- public:
- explicit Iterator(EnumDefPtr e) { upb_enum_begin(&iter_, e.ptr()); }
-
- int32_t number() { return upb_enum_iter_number(&iter_); }
- const char *name() { return upb_enum_iter_name(&iter_); }
- bool Done() { return upb_enum_done(&iter_); }
- void Next() { return upb_enum_next(&iter_); }
-
- private:
- upb_enum_iter iter_;
- };
-
- private:
- const upb_enumdef *ptr_;
-};
-
-inline upb::EnumDefPtr upb::FieldDefPtr::enum_subdef() const {
- return EnumDefPtr(upb_fielddef_enumsubdef(ptr_));
-}
-
-#endif /* __cplusplus */
-
/* upb_filedef ****************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
const char *upb_filedef_name(const upb_filedef *f);
const char *upb_filedef_package(const upb_filedef *f);
const char *upb_filedef_phpprefix(const upb_filedef *f);
@@ -3695,57 +3368,8 @@
const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i);
const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i);
-#ifdef __cplusplus
-} /* extern "C" */
-
-/* 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::FileDefPtr {
- public:
- explicit FileDefPtr(const upb_filedef *ptr) : ptr_(ptr) {}
-
- const upb_filedef* ptr() const { return ptr_; }
- explicit operator bool() const { return ptr_ != nullptr; }
-
- /* Get/set name of the file (eg. "foo/bar.proto"). */
- const char* name() const { return upb_filedef_name(ptr_); }
-
- /* Package name for definitions inside the file (eg. "foo.bar"). */
- const char* package() const { return upb_filedef_package(ptr_); }
-
- /* Sets the php class prefix which is prepended to all php generated classes
- * from this .proto. Default is empty. */
- const char* phpprefix() const { return upb_filedef_phpprefix(ptr_); }
-
- /* Use this option to change the namespace of php generated classes. Default
- * is empty. When this option is empty, the package name will be used for
- * determining the namespace. */
- const char* phpnamespace() const { return upb_filedef_phpnamespace(ptr_); }
-
- /* Syntax for the file. Defaults to proto2. */
- upb_syntax_t syntax() const { return upb_filedef_syntax(ptr_); }
-
- /* Get the list of dependencies from the file. These are returned in the
- * order that they were added to the FileDefPtr. */
- int dependency_count() const { return upb_filedef_depcount(ptr_); }
- const FileDefPtr dependency(int index) const {
- return FileDefPtr(upb_filedef_dep(ptr_, index));
- }
-
- private:
- const upb_filedef* ptr_;
-};
-
-#endif /* __cplusplus */
-
/* upb_symtab *****************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
upb_symtab *upb_symtab_new(void);
void upb_symtab_free(upb_symtab* s);
const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
@@ -3760,107 +3384,171 @@
/* For generated code only: loads a generated descriptor. */
typedef struct upb_def_init {
- struct upb_def_init **deps;
+ struct upb_def_init **deps; /* Dependencies of this file. */
+ const upb_msglayout **layouts; /* Pre-order layouts of all messages. */
const char *filename;
- upb_strview descriptor;
+ upb_strview descriptor; /* Serialized descriptor. */
} upb_def_init;
bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init);
+
#ifdef __cplusplus
} /* extern "C" */
-
-/* Non-const methods in upb::SymbolTable are NOT thread-safe. */
-class upb::SymbolTable {
- public:
- SymbolTable() : ptr_(upb_symtab_new(), upb_symtab_free) {}
- explicit SymbolTable(upb_symtab* s) : ptr_(s, upb_symtab_free) {}
-
- const upb_symtab* ptr() const { return ptr_.get(); }
- upb_symtab* ptr() { return ptr_.get(); }
-
- /* Finds an entry in the symbol table with this exact name. If not found,
- * returns NULL. */
- MessageDefPtr LookupMessage(const char *sym) const {
- return MessageDefPtr(upb_symtab_lookupmsg(ptr_.get(), sym));
- }
-
- EnumDefPtr LookupEnum(const char *sym) const {
- return EnumDefPtr(upb_symtab_lookupenum(ptr_.get(), sym));
- }
-
- FileDefPtr LookupFile(const char *name) const {
- return FileDefPtr(upb_symtab_lookupfile(ptr_.get(), name));
- }
-
- /* TODO: iteration? */
-
- /* Adds the given serialized FileDescriptorProto to the pool. */
- FileDefPtr AddFile(const google_protobuf_FileDescriptorProto *file_proto,
- Status *status) {
- return FileDefPtr(
- upb_symtab_addfile(ptr_.get(), file_proto, status->ptr()));
- }
-
- private:
- std::unique_ptr<upb_symtab, decltype(&upb_symtab_free)> ptr_;
-};
-
-UPB_INLINE const char* upb_safecstr(const std::string& str) {
- UPB_ASSERT(str.size() == std::strlen(str.c_str()));
- return str.c_str();
-}
-
#endif /* __cplusplus */
-
#endif /* UPB_DEF_H_ */
+#ifndef UPB_REFLECTION_H_
+#define UPB_REFLECTION_H_
-#ifndef UPB_MSGFACTORY_H_
-#define UPB_MSGFACTORY_H_
-/** upb_msgfactory ************************************************************/
-struct upb_msgfactory;
-typedef struct upb_msgfactory upb_msgfactory;
+typedef union {
+ bool bool_val;
+ float float_val;
+ double double_val;
+ int32_t int32_val;
+ int64_t int64_val;
+ uint32_t uint32_val;
+ uint64_t uint64_val;
+ const upb_map* map_val;
+ const upb_msg* msg_val;
+ const upb_array* array_val;
+ upb_strview str_val;
+} upb_msgval;
-#ifdef __cplusplus
-extern "C" {
-#endif
+typedef union {
+ upb_map* map;
+ upb_msg* msg;
+ upb_array* array;
+} upb_mutmsgval;
-/* A upb_msgfactory contains a cache of upb_msglayout, upb_handlers, and
- * upb_visitorplan objects. These are the objects necessary to represent,
- * populate, and and visit upb_msg objects.
+/** upb_msg *******************************************************************/
+
+/* Creates a new message of the given type in the given arena. */
+upb_msg *upb_msg_new(const upb_msgdef *m, upb_arena *a);
+
+/* Returns the value associated with this field. */
+upb_msgval upb_msg_get(const upb_msg *msg, const upb_fielddef *f);
+
+/* Returns a mutable pointer to a map, array, or submessage value. If the given
+ * arena is non-NULL this will construct a new object if it was not previously
+ * present. May not be called for primitive fields. */
+upb_mutmsgval upb_msg_mutable(upb_msg *msg, const upb_fielddef *f, upb_arena *a);
+
+/* May only be called for fields where upb_fielddef_haspresence(f) == true. */
+bool upb_msg_has(const upb_msg *msg, const upb_fielddef *f);
+
+/* Returns whether any field is set in the oneof. */
+bool upb_msg_hasoneof(const upb_msg *msg, const upb_oneofdef *o);
+
+/* Sets the given field to the given value. For a msg/array/map/string, the
+ * value must be in the same arena. */
+void upb_msg_set(upb_msg *msg, const upb_fielddef *f, upb_msgval val,
+ upb_arena *a);
+
+/* Clears any field presence and sets the value back to its default. */
+void upb_msg_clearfield(upb_msg *msg, const upb_fielddef *f);
+
+/* Iterate over present fields.
*
- * These caches are all populated by upb_msgdef, and lazily created on demand.
+ * size_t iter = UPB_MSG_BEGIN;
+ * const upb_fielddef *f;
+ * upb_msgval val;
+ * while (upb_msg_next(msg, m, ext_pool, &f, &val, &iter)) {
+ * process_field(f, val);
+ * }
+ *
+ * If ext_pool is NULL, no extensions will be returned. If the given symtab
+ * returns extensions that don't match what is in this message, those extensions
+ * will be skipped.
*/
-/* Creates and destroys a msgfactory, respectively. The messages for this
- * msgfactory must come from |symtab| (which should outlive the msgfactory). */
-upb_msgfactory *upb_msgfactory_new(const upb_symtab *symtab);
-void upb_msgfactory_free(upb_msgfactory *f);
+#define UPB_MSG_BEGIN -1
+bool upb_msg_next(const upb_msg *msg, const upb_msgdef *m,
+ const upb_symtab *ext_pool, const upb_fielddef **f,
+ upb_msgval *val, size_t *iter);
-const upb_symtab *upb_msgfactory_symtab(const upb_msgfactory *f);
+/* Adds unknown data (serialized protobuf data) to the given message. The data
+ * is copied into the message instance. */
+void upb_msg_addunknown(upb_msg *msg, const char *data, size_t len,
+ upb_arena *arena);
-/* The functions to get cached objects, lazily creating them on demand. These
- * all require:
+/* Returns a reference to the message's unknown data. */
+const char *upb_msg_getunknown(const upb_msg *msg, size_t *len);
+
+/** upb_array *****************************************************************/
+
+/* Creates a new array on the given arena that holds elements of this type. */
+upb_array *upb_array_new(upb_arena *a, upb_fieldtype_t type);
+
+/* Returns the size of the array. */
+size_t upb_array_size(const upb_array *arr);
+
+/* Returns the given element, which must be within the array's current size. */
+upb_msgval upb_array_get(const upb_array *arr, size_t i);
+
+/* Sets the given element, which must be within the array's current size. */
+void upb_array_set(upb_array *arr, size_t i, upb_msgval val);
+
+/* Appends an element to the array. Returns false on allocation failure. */
+bool upb_array_append(upb_array *array, upb_msgval val, upb_arena *arena);
+
+/* Changes the size of a vector. New elements are initialized to empty/0.
+ * Returns false on allocation failure. */
+bool upb_array_resize(upb_array *array, size_t size, upb_arena *arena);
+
+/** upb_map *******************************************************************/
+
+/* Creates a new map on the given arena with the given key/value size. */
+upb_map *upb_map_new(upb_arena *a, upb_fieldtype_t key_type,
+ upb_fieldtype_t value_type);
+
+/* Returns the number of entries in the map. */
+size_t upb_map_size(const upb_map *map);
+
+/* Stores a value for the given key into |*val| (or the zero value if the key is
+ * not present). Returns whether the key was present. The |val| pointer may be
+ * NULL, in which case the function tests whether the given key is present. */
+bool upb_map_get(const upb_map *map, upb_msgval key, upb_msgval *val);
+
+/* Removes all entries in the map. */
+void upb_map_clear(upb_map *map);
+
+/* Sets the given key to the given value. Returns true if this was a new key in
+ * the map, or false if an existing key was replaced. */
+bool upb_map_set(upb_map *map, upb_msgval key, upb_msgval val,
+ upb_arena *arena);
+
+/* Deletes this key from the table. Returns true if the key was present. */
+bool upb_map_delete(upb_map *map, upb_msgval key);
+
+/* Map iteration:
*
- * - m is in upb_msgfactory_symtab(f)
- * - upb_msgdef_mapentry(m) == false (since map messages can't have layouts).
+ * size_t iter = UPB_MAP_BEGIN;
+ * while (upb_mapiter_next(map, &iter)) {
+ * upb_msgval key = upb_mapiter_key(map, iter);
+ * upb_msgval val = upb_mapiter_value(map, iter);
*
- * The returned objects will live for as long as the msgfactory does.
- *
- * TODO(haberman): consider making this thread-safe and take a const
- * upb_msgfactory. */
-const upb_msglayout *upb_msgfactory_getlayout(upb_msgfactory *f,
- const upb_msgdef *m);
+ * // If mutating is desired.
+ * upb_mapiter_setvalue(map, iter, value2);
+ * }
+ */
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
+/* Advances to the next entry. Returns false if no more entries are present. */
+bool upb_mapiter_next(const upb_map *map, size_t *iter);
-#endif /* UPB_MSGFACTORY_H_ */
+/* Returns the key and value for this entry of the map. */
+upb_msgval upb_mapiter_key(const upb_map *map, size_t iter);
+upb_msgval upb_mapiter_value(const upb_map *map, size_t iter);
+
+/* Sets the value for this entry. The iterator must not be done, and the
+ * iterator must not have been initialized const. */
+void upb_mapiter_setvalue(upb_map *map, size_t iter, upb_msgval value);
+
+
+#endif /* UPB_REFLECTION_H_ */
/*
** upb::Handlers (upb_handlers)
**
@@ -5693,15 +5381,16 @@
return sub->closure ? true : false;
}
-UPB_INLINE bool upb_sink_endsubmsg(upb_sink s, upb_selector_t sel) {
+UPB_INLINE bool upb_sink_endsubmsg(upb_sink s, upb_sink sub,
+ upb_selector_t sel) {
typedef upb_endfield_handlerfunc func;
func *endsubmsg;
const void *hd;
if (!s.handlers) return true;
endsubmsg = (func*)upb_handlers_gethandler(s.handlers, sel, &hd);
- if (!endsubmsg) return s.closure;
- return endsubmsg(s.closure, hd);
+ if (!endsubmsg) return true;
+ return endsubmsg(sub.closure, hd);
}
#ifdef __cplusplus
@@ -5867,8 +5556,8 @@
return ret;
}
- bool EndSubMessage(HandlersPtr::Selector s) {
- return upb_sink_endsubmsg(sink_, s);
+ bool EndSubMessage(HandlersPtr::Selector s, Sink sub) {
+ return upb_sink_endsubmsg(sink_, sub.sink_, s);
}
/* For repeated fields of any type, the sequence of values must be wrapped in
@@ -6567,21 +6256,22 @@
* descriptor type (upb_descriptortype_t). */
extern const uint8_t upb_pb_native_wire_types[];
-UPB_INLINE uint64_t byteswap64(uint64_t val)
-{
- return ((((val) & 0xff00000000000000ull) >> 56)
- | (((val) & 0x00ff000000000000ull) >> 40)
- | (((val) & 0x0000ff0000000000ull) >> 24)
- | (((val) & 0x000000ff00000000ull) >> 8)
- | (((val) & 0x00000000ff000000ull) << 8)
- | (((val) & 0x0000000000ff0000ull) << 24)
- | (((val) & 0x000000000000ff00ull) << 40)
- | (((val) & 0x00000000000000ffull) << 56));
+UPB_INLINE uint64_t byteswap64(uint64_t val) {
+ uint64_t byte = 0xff;
+ return (val & (byte << 56) >> 56)
+ | (val & (byte << 48) >> 40)
+ | (val & (byte << 40) >> 24)
+ | (val & (byte << 32) >> 8)
+ | (val & (byte << 24) << 8)
+ | (val & (byte << 16) << 24)
+ | (val & (byte << 8) << 40)
+ | (val & (byte << 0) << 56);
}
/* Zig-zag encoding/decoding **************************************************/
-UPB_INLINE int32_t upb_zzdec_32(uint32_t n) {
+UPB_INLINE int32_t upb_zzdec_32(uint64_t _n) {
+ uint32_t n = (uint32_t)_n;
return (n >> 1) ^ -(int32_t)(n & 1);
}
UPB_INLINE int64_t upb_zzdec_64(uint64_t n) {
@@ -7064,8 +6754,9 @@
#endif /* UPB_JSON_TYPED_PRINTER_H_ */
/* See port_def.inc. This should #undef all macros #defined there. */
+#undef UPB_MAPTYPE_STRING
#undef UPB_SIZE
-#undef UPB_FIELD_AT
+#undef UPB_PTR_AT
#undef UPB_READ_ONEOF
#undef UPB_WRITE_ONEOF
#undef UPB_INLINE
@@ -7075,6 +6766,7 @@
#undef UPB_MAX
#undef UPB_MIN
#undef UPB_UNUSED
+#undef UPB_ASSUME
#undef UPB_ASSERT
#undef UPB_ASSERT_DEBUGVAR
#undef UPB_UNREACHABLE
diff --git a/ruby/google-protobuf.gemspec b/ruby/google-protobuf.gemspec
index 1ba594d..29af948 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.11.0.rc.1"
+ s.version = "3.12.0.rc.2"
git_tag = "v#{s.version.to_s.sub('.rc.', '-rc')}" # Converts X.Y.Z.rc.N to vX.Y.Z-rcN, used for the git tag
s.licenses = ["BSD-3-Clause"]
s.summary = "Protocol Buffers"
@@ -17,13 +17,13 @@
else
s.files += Dir.glob('ext/**/*')
s.extensions= ["ext/google/protobuf_c/extconf.rb"]
- s.add_development_dependency "rake-compiler-dock", "~> 0.6.0"
+ s.add_development_dependency "rake-compiler-dock", ">= 1.0.1", "< 2.0"
end
s.test_files = ["tests/basic.rb",
"tests/stress.rb",
"tests/generated_code_test.rb"]
s.required_ruby_version = '>= 2.3'
- s.add_development_dependency "rake-compiler", "~> 0.9.5"
+ s.add_development_dependency "rake-compiler", "~> 1.1.0"
s.add_development_dependency "test-unit", '~> 3.0', '>= 3.0.9'
s.add_development_dependency "rubygems-tasks", "~> 0.2.4"
end
diff --git a/ruby/lib/google/protobuf/well_known_types.rb b/ruby/lib/google/protobuf/well_known_types.rb
old mode 100644
new mode 100755
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptor.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptor.java
index dd9179b..2f7261a 100644
--- a/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptor.java
+++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptor.java
@@ -85,7 +85,7 @@
* call-seq:
* Descriptor.name => name
*
- * Returns the name of this message type as a fully-qualfied string (e.g.,
+ * Returns the name of this message type as a fully-qualified string (e.g.,
* My.Package.MessageType).
*/
@JRubyMethod(name = "name")
diff --git a/ruby/tests/basic.rb b/ruby/tests/basic.rb
old mode 100644
new mode 100755
index 1cb8d34..687e1fb
--- a/ruby/tests/basic.rb
+++ b/ruby/tests/basic.rb
@@ -32,11 +32,11 @@
include CommonTests
def test_has_field
- m = TestMessage.new
- assert !m.has_optional_msg?
- m.optional_msg = TestMessage2.new
- assert m.has_optional_msg?
- assert TestMessage.descriptor.lookup('optional_msg').has?(m)
+ m = TestSingularFields.new
+ assert !m.has_singular_msg?
+ m.singular_msg = TestMessage2.new
+ assert m.has_singular_msg?
+ assert TestSingularFields.descriptor.lookup('singular_msg').has?(m)
m = OneofMessage.new
assert !m.has_my_oneof?
@@ -45,33 +45,32 @@
assert_raise NoMethodError do
m.has_a?
end
+ assert_true OneofMessage.descriptor.lookup('a').has?(m)
+
+ m = TestSingularFields.new
+ assert_raise NoMethodError do
+ m.has_singular_int32?
+ end
assert_raise ArgumentError do
- OneofMessage.descriptor.lookup('a').has?(m)
+ TestSingularFields.descriptor.lookup('singular_int32').has?(m)
+ end
+
+ assert_raise NoMethodError do
+ m.has_singular_string?
+ end
+ assert_raise ArgumentError do
+ TestSingularFields.descriptor.lookup('singular_string').has?(m)
+ end
+
+ assert_raise NoMethodError do
+ m.has_singular_bool?
+ end
+ assert_raise ArgumentError do
+ TestSingularFields.descriptor.lookup('singular_bool').has?(m)
end
m = TestMessage.new
assert_raise NoMethodError do
- m.has_optional_int32?
- end
- assert_raise ArgumentError do
- TestMessage.descriptor.lookup('optional_int32').has?(m)
- end
-
- assert_raise NoMethodError do
- m.has_optional_string?
- end
- assert_raise ArgumentError do
- TestMessage.descriptor.lookup('optional_string').has?(m)
- end
-
- assert_raise NoMethodError do
- m.has_optional_bool?
- end
- assert_raise ArgumentError do
- TestMessage.descriptor.lookup('optional_bool').has?(m)
- end
-
- assert_raise NoMethodError do
m.has_repeated_msg?
end
assert_raise ArgumentError do
@@ -79,41 +78,60 @@
end
end
+ def test_no_presence
+ m = TestSingularFields.new
+
+ # Explicitly setting to zero does not cause anything to be serialized.
+ m.singular_int32 = 0
+ assert_equal "", TestSingularFields.encode(m)
+
+ # Explicitly setting to a non-zero value *does* cause serialization.
+ m.singular_int32 = 1
+ assert_not_equal "", TestSingularFields.encode(m)
+
+ m.singular_int32 = 0
+ assert_equal "", TestSingularFields.encode(m)
+ end
+
def test_set_clear_defaults
+ m = TestSingularFields.new
+
+ m.singular_int32 = -42
+ assert_equal -42, m.singular_int32
+ m.clear_singular_int32
+ assert_equal 0, m.singular_int32
+
+ m.singular_int32 = 50
+ assert_equal 50, m.singular_int32
+ TestSingularFields.descriptor.lookup('singular_int32').clear(m)
+ assert_equal 0, m.singular_int32
+
+ m.singular_string = "foo bar"
+ assert_equal "foo bar", m.singular_string
+ m.clear_singular_string
+ assert_equal "", m.singular_string
+
+ m.singular_string = "foo"
+ assert_equal "foo", m.singular_string
+ TestSingularFields.descriptor.lookup('singular_string').clear(m)
+ assert_equal "", m.singular_string
+
+ m.singular_msg = TestMessage2.new(:foo => 42)
+ assert_equal TestMessage2.new(:foo => 42), m.singular_msg
+ assert m.has_singular_msg?
+ m.clear_singular_msg
+ assert_equal nil, m.singular_msg
+ assert !m.has_singular_msg?
+
+ m.singular_msg = TestMessage2.new(:foo => 42)
+ assert_equal TestMessage2.new(:foo => 42), m.singular_msg
+ TestSingularFields.descriptor.lookup('singular_msg').clear(m)
+ assert_equal nil, m.singular_msg
+ end
+
+ def test_clear_repeated_fields
m = TestMessage.new
- m.optional_int32 = -42
- assert_equal -42, m.optional_int32
- m.clear_optional_int32
- assert_equal 0, m.optional_int32
-
- m.optional_int32 = 50
- assert_equal 50, m.optional_int32
- TestMessage.descriptor.lookup('optional_int32').clear(m)
- assert_equal 0, m.optional_int32
-
- m.optional_string = "foo bar"
- assert_equal "foo bar", m.optional_string
- m.clear_optional_string
- assert_equal "", m.optional_string
-
- m.optional_string = "foo"
- assert_equal "foo", m.optional_string
- TestMessage.descriptor.lookup('optional_string').clear(m)
- assert_equal "", m.optional_string
-
- m.optional_msg = TestMessage2.new(:foo => 42)
- assert_equal TestMessage2.new(:foo => 42), m.optional_msg
- assert m.has_optional_msg?
- m.clear_optional_msg
- assert_equal nil, m.optional_msg
- assert !m.has_optional_msg?
-
- m.optional_msg = TestMessage2.new(:foo => 42)
- assert_equal TestMessage2.new(:foo => 42), m.optional_msg
- TestMessage.descriptor.lookup('optional_msg').clear(m)
- assert_equal nil, m.optional_msg
-
m.repeated_int32.push(1)
assert_equal [1], m.repeated_int32
m.clear_repeated_int32
@@ -128,6 +146,7 @@
m.a = "foo"
assert_equal "foo", m.a
assert m.has_my_oneof?
+ assert_equal :a, m.my_oneof
m.clear_a
assert !m.has_my_oneof?
@@ -143,7 +162,6 @@
assert !m.has_my_oneof?
end
-
def test_initialization_map_errors
e = assert_raise ArgumentError do
TestMessage.new(:hello => "world")
@@ -276,6 +294,86 @@
assert_equal m5, m
end
+ def test_map_wrappers_with_default_values
+ run_asserts = ->(m) {
+ assert_equal 0.0, m.map_double[0].value
+ assert_equal 0.0, m.map_float[0].value
+ assert_equal 0, m.map_int32[0].value
+ assert_equal 0, m.map_int64[0].value
+ assert_equal 0, m.map_uint32[0].value
+ assert_equal 0, m.map_uint64[0].value
+ assert_equal false, m.map_bool[0].value
+ assert_equal '', m.map_string[0].value
+ assert_equal '', m.map_bytes[0].value
+ }
+
+ m = proto_module::Wrapper.new(
+ map_double: {0 => Google::Protobuf::DoubleValue.new(value: 0.0)},
+ map_float: {0 => Google::Protobuf::FloatValue.new(value: 0.0)},
+ map_int32: {0 => Google::Protobuf::Int32Value.new(value: 0)},
+ map_int64: {0 => Google::Protobuf::Int64Value.new(value: 0)},
+ map_uint32: {0 => Google::Protobuf::UInt32Value.new(value: 0)},
+ map_uint64: {0 => Google::Protobuf::UInt64Value.new(value: 0)},
+ map_bool: {0 => Google::Protobuf::BoolValue.new(value: false)},
+ map_string: {0 => Google::Protobuf::StringValue.new(value: '')},
+ map_bytes: {0 => Google::Protobuf::BytesValue.new(value: '')},
+ )
+
+ run_asserts.call(m)
+ serialized = proto_module::Wrapper::encode(m)
+ m2 = proto_module::Wrapper::decode(serialized)
+ run_asserts.call(m2)
+
+ # Test the case where we are serializing directly from the parsed form
+ # (before anything lazy is materialized).
+ m3 = proto_module::Wrapper::decode(serialized)
+ serialized2 = proto_module::Wrapper::encode(m3)
+ m4 = proto_module::Wrapper::decode(serialized2)
+ run_asserts.call(m4)
+
+ # Test that the lazy form compares equal to the expanded form.
+ m5 = proto_module::Wrapper::decode(serialized2)
+ assert_equal m5, m
+ end
+
+ def test_map_wrappers_with_no_value
+ run_asserts = ->(m) {
+ assert_equal 0.0, m.map_double[0].value
+ assert_equal 0.0, m.map_float[0].value
+ assert_equal 0, m.map_int32[0].value
+ assert_equal 0, m.map_int64[0].value
+ assert_equal 0, m.map_uint32[0].value
+ assert_equal 0, m.map_uint64[0].value
+ assert_equal false, m.map_bool[0].value
+ assert_equal '', m.map_string[0].value
+ assert_equal '', m.map_bytes[0].value
+ }
+
+ m = proto_module::Wrapper.new(
+ map_double: {0 => Google::Protobuf::DoubleValue.new()},
+ map_float: {0 => Google::Protobuf::FloatValue.new()},
+ map_int32: {0 => Google::Protobuf::Int32Value.new()},
+ map_int64: {0 => Google::Protobuf::Int64Value.new()},
+ map_uint32: {0 => Google::Protobuf::UInt32Value.new()},
+ map_uint64: {0 => Google::Protobuf::UInt64Value.new()},
+ map_bool: {0 => Google::Protobuf::BoolValue.new()},
+ map_string: {0 => Google::Protobuf::StringValue.new()},
+ map_bytes: {0 => Google::Protobuf::BytesValue.new()},
+ )
+ run_asserts.call(m)
+
+ serialized = proto_module::Wrapper::encode(m)
+ m2 = proto_module::Wrapper::decode(serialized)
+ run_asserts.call(m2)
+
+ # Test the case where we are serializing directly from the parsed form
+ # (before anything lazy is materialized).
+ m3 = proto_module::Wrapper::decode(serialized)
+ serialized2 = proto_module::Wrapper::encode(m3)
+ m4 = proto_module::Wrapper::decode(serialized2)
+ run_asserts.call(m4)
+ end
+
def test_concurrent_decoding
o = Outer.new
o.items[0] = Inner.new
diff --git a/ruby/tests/basic_proto2.rb b/ruby/tests/basic_proto2.rb
old mode 100644
new mode 100755
index 4c7ddd5..2d30a08
--- a/ruby/tests/basic_proto2.rb
+++ b/ruby/tests/basic_proto2.rb
@@ -73,10 +73,11 @@
m = OneofMessage.new
assert !m.has_my_oneof?
m.a = "foo"
+ assert m.has_my_oneof?
+ assert_equal :a, m.my_oneof
assert m.has_a?
assert OneofMessage.descriptor.lookup('a').has?(m)
assert_equal "foo", m.a
- assert m.has_my_oneof?
assert !m.has_b?
assert !OneofMessage.descriptor.lookup('b').has?(m)
assert !m.has_c?
@@ -197,6 +198,17 @@
assert !m.has_my_oneof?
end
+ def test_assign_nil
+ m = TestMessageDefaults.new
+ m.optional_msg = TestMessage2.new(:foo => 42)
+
+ assert_equal TestMessage2.new(:foo => 42), m.optional_msg
+ assert m.has_optional_msg?
+ m.optional_msg = nil
+ assert_equal nil, m.optional_msg
+ assert !m.has_optional_msg?
+ end
+
def test_initialization_map_errors
e = assert_raise ArgumentError do
TestMessage.new(:hello => "world")
diff --git a/ruby/tests/basic_test.proto b/ruby/tests/basic_test.proto
index a918540..6086879 100644
--- a/ruby/tests/basic_test.proto
+++ b/ruby/tests/basic_test.proto
@@ -21,17 +21,17 @@
}
message TestMessage {
- int32 optional_int32 = 1;
- int64 optional_int64 = 2;
- uint32 optional_uint32 = 3;
- uint64 optional_uint64 = 4;
- bool optional_bool = 5;
- float optional_float = 6;
- double optional_double = 7;
- string optional_string = 8;
- bytes optional_bytes = 9;
- TestMessage2 optional_msg = 10;
- TestEnum optional_enum = 11;
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional bool optional_bool = 5;
+ optional float optional_float = 6;
+ optional double optional_double = 7;
+ optional string optional_string = 8;
+ optional bytes optional_bytes = 9;
+ optional TestMessage2 optional_msg = 10;
+ optional TestEnum optional_enum = 11;
repeated int32 repeated_int32 = 12;
repeated int64 repeated_int64 = 13;
@@ -46,6 +46,20 @@
repeated TestEnum repeated_enum = 22;
}
+message TestSingularFields {
+ int32 singular_int32 = 1;
+ int64 singular_int64 = 2;
+ uint32 singular_uint32 = 3;
+ uint64 singular_uint64 = 4;
+ bool singular_bool = 5;
+ float singular_float = 6;
+ double singular_double = 7;
+ string singular_string = 8;
+ bytes singular_bytes = 9;
+ TestMessage2 singular_msg = 10;
+ TestEnum singular_enum = 11;
+}
+
message TestMessage2 {
int32 foo = 1;
}
diff --git a/ruby/tests/common_tests.rb b/ruby/tests/common_tests.rb
index ada4243..1f5013a 100644
--- a/ruby/tests/common_tests.rb
+++ b/ruby/tests/common_tests.rb
@@ -1265,6 +1265,37 @@
assert proto_module::TestMessage.new != nil
end
+ def test_wrappers_set_to_default
+ run_asserts = ->(m) {
+ assert_equal 0.0, m.double.value
+ assert_equal 0.0, m.float.value
+ assert_equal 0, m.int32.value
+ assert_equal 0, m.int64.value
+ assert_equal 0, m.uint32.value
+ assert_equal 0, m.uint64.value
+ assert_equal false, m.bool.value
+ assert_equal '', m.string.value
+ assert_equal '', m.bytes.value
+ }
+
+ m = proto_module::Wrapper.new(
+ double: Google::Protobuf::DoubleValue.new(value: 0.0),
+ float: Google::Protobuf::FloatValue.new(value: 0.0),
+ int32: Google::Protobuf::Int32Value.new(value: 0),
+ int64: Google::Protobuf::Int64Value.new(value: 0),
+ uint32: Google::Protobuf::UInt32Value.new(value: 0),
+ uint64: Google::Protobuf::UInt64Value.new(value: 0),
+ bool: Google::Protobuf::BoolValue.new(value: false),
+ string: Google::Protobuf::StringValue.new(value: ""),
+ bytes: Google::Protobuf::BytesValue.new(value: ''),
+ )
+
+ run_asserts.call(m)
+ m2 = proto_module::Wrapper.decode(m.to_proto)
+ run_asserts.call(m2)
+ m3 = proto_module::Wrapper.decode_json(m.to_json)
+ end
+
def test_wrapper_getters
run_asserts = ->(m) {
assert_equal 2.0, m.double_as_value
@@ -1692,7 +1723,7 @@
m.duration = Rational(3, 2)
assert_equal Google::Protobuf::Duration.new(seconds: 1, nanos: 500_000_000), m.duration
- m.duration = BigDecimal.new("5")
+ m.duration = BigDecimal("5")
assert_equal Google::Protobuf::Duration.new(seconds: 5, nanos: 0), m.duration
m = proto_module::TimeMessage.new(duration: 1.1)
@@ -1708,7 +1739,7 @@
m.freeze
frozen_error = assert_raise(FrozenErrorType) { m.optional_int32 = 20 }
- assert_equal "can't modify frozen #{proto_module}::TestMessage", frozen_error.message
+ assert_match "can't modify frozen #{proto_module}::TestMessage", frozen_error.message
assert_equal 10, m.optional_int32
assert_equal true, m.frozen?
diff --git a/ruby/tests/encode_decode_test.rb b/ruby/tests/encode_decode_test.rb
old mode 100644
new mode 100755
diff --git a/ruby/tests/gc_test.rb b/ruby/tests/gc_test.rb
old mode 100644
new mode 100755
index 55b9628..6ef4e2e
--- a/ruby/tests/gc_test.rb
+++ b/ruby/tests/gc_test.rb
@@ -4,7 +4,9 @@
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)))
old_gc = GC.stress
-GC.stress = 0x01 | 0x04
+# Ruby 2.7.0 - 2.7.1 has a GC bug in its parser, so turn off stress for now
+# See https://bugs.ruby-lang.org/issues/16807
+GC.stress = 0x01 | 0x04 unless RUBY_VERSION.match?(/^2\.7\./)
require 'generated_code_pb'
require 'generated_code_proto2_pb'
GC.stress = old_gc
diff --git a/ruby/tests/generated_code_proto2_test.rb b/ruby/tests/generated_code_proto2_test.rb
old mode 100644
new mode 100755
diff --git a/ruby/tests/generated_code_test.rb b/ruby/tests/generated_code_test.rb
old mode 100644
new mode 100755
diff --git a/ruby/tests/repeated_field_test.rb b/ruby/tests/repeated_field_test.rb
old mode 100644
new mode 100755
index ced9de8..6307447
--- a/ruby/tests/repeated_field_test.rb
+++ b/ruby/tests/repeated_field_test.rb
@@ -20,6 +20,7 @@
:iter_for_each_with_index, :dimensions, :copy_data, :copy_data_simple,
:nitems, :iter_for_reverse_each, :indexes, :append, :prepend]
arr_methods -= [:union, :difference, :filter!]
+ arr_methods -= [:intersection, :deconstruct] # ruby 2.7 methods we can ignore
arr_methods.each do |method_name|
assert m.repeated_string.respond_to?(method_name) == true, "does not respond to #{method_name}"
end
diff --git a/ruby/tests/stress.rb b/ruby/tests/stress.rb
old mode 100644
new mode 100755
diff --git a/ruby/tests/type_errors.rb b/ruby/tests/type_errors.rb
old mode 100644
new mode 100755
diff --git a/ruby/tests/well_known_types_test.rb b/ruby/tests/well_known_types_test.rb
old mode 100644
new mode 100755
diff --git a/ruby/travis-test.sh b/ruby/travis-test.sh
index 6dec0c9..b39a6c5 100755
--- a/ruby/travis-test.sh
+++ b/ruby/travis-test.sh
@@ -16,7 +16,7 @@
git clean -f && \
gem install bundler && bundle && \
rake test"
- elif [ "$version" == "ruby-2.6.0" ] ; then
+ elif [ "$version" == "ruby-2.6.0" -o "$version" == "ruby-2.7.0" ] ; then
bash --login -c \
"rvm install $version && rvm use $version && \
which ruby && \
diff --git a/src/Makefile.am b/src/Makefile.am
index 60bb445..1837279 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -18,7 +18,7 @@
PTHREAD_DEF =
endif
-PROTOBUF_VERSION = 22:0:0
+PROTOBUF_VERSION = 23:0:0
if GCC
# Turn on all warnings except for sign comparison (we ignore sign comparison
@@ -510,6 +510,7 @@
google/protobuf/unittest_proto3_arena.proto \
google/protobuf/unittest_proto3_arena_lite.proto \
google/protobuf/unittest_proto3_lite.proto \
+ google/protobuf/unittest_proto3_optional.proto \
google/protobuf/unittest_well_known_types.proto \
google/protobuf/util/internal/testdata/anys.proto \
google/protobuf/util/internal/testdata/books.proto \
@@ -643,6 +644,8 @@
google/protobuf/unittest_proto3_arena_lite.pb.h \
google/protobuf/unittest_proto3_lite.pb.cc \
google/protobuf/unittest_proto3_lite.pb.h \
+ google/protobuf/unittest_proto3_optional.pb.cc \
+ google/protobuf/unittest_proto3_optional.pb.h \
google/protobuf/unittest_well_known_types.pb.cc \
google/protobuf/unittest_well_known_types.pb.h \
google/protobuf/util/internal/testdata/anys.pb.cc \
@@ -686,7 +689,7 @@
# relative to srcdir, which may not be the same as the current directory when
# building out-of-tree.
unittest_proto_middleman: protoc$(EXEEXT) $(protoc_inputs)
- oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/protoc$(EXEEXT) -I. --cpp_out=$$oldpwd $(protoc_inputs) )
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/protoc$(EXEEXT) -I. --cpp_out=$$oldpwd $(protoc_inputs) --experimental_allow_proto3_optional )
touch unittest_proto_middleman
endif
diff --git a/src/README.md b/src/README.md
index 007deb3..78d6bb5 100644
--- a/src/README.md
+++ b/src/README.md
@@ -40,22 +40,21 @@
have also cloned the submodules and generated the configure script (skip this
if you are using a release .tar.gz or .zip package):
-```shell
git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf
git submodule update --init --recursive
./autogen.sh
-```
+
To build and install the C++ Protocol Buffer runtime and the Protocol
Buffer compiler (protoc) execute the following:
-```shell
+
./configure
make
make check
sudo make install
sudo ldconfig # refresh shared library cache.
-```
+
If "make check" fails, you can still install, but it is likely that
some features of this library will not work correctly on your system.
Proceed at your own risk.
@@ -123,15 +122,15 @@
For a Mac system, Unix tools are not available by default. You will first need
to install Xcode from the Mac AppStore and then run the following command from
a terminal:
-```shell
+
sudo xcode-select --install
-```shell
+
To install Unix tools, you can install "port" following the instructions at
https://www.macports.org . This will reside in /opt/local/bin/port for most
Mac installations.
-```shell
+
sudo /opt/local/bin/port install autoconf automake libtool
-```
+
Then follow the Unix instructions above.
**Note for cross-compiling**
diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc
index 5a79335..1eba999 100644
--- a/src/google/protobuf/any.pb.cc
+++ b/src/google/protobuf/any.pb.cc
@@ -69,16 +69,15 @@
&scc_info_Any_google_2fprotobuf_2fany_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fany_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fany_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto = {
- &descriptor_table_google_2fprotobuf_2fany_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fany_2eproto, "google/protobuf/any.proto", 205,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fany_2eproto, "google/protobuf/any.proto", 205,
&descriptor_table_google_2fprotobuf_2fany_2eproto_once, descriptor_table_google_2fprotobuf_2fany_2eproto_sccs, descriptor_table_google_2fprotobuf_2fany_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fany_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fany_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fany_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fany_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -102,23 +101,26 @@
public:
};
-Any::Any()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr), _any_metadata_(&type_url_, &value_) {
+Any::Any(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
+ _any_metadata_(&type_url_, &value_) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Any)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Any)
}
Any::Any(const Any& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_any_metadata_(&type_url_, &value_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_type_url().empty()) {
- type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.type_url_);
+ type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_type_url(),
+ GetArena());
}
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_value().empty()) {
- value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
+ value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_value(),
+ GetArena());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.Any)
}
@@ -132,13 +134,21 @@
Any::~Any() {
// @@protoc_insertion_point(destructor:google.protobuf.Any)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Any::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
+void Any::ArenaDtor(void* object) {
+ Any* _this = reinterpret_cast< Any* >(object);
+ (void)_this;
+}
+void Any::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void Any::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -154,13 +164,14 @@
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- _internal_metadata_.Clear();
+ type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Any::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -189,7 +200,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -227,7 +240,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any)
return target;
@@ -282,17 +295,15 @@
void Any::MergeFrom(const Any& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Any)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.type_url().size() > 0) {
-
- type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.type_url_);
+ _internal_set_type_url(from._internal_type_url());
}
if (from.value().size() > 0) {
-
- value_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.value_);
+ _internal_set_value(from._internal_value());
}
}
@@ -316,11 +327,9 @@
void Any::InternalSwap(Any* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- type_url_.Swap(&other->type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ type_url_.Swap(&other->type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
::PROTOBUF_NAMESPACE_ID::Metadata Any::GetMetadata() const {
@@ -332,7 +341,7 @@
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Any >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Any >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Any >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h
index 7ea175d..61b4722 100644
--- a/src/google/protobuf/any.pb.h
+++ b/src/google/protobuf/any.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -66,10 +66,10 @@
// ===================================================================
-class PROTOBUF_EXPORT Any :
+class PROTOBUF_EXPORT Any PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ {
public:
- Any();
+ inline Any() : Any(nullptr) {};
virtual ~Any();
Any(const Any& from);
@@ -83,7 +83,7 @@
return *this;
}
inline Any& operator=(Any&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -148,6 +148,15 @@
}
inline void Swap(Any* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(Any* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -182,13 +191,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.Any";
}
+ protected:
+ explicit Any(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -218,6 +225,15 @@
std::string* mutable_type_url();
std::string* release_type_url();
void set_allocated_type_url(std::string* type_url);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_type_url();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_type_url(
+ std::string* type_url);
private:
const std::string& _internal_type_url() const;
void _internal_set_type_url(const std::string& value);
@@ -234,6 +250,15 @@
std::string* mutable_value();
std::string* release_value();
void set_allocated_value(std::string* value);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_value();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_value(
+ std::string* value);
private:
const std::string& _internal_value() const;
void _internal_set_value(const std::string& value);
@@ -244,7 +269,9 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_url_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
@@ -264,7 +291,7 @@
// string type_url = 1;
inline void Any::clear_type_url() {
- type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Any::type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.type_url)
@@ -279,38 +306,39 @@
return _internal_mutable_type_url();
}
inline const std::string& Any::_internal_type_url() const {
- return type_url_.GetNoArena();
+ return type_url_.Get();
}
inline void Any::_internal_set_type_url(const std::string& value) {
- type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Any::set_type_url(std::string&& value) {
- type_url_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ type_url_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.type_url)
}
inline void Any::set_type_url(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url)
}
-inline void Any::set_type_url(const char* value, size_t size) {
+inline void Any::set_type_url(const char* value,
+ size_t size) {
- type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.type_url)
}
inline std::string* Any::_internal_mutable_type_url() {
- return type_url_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Any::release_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.type_url)
-
- return type_url_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Any::set_allocated_type_url(std::string* type_url) {
if (type_url != nullptr) {
@@ -318,13 +346,33 @@
} else {
}
- type_url_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_url);
+ type_url_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_url,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.type_url)
}
+inline std::string* Any::unsafe_arena_release_type_url() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Any.type_url)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return type_url_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Any::unsafe_arena_set_allocated_type_url(
+ std::string* type_url) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (type_url != nullptr) {
+
+ } else {
+
+ }
+ type_url_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ type_url, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Any.type_url)
+}
// bytes value = 2;
inline void Any::clear_value() {
- value_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Any::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.value)
@@ -339,38 +387,39 @@
return _internal_mutable_value();
}
inline const std::string& Any::_internal_value() const {
- return value_.GetNoArena();
+ return value_.Get();
}
inline void Any::_internal_set_value(const std::string& value) {
- value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Any::set_value(std::string&& value) {
- value_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ value_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.value)
}
inline void Any::set_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.value)
}
-inline void Any::set_value(const void* value, size_t size) {
+inline void Any::set_value(const void* value,
+ size_t size) {
- value_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.value)
}
inline std::string* Any::_internal_mutable_value() {
- return value_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Any::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.value)
-
- return value_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Any::set_allocated_value(std::string* value) {
if (value != nullptr) {
@@ -378,9 +427,29 @@
} else {
}
- value_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
}
+inline std::string* Any::unsafe_arena_release_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Any.value)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Any::unsafe_arena_set_allocated_value(
+ std::string* value) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (value != nullptr) {
+
+ } else {
+
+ }
+ value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ value, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Any.value)
+}
#ifdef __GNUC__
#pragma GCC diagnostic pop
diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc
index 294c4ef..816df12 100644
--- a/src/google/protobuf/api.pb.cc
+++ b/src/google/protobuf/api.pb.cc
@@ -159,16 +159,15 @@
&scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fapi_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fapi_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto = {
- &descriptor_table_google_2fprotobuf_2fapi_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto, "google/protobuf/api.proto", 750,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto, "google/protobuf/api.proto", 750,
&descriptor_table_google_2fprotobuf_2fapi_2eproto_once, descriptor_table_google_2fprotobuf_2fapi_2eproto_sccs, descriptor_table_google_2fprotobuf_2fapi_2eproto_deps, 3, 2,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fapi_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fapi_2eproto, 3, file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto, file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fapi_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fapi_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fapi_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fapi_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -190,30 +189,35 @@
options_.Clear();
}
void Api::clear_source_context() {
- if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) {
+ if (GetArena() == nullptr && source_context_ != nullptr) {
delete source_context_;
}
source_context_ = nullptr;
}
-Api::Api()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+Api::Api(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
+ methods_(arena),
+ options_(arena),
+ mixins_(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Api)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Api)
}
Api::Api(const Api& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
methods_(from.methods_),
options_(from.options_),
mixins_(from.mixins_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
+ GetArena());
}
version_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_version().empty()) {
- version_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.version_);
+ version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_version(),
+ GetArena());
}
if (from._internal_has_source_context()) {
source_context_ = new PROTOBUF_NAMESPACE_ID::SourceContext(*from.source_context_);
@@ -236,14 +240,22 @@
Api::~Api() {
// @@protoc_insertion_point(destructor:google.protobuf.Api)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Api::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
version_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete source_context_;
}
+void Api::ArenaDtor(void* object) {
+ Api* _this = reinterpret_cast< Api* >(object);
+ (void)_this;
+}
+void Api::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void Api::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -262,18 +274,19 @@
methods_.Clear();
options_.Clear();
mixins_.Clear();
- name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- version_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) {
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ version_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ if (GetArena() == nullptr && source_context_ != nullptr) {
delete source_context_;
}
source_context_ = nullptr;
syntax_ = 0;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Api::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -343,7 +356,7 @@
// .google.protobuf.Syntax syntax = 7;
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_syntax(static_cast<PROTOBUF_NAMESPACE_ID::Syntax>(val));
} else goto handle_unusual;
@@ -354,7 +367,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -435,7 +450,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Api)
return target;
@@ -524,7 +539,7 @@
void Api::MergeFrom(const Api& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Api)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -532,12 +547,10 @@
options_.MergeFrom(from.options_);
mixins_.MergeFrom(from.mixins_);
if (from.name().size() > 0) {
-
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ _internal_set_name(from._internal_name());
}
if (from.version().size() > 0) {
-
- version_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.version_);
+ _internal_set_version(from._internal_version());
}
if (from.has_source_context()) {
_internal_mutable_source_context()->PROTOBUF_NAMESPACE_ID::SourceContext::MergeFrom(from._internal_source_context());
@@ -567,16 +580,18 @@
void Api::InternalSwap(Api* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
methods_.InternalSwap(&other->methods_);
options_.InternalSwap(&other->options_);
mixins_.InternalSwap(&other->mixins_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- version_.Swap(&other->version_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(source_context_, other->source_context_);
- swap(syntax_, other->syntax_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ version_.Swap(&other->version_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Api, syntax_)
+ + sizeof(Api::syntax_)
+ - PROTOBUF_FIELD_OFFSET(Api, source_context_)>(
+ reinterpret_cast<char*>(&source_context_),
+ reinterpret_cast<char*>(&other->source_context_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Api::GetMetadata() const {
@@ -595,27 +610,31 @@
void Method::clear_options() {
options_.Clear();
}
-Method::Method()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+Method::Method(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
+ options_(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Method)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Method)
}
Method::Method(const Method& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
options_(from.options_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
+ GetArena());
}
request_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_request_type_url().empty()) {
- request_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.request_type_url_);
+ request_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_request_type_url(),
+ GetArena());
}
response_type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_response_type_url().empty()) {
- response_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.response_type_url_);
+ response_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_response_type_url(),
+ GetArena());
}
::memcpy(&request_streaming_, &from.request_streaming_,
static_cast<size_t>(reinterpret_cast<char*>(&syntax_) -
@@ -636,14 +655,22 @@
Method::~Method() {
// @@protoc_insertion_point(destructor:google.protobuf.Method)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Method::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
request_type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
response_type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
+void Method::ArenaDtor(void* object) {
+ Method* _this = reinterpret_cast< Method* >(object);
+ (void)_this;
+}
+void Method::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void Method::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -660,17 +687,18 @@
(void) cached_has_bits;
options_.Clear();
- name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- request_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- response_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ request_type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ response_type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
::memset(&request_streaming_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Method::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -697,7 +725,7 @@
// bool request_streaming = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
- request_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ request_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -713,7 +741,7 @@
// bool response_streaming = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
- response_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ response_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -732,7 +760,7 @@
// .google.protobuf.Syntax syntax = 7;
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_syntax(static_cast<PROTOBUF_NAMESPACE_ID::Syntax>(val));
} else goto handle_unusual;
@@ -743,7 +771,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -822,7 +852,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Method)
return target;
@@ -907,22 +937,19 @@
void Method::MergeFrom(const Method& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Method)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
-
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ _internal_set_name(from._internal_name());
}
if (from.request_type_url().size() > 0) {
-
- request_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.request_type_url_);
+ _internal_set_request_type_url(from._internal_request_type_url());
}
if (from.response_type_url().size() > 0) {
-
- response_type_url_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.response_type_url_);
+ _internal_set_response_type_url(from._internal_response_type_url());
}
if (from.request_streaming() != 0) {
_internal_set_request_streaming(from._internal_request_streaming());
@@ -955,17 +982,17 @@
void Method::InternalSwap(Method* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- request_type_url_.Swap(&other->request_type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- response_type_url_.Swap(&other->response_type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(request_streaming_, other->request_streaming_);
- swap(response_streaming_, other->response_streaming_);
- swap(syntax_, other->syntax_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ request_type_url_.Swap(&other->request_type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ response_type_url_.Swap(&other->response_type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Method, syntax_)
+ + sizeof(Method::syntax_)
+ - PROTOBUF_FIELD_OFFSET(Method, request_streaming_)>(
+ reinterpret_cast<char*>(&request_streaming_),
+ reinterpret_cast<char*>(&other->request_streaming_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Method::GetMetadata() const {
@@ -981,22 +1008,24 @@
public:
};
-Mixin::Mixin()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+Mixin::Mixin(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Mixin)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Mixin)
}
Mixin::Mixin(const Mixin& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
+ GetArena());
}
root_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_root().empty()) {
- root_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.root_);
+ root_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_root(),
+ GetArena());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.Mixin)
}
@@ -1010,13 +1039,21 @@
Mixin::~Mixin() {
// @@protoc_insertion_point(destructor:google.protobuf.Mixin)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Mixin::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
root_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
+void Mixin::ArenaDtor(void* object) {
+ Mixin* _this = reinterpret_cast< Mixin* >(object);
+ (void)_this;
+}
+void Mixin::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void Mixin::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -1032,13 +1069,14 @@
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- root_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- _internal_metadata_.Clear();
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ root_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Mixin::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1068,7 +1106,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1110,7 +1150,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Mixin)
return target;
@@ -1165,17 +1205,15 @@
void Mixin::MergeFrom(const Mixin& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Mixin)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.name().size() > 0) {
-
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ _internal_set_name(from._internal_name());
}
if (from.root().size() > 0) {
-
- root_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.root_);
+ _internal_set_root(from._internal_root());
}
}
@@ -1199,11 +1237,9 @@
void Mixin::InternalSwap(Mixin* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- root_.Swap(&other->root_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ root_.Swap(&other->root_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
::PROTOBUF_NAMESPACE_ID::Metadata Mixin::GetMetadata() const {
@@ -1215,13 +1251,13 @@
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Api* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Api >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Api >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Api >(arena);
}
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Method* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Method >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Method >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Method >(arena);
}
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::Mixin* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Mixin >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::Mixin >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::Mixin >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h
index 91bc34e..4fc4fa8 100644
--- a/src/google/protobuf/api.pb.h
+++ b/src/google/protobuf/api.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -76,10 +76,10 @@
// ===================================================================
-class PROTOBUF_EXPORT Api :
+class PROTOBUF_EXPORT Api PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ {
public:
- Api();
+ inline Api() : Api(nullptr) {};
virtual ~Api();
Api(const Api& from);
@@ -93,7 +93,7 @@
return *this;
}
inline Api& operator=(Api&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -125,6 +125,15 @@
}
inline void Swap(Api* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(Api* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -159,13 +168,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.Api";
}
+ protected:
+ explicit Api(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -254,6 +261,15 @@
std::string* mutable_name();
std::string* release_name();
void set_allocated_name(std::string* name);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_name();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ std::string* name);
private:
const std::string& _internal_name() const;
void _internal_set_name(const std::string& value);
@@ -270,6 +286,15 @@
std::string* mutable_version();
std::string* release_version();
void set_allocated_version(std::string* version);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_version();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_version(
+ std::string* version);
private:
const std::string& _internal_version() const;
void _internal_set_version(const std::string& value);
@@ -290,6 +315,9 @@
const PROTOBUF_NAMESPACE_ID::SourceContext& _internal_source_context() const;
PROTOBUF_NAMESPACE_ID::SourceContext* _internal_mutable_source_context();
public:
+ void unsafe_arena_set_allocated_source_context(
+ PROTOBUF_NAMESPACE_ID::SourceContext* source_context);
+ PROTOBUF_NAMESPACE_ID::SourceContext* unsafe_arena_release_source_context();
// .google.protobuf.Syntax syntax = 7;
void clear_syntax();
@@ -304,7 +332,9 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Method > methods_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option > options_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Mixin > mixins_;
@@ -317,10 +347,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Method :
+class PROTOBUF_EXPORT Method PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ {
public:
- Method();
+ inline Method() : Method(nullptr) {};
virtual ~Method();
Method(const Method& from);
@@ -334,7 +364,7 @@
return *this;
}
inline Method& operator=(Method&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -366,6 +396,15 @@
}
inline void Swap(Method* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(Method* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -400,13 +439,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.Method";
}
+ protected:
+ explicit Method(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -459,6 +496,15 @@
std::string* mutable_name();
std::string* release_name();
void set_allocated_name(std::string* name);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_name();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ std::string* name);
private:
const std::string& _internal_name() const;
void _internal_set_name(const std::string& value);
@@ -475,6 +521,15 @@
std::string* mutable_request_type_url();
std::string* release_request_type_url();
void set_allocated_request_type_url(std::string* request_type_url);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_request_type_url();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_request_type_url(
+ std::string* request_type_url);
private:
const std::string& _internal_request_type_url() const;
void _internal_set_request_type_url(const std::string& value);
@@ -491,6 +546,15 @@
std::string* mutable_response_type_url();
std::string* release_response_type_url();
void set_allocated_response_type_url(std::string* response_type_url);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_response_type_url();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_response_type_url(
+ std::string* response_type_url);
private:
const std::string& _internal_response_type_url() const;
void _internal_set_response_type_url(const std::string& value);
@@ -528,7 +592,9 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::Option > options_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr request_type_url_;
@@ -541,10 +607,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Mixin :
+class PROTOBUF_EXPORT Mixin PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ {
public:
- Mixin();
+ inline Mixin() : Mixin(nullptr) {};
virtual ~Mixin();
Mixin(const Mixin& from);
@@ -558,7 +624,7 @@
return *this;
}
inline Mixin& operator=(Mixin&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -590,6 +656,15 @@
}
inline void Swap(Mixin* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(Mixin* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -624,13 +699,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.Mixin";
}
+ protected:
+ explicit Mixin(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -660,6 +733,15 @@
std::string* mutable_name();
std::string* release_name();
void set_allocated_name(std::string* name);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_name();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ std::string* name);
private:
const std::string& _internal_name() const;
void _internal_set_name(const std::string& value);
@@ -676,6 +758,15 @@
std::string* mutable_root();
std::string* release_root();
void set_allocated_root(std::string* root);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_root();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_root(
+ std::string* root);
private:
const std::string& _internal_root() const;
void _internal_set_root(const std::string& value);
@@ -686,7 +777,9 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr root_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
@@ -705,7 +798,7 @@
// string name = 1;
inline void Api::clear_name() {
- name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Api::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.name)
@@ -720,38 +813,39 @@
return _internal_mutable_name();
}
inline const std::string& Api::_internal_name() const {
- return name_.GetNoArena();
+ return name_.Get();
}
inline void Api::_internal_set_name(const std::string& value) {
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Api::set_name(std::string&& value) {
- name_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ name_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.name)
}
inline void Api::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Api.name)
}
-inline void Api::set_name(const char* value, size_t size) {
+inline void Api::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.name)
}
inline std::string* Api::_internal_mutable_name() {
- return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Api::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Api.name)
-
- return name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Api::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -759,9 +853,29 @@
} else {
}
- name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.name)
}
+inline std::string* Api::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Api.name)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Api::unsafe_arena_set_allocated_name(
+ std::string* name) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (name != nullptr) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ name, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Api.name)
+}
// repeated .google.protobuf.Method methods = 2;
inline int Api::_internal_methods_size() const {
@@ -840,7 +954,7 @@
// string version = 4;
inline void Api::clear_version() {
- version_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ version_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Api::version() const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.version)
@@ -855,38 +969,39 @@
return _internal_mutable_version();
}
inline const std::string& Api::_internal_version() const {
- return version_.GetNoArena();
+ return version_.Get();
}
inline void Api::_internal_set_version(const std::string& value) {
- version_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Api::set_version(std::string&& value) {
- version_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ version_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.version)
}
inline void Api::set_version(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- version_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Api.version)
}
-inline void Api::set_version(const char* value, size_t size) {
+inline void Api::set_version(const char* value,
+ size_t size) {
- version_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.version)
}
inline std::string* Api::_internal_mutable_version() {
- return version_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return version_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Api::release_version() {
// @@protoc_insertion_point(field_release:google.protobuf.Api.version)
-
- return version_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return version_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Api::set_allocated_version(std::string* version) {
if (version != nullptr) {
@@ -894,9 +1009,29 @@
} else {
}
- version_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), version);
+ version_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), version,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.version)
}
+inline std::string* Api::unsafe_arena_release_version() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Api.version)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return version_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Api::unsafe_arena_set_allocated_version(
+ std::string* version) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (version != nullptr) {
+
+ } else {
+
+ }
+ version_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ version, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Api.version)
+}
// .google.protobuf.SourceContext source_context = 5;
inline bool Api::_internal_has_source_context() const {
@@ -914,7 +1049,29 @@
// @@protoc_insertion_point(field_get:google.protobuf.Api.source_context)
return _internal_source_context();
}
+inline void Api::unsafe_arena_set_allocated_source_context(
+ PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_);
+ }
+ source_context_ = source_context;
+ if (source_context) {
+
+ } else {
+
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Api.source_context)
+}
inline PROTOBUF_NAMESPACE_ID::SourceContext* Api::release_source_context() {
+
+ PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_;
+ source_context_ = nullptr;
+ if (GetArena() != nullptr) {
+ temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
+ }
+ return temp;
+}
+inline PROTOBUF_NAMESPACE_ID::SourceContext* Api::unsafe_arena_release_source_context() {
// @@protoc_insertion_point(field_release:google.protobuf.Api.source_context)
PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_;
@@ -924,7 +1081,7 @@
inline PROTOBUF_NAMESPACE_ID::SourceContext* Api::_internal_mutable_source_context() {
if (source_context_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceContext>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceContext>(GetArena());
source_context_ = p;
}
return source_context_;
@@ -934,12 +1091,13 @@
return _internal_mutable_source_context();
}
inline void Api::set_allocated_source_context(PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_);
}
if (source_context) {
- ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
+ ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
+ reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context)->GetArena();
if (message_arena != submessage_arena) {
source_context = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, source_context, submessage_arena);
@@ -1017,7 +1175,7 @@
// string name = 1;
inline void Method::clear_name() {
- name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Method::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.name)
@@ -1032,38 +1190,39 @@
return _internal_mutable_name();
}
inline const std::string& Method::_internal_name() const {
- return name_.GetNoArena();
+ return name_.Get();
}
inline void Method::_internal_set_name(const std::string& value) {
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Method::set_name(std::string&& value) {
- name_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ name_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.name)
}
inline void Method::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.name)
}
-inline void Method::set_name(const char* value, size_t size) {
+inline void Method::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.name)
}
inline std::string* Method::_internal_mutable_name() {
- return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Method::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Method.name)
-
- return name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Method::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -1071,13 +1230,33 @@
} else {
}
- name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.name)
}
+inline std::string* Method::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Method.name)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Method::unsafe_arena_set_allocated_name(
+ std::string* name) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (name != nullptr) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ name, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Method.name)
+}
// string request_type_url = 2;
inline void Method::clear_request_type_url() {
- request_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ request_type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Method::request_type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.request_type_url)
@@ -1092,38 +1271,39 @@
return _internal_mutable_request_type_url();
}
inline const std::string& Method::_internal_request_type_url() const {
- return request_type_url_.GetNoArena();
+ return request_type_url_.Get();
}
inline void Method::_internal_set_request_type_url(const std::string& value) {
- request_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ request_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Method::set_request_type_url(std::string&& value) {
- request_type_url_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ request_type_url_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.request_type_url)
}
inline void Method::set_request_type_url(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- request_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ request_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.request_type_url)
}
-inline void Method::set_request_type_url(const char* value, size_t size) {
+inline void Method::set_request_type_url(const char* value,
+ size_t size) {
- request_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ request_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.request_type_url)
}
inline std::string* Method::_internal_mutable_request_type_url() {
- return request_type_url_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return request_type_url_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Method::release_request_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Method.request_type_url)
-
- return request_type_url_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return request_type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Method::set_allocated_request_type_url(std::string* request_type_url) {
if (request_type_url != nullptr) {
@@ -1131,9 +1311,29 @@
} else {
}
- request_type_url_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), request_type_url);
+ request_type_url_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), request_type_url,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.request_type_url)
}
+inline std::string* Method::unsafe_arena_release_request_type_url() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Method.request_type_url)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return request_type_url_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Method::unsafe_arena_set_allocated_request_type_url(
+ std::string* request_type_url) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (request_type_url != nullptr) {
+
+ } else {
+
+ }
+ request_type_url_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ request_type_url, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Method.request_type_url)
+}
// bool request_streaming = 3;
inline void Method::clear_request_streaming() {
@@ -1157,7 +1357,7 @@
// string response_type_url = 4;
inline void Method::clear_response_type_url() {
- response_type_url_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ response_type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Method::response_type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.response_type_url)
@@ -1172,38 +1372,39 @@
return _internal_mutable_response_type_url();
}
inline const std::string& Method::_internal_response_type_url() const {
- return response_type_url_.GetNoArena();
+ return response_type_url_.Get();
}
inline void Method::_internal_set_response_type_url(const std::string& value) {
- response_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ response_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Method::set_response_type_url(std::string&& value) {
- response_type_url_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ response_type_url_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.response_type_url)
}
inline void Method::set_response_type_url(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- response_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ response_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.response_type_url)
}
-inline void Method::set_response_type_url(const char* value, size_t size) {
+inline void Method::set_response_type_url(const char* value,
+ size_t size) {
- response_type_url_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ response_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.response_type_url)
}
inline std::string* Method::_internal_mutable_response_type_url() {
- return response_type_url_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return response_type_url_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Method::release_response_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Method.response_type_url)
-
- return response_type_url_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return response_type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Method::set_allocated_response_type_url(std::string* response_type_url) {
if (response_type_url != nullptr) {
@@ -1211,9 +1412,29 @@
} else {
}
- response_type_url_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), response_type_url);
+ response_type_url_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), response_type_url,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.response_type_url)
}
+inline std::string* Method::unsafe_arena_release_response_type_url() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Method.response_type_url)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return response_type_url_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Method::unsafe_arena_set_allocated_response_type_url(
+ std::string* response_type_url) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (response_type_url != nullptr) {
+
+ } else {
+
+ }
+ response_type_url_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ response_type_url, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Method.response_type_url)
+}
// bool response_streaming = 5;
inline void Method::clear_response_streaming() {
@@ -1297,7 +1518,7 @@
// string name = 1;
inline void Mixin::clear_name() {
- name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Mixin::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Mixin.name)
@@ -1312,38 +1533,39 @@
return _internal_mutable_name();
}
inline const std::string& Mixin::_internal_name() const {
- return name_.GetNoArena();
+ return name_.Get();
}
inline void Mixin::_internal_set_name(const std::string& value) {
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Mixin::set_name(std::string&& value) {
- name_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ name_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.name)
}
inline void Mixin::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.name)
}
-inline void Mixin::set_name(const char* value, size_t size) {
+inline void Mixin::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.name)
}
inline std::string* Mixin::_internal_mutable_name() {
- return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Mixin::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Mixin.name)
-
- return name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Mixin::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -1351,13 +1573,33 @@
} else {
}
- name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.name)
}
+inline std::string* Mixin::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Mixin.name)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Mixin::unsafe_arena_set_allocated_name(
+ std::string* name) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (name != nullptr) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ name, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Mixin.name)
+}
// string root = 2;
inline void Mixin::clear_root() {
- root_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ root_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Mixin::root() const {
// @@protoc_insertion_point(field_get:google.protobuf.Mixin.root)
@@ -1372,38 +1614,39 @@
return _internal_mutable_root();
}
inline const std::string& Mixin::_internal_root() const {
- return root_.GetNoArena();
+ return root_.Get();
}
inline void Mixin::_internal_set_root(const std::string& value) {
- root_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ root_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Mixin::set_root(std::string&& value) {
- root_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ root_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.root)
}
inline void Mixin::set_root(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- root_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ root_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.root)
}
-inline void Mixin::set_root(const char* value, size_t size) {
+inline void Mixin::set_root(const char* value,
+ size_t size) {
- root_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ root_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.root)
}
inline std::string* Mixin::_internal_mutable_root() {
- return root_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return root_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Mixin::release_root() {
// @@protoc_insertion_point(field_release:google.protobuf.Mixin.root)
-
- return root_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return root_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Mixin::set_allocated_root(std::string* root) {
if (root != nullptr) {
@@ -1411,9 +1654,29 @@
} else {
}
- root_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), root);
+ root_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), root,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root)
}
+inline std::string* Mixin::unsafe_arena_release_root() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Mixin.root)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return root_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Mixin::unsafe_arena_set_allocated_root(
+ std::string* root) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (root != nullptr) {
+
+ } else {
+
+ }
+ root_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ root, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Mixin.root)
+}
#ifdef __GNUC__
#pragma GCC diagnostic pop
diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc
index 069dcdf..7362b62 100644
--- a/src/google/protobuf/arena.cc
+++ b/src/google/protobuf/arena.cc
@@ -59,11 +59,12 @@
}
#elif defined(PROTOBUF_USE_DLLS)
ArenaImpl::ThreadCache& ArenaImpl::thread_cache() {
- static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_ = {-1, NULL};
+ static PROTOBUF_THREAD_LOCAL ThreadCache thread_cache_ = {-1, NULL};
return thread_cache_;
}
#else
-GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL};
+PROTOBUF_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1,
+ NULL};
#endif
void ArenaImpl::Init() {
diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h
index d73b53c..038553c 100644
--- a/src/google/protobuf/arena.h
+++ b/src/google/protobuf/arena.h
@@ -219,14 +219,15 @@
// any special requirements on the type T, and will invoke the object's
// destructor when the arena is destroyed.
//
-// The arena message allocation protocol, required by CreateMessage<T>, is as
-// follows:
+// The arena message allocation protocol, required by
+// CreateMessage<T>(Arena* arena, Args&&... args), is as follows:
//
-// - The type T must have (at least) two constructors: a constructor with no
-// arguments, called when a T is allocated on the heap; and a constructor with
-// a Arena* argument, called when a T is allocated on an arena. If the
-// second constructor is called with a NULL arena pointer, it must be
-// equivalent to invoking the first (no-argument) constructor.
+// - The type T must have (at least) two constructors: a constructor callable
+// with `args` (without `arena`), called when a T is allocated on the heap;
+// and a constructor callable with `Arena* arena, Args&&... args`, called when
+// a T is allocated on an arena. If the second constructor is called with a
+// NULL arena pointer, it must be equivalent to invoking the first
+// (`args`-only) constructor.
//
// - The type T must have a particular type trait: a nested type
// |InternalArenaConstructable_|. This is usually a typedef to |void|. If no
@@ -239,16 +240,11 @@
// present on the type, then its destructor is always called when the
// containing arena is destroyed.
//
-// - One- and two-user-argument forms of CreateMessage<T>() also exist that
-// forward these constructor arguments to T's constructor: for example,
-// CreateMessage<T>(Arena*, arg1, arg2) forwards to a constructor T(Arena*,
-// arg1, arg2).
-//
// This protocol is implemented by all arena-enabled proto2 message classes as
// well as protobuf container types like RepeatedPtrField and Map. The protocol
// is internal to protobuf and is not guaranteed to be stable. Non-proto types
// should not rely on this protocol.
-class PROTOBUF_EXPORT alignas(8) Arena final {
+class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final {
public:
// Arena constructor taking custom options. See ArenaOptions below for
// descriptions of the options available.
@@ -453,7 +449,7 @@
return new (ptr) T(std::forward<Args>(args)...);
}
- static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); }
+ static Arena* GetArena(const T* p) { return p->GetArena(); }
friend class Arena;
};
@@ -532,6 +528,7 @@
// the cookie is not null.
template <typename T>
PROTOBUF_ALWAYS_INLINE void* AllocateInternal(bool skip_explicit_ownership) {
+ static_assert(alignof(T) <= 8, "T is overaligned, see b/151247138");
const size_t n = internal::AlignUpTo8(sizeof(T));
AllocHook(RTTI_TYPE_ID(T), n);
// Monitor allocation if needed.
@@ -616,24 +613,25 @@
// CreateInArenaStorage is used to implement map field. Without it,
// Map need to call generated message's protected arena constructor,
// which needs to declare Map as friend of generated message.
- template <typename T>
- static void CreateInArenaStorage(T* ptr, Arena* arena) {
+ template <typename T, typename... Args>
+ static void CreateInArenaStorage(T* ptr, Arena* arena, Args&&... args) {
CreateInArenaStorageInternal(ptr, arena,
- typename is_arena_constructable<T>::type());
+ typename is_arena_constructable<T>::type(),
+ std::forward<Args>(args)...);
RegisterDestructorInternal(
ptr, arena,
typename InternalHelper<T>::is_destructor_skippable::type());
}
- template <typename T>
+ template <typename T, typename... Args>
static void CreateInArenaStorageInternal(T* ptr, Arena* arena,
- std::true_type) {
- InternalHelper<T>::Construct(ptr, arena);
+ std::true_type, Args&&... args) {
+ InternalHelper<T>::Construct(ptr, arena, std::forward<Args>(args)...);
}
- template <typename T>
+ template <typename T, typename... Args>
static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */,
- std::false_type) {
- new (ptr) T();
+ std::false_type, Args&&... args) {
+ new (ptr) T(std::forward<Args>(args)...);
}
template <typename T>
@@ -665,7 +663,7 @@
// Implementation for GetArena(). Only message objects with
// InternalArenaConstructable_ tags can be associated with an arena, and such
- // objects must implement a GetArenaNoVirtual() method.
+ // objects must implement a GetArena() method.
template <typename T, typename std::enable_if<
is_arena_constructable<T>::value, int>::type = 0>
PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) {
@@ -692,6 +690,17 @@
AllocHook(NULL, n);
return AllocateAlignedNoHook(internal::AlignUpTo8(n));
}
+ template<size_t Align>
+ void* AllocateAlignedTo(size_t n) {
+ static_assert(Align > 0, "Alignment must be greater than 0");
+ static_assert((Align & (Align - 1)) == 0, "Alignment must be power of two");
+ if (Align <= 8) return AllocateAligned(n);
+ // TODO(b/151247138): if the pointer would have been aligned already,
+ // this is wasting space. We should pass the alignment down.
+ uintptr_t ptr = reinterpret_cast<uintptr_t>(AllocateAligned(n + Align - 8));
+ ptr = (ptr + Align - 1) & -Align;
+ return reinterpret_cast<void*>(ptr);
+ }
void* AllocateAlignedNoHook(size_t n);
diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h
index d7b7ed7..c9b4c54 100644
--- a/src/google/protobuf/arena_impl.h
+++ b/src/google/protobuf/arena_impl.h
@@ -135,6 +135,8 @@
void AddCleanup(void* elem, void (*cleanup)(void*));
private:
+ friend class ArenaBenchmark;
+
void* AllocateAlignedFallback(size_t n);
void* AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*));
void AddCleanupFallback(void* elem, void (*cleanup)(void*));
@@ -286,16 +288,16 @@
};
static std::atomic<LifecycleId> lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
- // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread
+ // Android ndk does not support __thread keyword so we use a custom thread
// local storage class we implemented.
- // iOS also does not support the GOOGLE_THREAD_LOCAL keyword.
+ // iOS also does not support the __thread keyword.
static ThreadCache& thread_cache();
#elif defined(PROTOBUF_USE_DLLS)
// Thread local variables cannot be exposed through DLL interface but we can
// wrap them in static functions.
static ThreadCache& thread_cache();
#else
- static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_;
+ static PROTOBUF_THREAD_LOCAL ThreadCache thread_cache_;
static ThreadCache& thread_cache() { return thread_cache_; }
#endif
diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc
index 7e5b115..dd73d79 100644
--- a/src/google/protobuf/arena_unittest.cc
+++ b/src/google/protobuf/arena_unittest.cc
@@ -58,6 +58,9 @@
#include <google/protobuf/stubs/strutil.h>
+// Must be included last
+#include <google/protobuf/port_def.inc>
+
using proto2_arena_unittest::ArenaMessage;
using protobuf_unittest::TestAllExtensions;
using protobuf_unittest::TestAllTypes;
diff --git a/src/google/protobuf/compiler/annotation_test_util.h b/src/google/protobuf/compiler/annotation_test_util.h
index 7c13191..fa87c6c 100644
--- a/src/google/protobuf/compiler/annotation_test_util.h
+++ b/src/google/protobuf/compiler/annotation_test_util.h
@@ -60,7 +60,7 @@
// directory.
void AddFile(const std::string& filename, const std::string& data);
-// Runs proto compiler. Captures proto file structrue in FileDescriptorProto.
+// Runs proto compiler. Captures proto file structure in FileDescriptorProto.
// Files will be generated in TestTempDir() folder. Callers of this
// function must read generated files themselves.
//
diff --git a/src/google/protobuf/compiler/code_generator.cc b/src/google/protobuf/compiler/code_generator.cc
index 428ec46..693300d 100644
--- a/src/google/protobuf/compiler/code_generator.cc
+++ b/src/google/protobuf/compiler/code_generator.cc
@@ -50,7 +50,7 @@
const std::string& parameter,
GeneratorContext* generator_context,
std::string* error) const {
- // Default implemenation is just to call the per file method, and prefix any
+ // Default implementation 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++) {
diff --git a/src/google/protobuf/compiler/code_generator.h b/src/google/protobuf/compiler/code_generator.h
index 528dc76..1bc8dfc 100644
--- a/src/google/protobuf/compiler/code_generator.h
+++ b/src/google/protobuf/compiler/code_generator.h
@@ -102,6 +102,16 @@
GeneratorContext* generator_context,
std::string* error) const;
+ // Sync with plugin.proto.
+ enum Feature {
+ FEATURE_PROTO3_OPTIONAL = 1,
+ };
+
+ // Implement this to indicate what features this code generator supports.
+ // This should be a bitwise OR of features from the Features enum in
+ // plugin.proto.
+ virtual uint64 GetSupportedFeatures() const { return 0; }
+
// 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
diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc
index 2de5659..b55070f 100644
--- a/src/google/protobuf/compiler/command_line_interface.cc
+++ b/src/google/protobuf/compiler/command_line_interface.cc
@@ -773,16 +773,9 @@
#endif
CommandLineInterface::CommandLineInterface()
- : mode_(MODE_COMPILE),
- print_mode_(PRINT_NONE),
- error_format_(ERROR_FORMAT_GCC),
- direct_dependencies_explicitly_set_(false),
- direct_dependencies_violation_msg_(
- kDefaultDirectDependenciesViolationMsg),
- imports_in_descriptor_set_(false),
- source_info_in_descriptor_set_(false),
- disallow_services_(false) {
-}
+ : direct_dependencies_violation_msg_(
+ kDefaultDirectDependenciesViolationMsg) {}
+
CommandLineInterface::~CommandLineInterface() {}
void CommandLineInterface::RegisterGenerator(const std::string& flag_name,
@@ -811,6 +804,39 @@
plugin_prefix_ = exe_name_prefix;
}
+namespace {
+
+bool ContainsProto3Optional(const Descriptor* desc) {
+ for (int i = 0; i < desc->field_count(); i++) {
+ if (desc->field(i)->has_optional_keyword()) {
+ return true;
+ }
+ }
+ for (int i = 0; i < desc->nested_type_count(); i++) {
+ if (ContainsProto3Optional(desc->nested_type(i))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ContainsProto3Optional(const FileDescriptor* file) {
+ if (file->syntax() == FileDescriptor::SYNTAX_PROTO3) {
+ for (int i = 0; i < file->message_type_count(); i++) {
+ if (ContainsProto3Optional(file->message_type(i))) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+} // namespace
+
+namespace {
+std::unique_ptr<SimpleDescriptorDatabase>
+PopulateSingleSimpleDescriptorDatabase(const std::string& descriptor_set_name);
+}
int CommandLineInterface::Run(int argc, const char* const argv[]) {
Clear();
@@ -827,16 +853,38 @@
std::unique_ptr<DiskSourceTree> disk_source_tree;
std::unique_ptr<ErrorPrinter> error_collector;
std::unique_ptr<DescriptorPool> descriptor_pool;
- std::unique_ptr<SimpleDescriptorDatabase> descriptor_set_in_database;
+
+ // The SimpleDescriptorDatabases here are the constituents of the
+ // MergedDescriptorDatabase descriptor_set_in_database, so this vector is for
+ // managing their lifetimes. Its scope should match descriptor_set_in_database
+ std::vector<std::unique_ptr<SimpleDescriptorDatabase>>
+ databases_per_descriptor_set;
+ std::unique_ptr<MergedDescriptorDatabase> descriptor_set_in_database;
+
std::unique_ptr<SourceTreeDescriptorDatabase> source_tree_database;
// Any --descriptor_set_in FileDescriptorSet objects will be used as a
// fallback to input_files on command line, so create that db first.
if (!descriptor_set_in_names_.empty()) {
- descriptor_set_in_database.reset(new SimpleDescriptorDatabase());
- if (!PopulateSimpleDescriptorDatabase(descriptor_set_in_database.get())) {
- return 1;
+ for (const std::string& name : descriptor_set_in_names_) {
+ std::unique_ptr<SimpleDescriptorDatabase> database_for_descriptor_set =
+ PopulateSingleSimpleDescriptorDatabase(name);
+ if (!database_for_descriptor_set) {
+ return EXIT_FAILURE;
+ }
+ databases_per_descriptor_set.push_back(
+ std::move(database_for_descriptor_set));
}
+
+ std::vector<DescriptorDatabase*> raw_databases_per_descriptor_set;
+ raw_databases_per_descriptor_set.reserve(
+ databases_per_descriptor_set.size());
+ for (const std::unique_ptr<SimpleDescriptorDatabase>& db :
+ databases_per_descriptor_set) {
+ raw_databases_per_descriptor_set.push_back(db.get());
+ }
+ descriptor_set_in_database.reset(
+ new MergedDescriptorDatabase(raw_databases_per_descriptor_set));
}
if (proto_path_.empty()) {
@@ -876,6 +924,16 @@
}
+ for (auto fd : parsed_files) {
+ if (!AllowProto3Optional(*fd) && ContainsProto3Optional(fd)) {
+ std::cerr << fd->name()
+ << ": This file contains proto3 optional fields, but "
+ "--experimental_allow_proto3_optional was not set."
+ << std::endl;
+ return 1;
+ }
+ }
+
// We construct a separate GeneratorContext for each output location. Note
// that two code generators may output to the same location, in which case
// they should share a single GeneratorContext so that OpenForInsert() works.
@@ -886,7 +944,8 @@
for (int i = 0; i < output_directives_.size(); i++) {
std::string output_location = output_directives_[i].output_location;
if (!HasSuffixString(output_location, ".zip") &&
- !HasSuffixString(output_location, ".jar")) {
+ !HasSuffixString(output_location, ".jar") &&
+ !HasSuffixString(output_location, ".srcjar")) {
AddTrailingSlash(&output_location);
}
@@ -999,46 +1058,66 @@
return true;
}
-bool CommandLineInterface::PopulateSimpleDescriptorDatabase(
- SimpleDescriptorDatabase* database) {
- for (int i = 0; i < descriptor_set_in_names_.size(); i++) {
- int fd;
- do {
- fd = open(descriptor_set_in_names_[i].c_str(), O_RDONLY | O_BINARY);
- } while (fd < 0 && errno == EINTR);
- if (fd < 0) {
- std::cerr << descriptor_set_in_names_[i] << ": " << strerror(ENOENT)
- << std::endl;
- return false;
- }
+namespace {
+std::unique_ptr<SimpleDescriptorDatabase>
+PopulateSingleSimpleDescriptorDatabase(const std::string& descriptor_set_name) {
+ int fd;
+ do {
+ fd = open(descriptor_set_name.c_str(), O_RDONLY | O_BINARY);
+ } while (fd < 0 && errno == EINTR);
+ if (fd < 0) {
+ std::cerr << descriptor_set_name << ": " << strerror(ENOENT) << std::endl;
+ return nullptr;
+ }
- FileDescriptorSet file_descriptor_set;
- bool parsed = file_descriptor_set.ParseFromFileDescriptor(fd);
- if (close(fd) != 0) {
- std::cerr << descriptor_set_in_names_[i] << ": close: " << strerror(errno)
- << std::endl;
- return false;
- }
+ FileDescriptorSet file_descriptor_set;
+ bool parsed = file_descriptor_set.ParseFromFileDescriptor(fd);
+ if (close(fd) != 0) {
+ std::cerr << descriptor_set_name << ": close: " << strerror(errno)
+ << std::endl;
+ return nullptr;
+ }
- if (!parsed) {
- std::cerr << descriptor_set_in_names_[i] << ": Unable to parse."
- << std::endl;
- return false;
- }
+ if (!parsed) {
+ std::cerr << descriptor_set_name << ": Unable to parse." << std::endl;
+ return nullptr;
+ }
- for (int j = 0; j < file_descriptor_set.file_size(); j++) {
- FileDescriptorProto previously_added_file_descriptor_proto;
- if (database->FindFileByName(file_descriptor_set.file(j).name(),
- &previously_added_file_descriptor_proto)) {
- // already present - skip
- continue;
- }
- if (!database->Add(file_descriptor_set.file(j))) {
- return false;
- }
+ std::unique_ptr<SimpleDescriptorDatabase> database{
+ new SimpleDescriptorDatabase()};
+
+ for (int j = 0; j < file_descriptor_set.file_size(); j++) {
+ FileDescriptorProto previously_added_file_descriptor_proto;
+ if (database->FindFileByName(file_descriptor_set.file(j).name(),
+ &previously_added_file_descriptor_proto)) {
+ // already present - skip
+ continue;
+ }
+ if (!database->Add(file_descriptor_set.file(j))) {
+ return nullptr;
}
}
- return true;
+ return database;
+}
+
+} // namespace
+
+bool CommandLineInterface::AllowProto3Optional(
+ const FileDescriptor& file) const {
+ if (allow_proto3_optional_) return true;
+
+ // Whitelist all ads protos. Ads is an early adopter of this feature.
+ if (file.name().find("google/ads/googleads") != std::string::npos) {
+ return true;
+ }
+
+ // Whitelist all protos testing proto3 optional.
+ if (file.name().find("test_proto3_optional") != std::string::npos) {
+ return true;
+ }
+
+
+ return false;
}
bool CommandLineInterface::VerifyInputFilesInDescriptors(
@@ -1067,10 +1146,26 @@
DescriptorPool* descriptor_pool, DiskSourceTree* source_tree,
std::vector<const FileDescriptor*>* parsed_files) {
- // Track unused imports in all source files
- for (const auto& input_file : input_files_) {
- descriptor_pool->AddUnusedImportTrackFile(input_file);
+ if (!proto_path_.empty()) {
+ // Track unused imports in all source files that were loaded from the
+ // filesystem. We do not track unused imports for files loaded from
+ // descriptor sets as they may be programmatically generated in which case
+ // exerting this level of rigor is less desirable. We're also making the
+ // assumption that the initial parse of the proto from the filesystem
+ // was rigorous in checking unused imports and that the descriptor set
+ // being parsed was produced then and that it was subsequent mutations
+ // of that descriptor set that left unused imports.
+ //
+ // Note that relying on proto_path exclusively is limited in that we may
+ // be loading descriptors from both the filesystem and descriptor sets
+ // depending on the invocation. At least for invocations that are
+ // exclusively reading from descriptor sets, we can eliminate this failure
+ // condition.
+ for (const auto& input_file : input_files_) {
+ descriptor_pool->AddUnusedImportTrackFile(input_file);
+ }
}
+
bool result = true;
// Parse each file.
for (const auto& input_file : input_files_) {
@@ -1138,6 +1233,7 @@
source_info_in_descriptor_set_ = false;
disallow_services_ = false;
direct_dependencies_explicitly_set_ = false;
+ allow_proto3_optional_ = false;
}
bool CommandLineInterface::MakeProtoProtoPathRelative(
@@ -1413,7 +1509,8 @@
if (*name == "-h" || *name == "--help" || *name == "--disallow_services" ||
*name == "--include_imports" || *name == "--include_source_info" ||
*name == "--version" || *name == "--decode_raw" ||
- *name == "--print_free_field_numbers") {
+ *name == "--print_free_field_numbers" ||
+ *name == "--experimental_allow_proto3_optional") {
// HACK: These are the only flags that don't take a value.
// They probably should not be hard-coded like this but for now it's
// not worth doing better.
@@ -1620,6 +1717,9 @@
} else if (name == "--disallow_services") {
disallow_services_ = true;
+ } else if (name == "--experimental_allow_proto3_optional") {
+ allow_proto3_optional_ = true;
+
} else if (name == "--encode" || name == "--decode" ||
name == "--decode_raw") {
if (mode_ != MODE_COMPILE) {
@@ -1920,6 +2020,28 @@
<< std::endl;
}
+bool CommandLineInterface::EnforceProto3OptionalSupport(
+ const std::string& codegen_name, uint64 supported_features,
+ const std::vector<const FileDescriptor*>& parsed_files) const {
+ bool supports_proto3_optional =
+ supported_features & CodeGenerator::FEATURE_PROTO3_OPTIONAL;
+ if (!supports_proto3_optional) {
+ for (const auto fd : parsed_files) {
+ if (ContainsProto3Optional(fd)) {
+ std::cerr << fd->name()
+ << ": is a proto3 file that contains optional fields, but "
+ "code generator "
+ << codegen_name
+ << " hasn't been updated to support optional fields in "
+ "proto3. Please ask the owner of this code generator to "
+ "support proto3 optional.";
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
bool CommandLineInterface::GenerateOutput(
const std::vector<const FileDescriptor*>& parsed_files,
const OutputDirective& output_directive,
@@ -1954,6 +2076,12 @@
}
parameters.append(generator_parameters_[output_directive.name]);
}
+ if (!EnforceProto3OptionalSupport(
+ output_directive.name,
+ output_directive.generator->GetSupportedFeatures(), parsed_files)) {
+ return false;
+ }
+
if (!output_directive.generator->GenerateAll(parsed_files, parameters,
generator_context, &error)) {
// Generator returned an error.
@@ -2118,6 +2246,9 @@
// Generator returned an error.
*error = response.error();
return false;
+ } else if (!EnforceProto3OptionalSupport(
+ plugin_name, response.supported_features(), parsed_files)) {
+ return false;
}
return true;
@@ -2228,12 +2359,20 @@
}
io::FileOutputStream out(fd);
- if (!file_set.SerializeToZeroCopyStream(&out)) {
- std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno())
- << std::endl;
- out.Close();
- return false;
+
+ {
+ io::CodedOutputStream coded_out(&out);
+ // Determinism is useful here because build outputs are sometimes checked
+ // into version control.
+ coded_out.SetSerializationDeterministic(true);
+ if (!file_set.SerializeToCodedStream(&coded_out)) {
+ std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno())
+ << std::endl;
+ out.Close();
+ return false;
+ }
}
+
if (!out.Close()) {
std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno())
<< std::endl;
@@ -2280,7 +2419,7 @@
// Nested Messages:
// Note that it only stores the nested message type, iff the nested type is
// either a direct child of the given descriptor, or the nested type is a
-// decendent of the given descriptor and all the nodes between the
+// descendant of the given descriptor and all the nodes between the
// nested type and the given descriptor are group types. e.g.
//
// message Foo {
diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h
index 9449fa3..3c95cd6 100644
--- a/src/google/protobuf/compiler/command_line_interface.h
+++ b/src/google/protobuf/compiler/command_line_interface.h
@@ -97,7 +97,7 @@
// protoc --cpp_out=outdir --foo_out=outdir --proto_path=src src/foo.proto
//
// The .proto file to compile can be specified on the command line using either
-// its physical file path, or a virtual path relative to a diretory specified
+// its physical file path, or a virtual path relative to a directory specified
// in --proto_path. For example, for src/foo.proto, the following two protoc
// invocations work the same way:
// 1. protoc --proto_path=src src/foo.proto (physical file path)
@@ -194,7 +194,7 @@
// DEPRECATED. Calling this method has no effect. Protocol compiler now
// always try to find the .proto file relative to the current directory
// first and if the file is not found, it will then treat the input path
- // as a virutal path.
+ // as a virtual path.
void SetInputsAreProtoPathRelative(bool /* enable */) {}
// Provides some text which will be printed when the --version flag is
@@ -226,6 +226,17 @@
bool MakeInputsBeProtoPathRelative(DiskSourceTree* source_tree,
DescriptorDatabase* fallback_database);
+ // Is this .proto file whitelisted, or do we have a command-line flag allowing
+ // us to use proto3 optional? This is a temporary control to avoid people from
+ // using proto3 optional until code generators have implemented it.
+ bool AllowProto3Optional(const FileDescriptor& file) const;
+
+ // Fails if these files use proto3 optional and the code generator doesn't
+ // support it. This is a permanent check.
+ bool EnforceProto3OptionalSupport(
+ const std::string& codegen_name, uint64 supported_features,
+ const std::vector<const FileDescriptor*>& parsed_files) const;
+
// Return status for ParseArguments() and InterpretArgument().
enum ParseArgumentStatus {
@@ -269,9 +280,6 @@
// Verify that all the input files exist in the given database.
bool VerifyInputFilesInDescriptors(DescriptorDatabase* fallback_database);
- // Loads descriptor_set_in into the provided database
- bool PopulateSimpleDescriptorDatabase(SimpleDescriptorDatabase* database);
-
// Parses input_files_ into parsed_files
bool ParseInputFiles(DescriptorPool* descriptor_pool,
DiskSourceTree* source_tree,
@@ -373,21 +381,21 @@
MODE_PRINT, // Print mode: print info of the given .proto files and exit.
};
- Mode mode_;
+ Mode mode_ = MODE_COMPILE;
enum PrintMode {
PRINT_NONE, // Not in MODE_PRINT
PRINT_FREE_FIELDS, // --print_free_fields
};
- PrintMode print_mode_;
+ PrintMode print_mode_ = PRINT_NONE;
enum ErrorFormat {
ERROR_FORMAT_GCC, // GCC error output format (default).
ERROR_FORMAT_MSVS // Visual Studio output (--error_format=msvs).
};
- ErrorFormat error_format_;
+ ErrorFormat error_format_ = ERROR_FORMAT_GCC;
std::vector<std::pair<std::string, std::string> >
proto_path_; // Search path for proto files.
@@ -396,7 +404,7 @@
// Names of proto files which are allowed to be imported. Used by build
// systems to enforce depend-on-what-you-import.
std::set<std::string> direct_dependencies_;
- bool direct_dependencies_explicitly_set_;
+ bool direct_dependencies_explicitly_set_ = false;
// If there's a violation of depend-on-what-you-import, this string will be
// presented to the user. "%s" will be replaced with the violating import.
@@ -435,10 +443,13 @@
// True if --include_source_info was given, meaning that we should not strip
// SourceCodeInfo from the DescriptorSet.
- bool source_info_in_descriptor_set_;
+ bool source_info_in_descriptor_set_ = false;
// Was the --disallow_services flag used?
- bool disallow_services_;
+ bool disallow_services_ = false;
+
+ // Was the --experimental_allow_proto3_optional flag used?
+ bool allow_proto3_optional_ = false;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CommandLineInterface);
};
diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc
index e4fd54e..a51ad92 100644
--- a/src/google/protobuf/compiler/command_line_interface_unittest.cc
+++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc
@@ -205,6 +205,17 @@
void ExpectFileContent(const std::string& filename,
const std::string& content);
+ // The default code generators support all features. Use this to create a
+ // code generator that omits the given feature(s).
+ void CreateGeneratorWithMissingFeatures(const std::string& name,
+ const std::string& description,
+ uint64 features) {
+ MockCodeGenerator* generator = new MockCodeGenerator(name);
+ generator->SuppressFeatures(features);
+ mock_generators_to_delete_.push_back(generator);
+ cli_.RegisterGenerator(name, generator, description);
+ }
+
private:
// The object we are testing.
CommandLineInterface cli_;
@@ -914,6 +925,58 @@
}
TEST_F(CommandLineInterfaceTest,
+ InputsOnlyFromDescriptorSetIn_UnusedImportIsNotReported) {
+ FileDescriptorSet file_descriptor_set;
+
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("unused.proto");
+ file_descriptor_proto->add_message_type()->set_name("Unused");
+
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("bar.proto");
+ file_descriptor_proto->add_dependency("unused.proto");
+ file_descriptor_proto->add_message_type()->set_name("Bar");
+
+ WriteDescriptorSet("unused_and_bar.bin", &file_descriptor_set);
+
+ Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/unused_and_bar.bin unused.proto bar.proto");
+ ExpectNoErrors();
+}
+
+TEST_F(CommandLineInterfaceTest,
+ InputsFromDescriptorSetInAndFileSystem_UnusedImportIsReported) {
+ FileDescriptorSet file_descriptor_set;
+
+ FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("unused.proto");
+ file_descriptor_proto->add_message_type()->set_name("Unused");
+
+ file_descriptor_proto = file_descriptor_set.add_file();
+ file_descriptor_proto->set_name("bar.proto");
+ file_descriptor_proto->add_dependency("unused.proto");
+ file_descriptor_proto->add_message_type()->set_name("Bar");
+
+ WriteDescriptorSet("unused_and_bar.bin", &file_descriptor_set);
+
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "import \"bar.proto\";\n"
+ "message Foo {\n"
+ " optional Bar bar = 1;\n"
+ "}\n");
+
+ Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
+ "--descriptor_set_in=$tmpdir/unused_and_bar.bin "
+ "--proto_path=$tmpdir unused.proto bar.proto foo.proto");
+ // Reporting unused imports here is unfair, since it's unactionable. Notice
+ // the lack of a line number.
+ // TODO(b/144853061): If the file with unused import is from the descriptor
+ // set and not from the file system, suppress the warning.
+ ExpectWarningSubstring("bar.proto: warning: Import unused.proto is unused.");
+}
+
+TEST_F(CommandLineInterfaceTest,
OnlyReportsUnusedImportsForFilesBeingGenerated) {
CreateTempFile("unused.proto",
"syntax = \"proto2\";\n"
@@ -975,7 +1038,6 @@
ExpectWarningSubstring(
"bar.proto:2:1: warning: Import unused.proto is unused.");
}
-
TEST_F(CommandLineInterfaceTest, CreateDirectory) {
// Test that when we output to a sub-directory, it is created.
@@ -1074,7 +1136,7 @@
}
TEST_F(CommandLineInterfaceTest, ExtraPluginParametersForOutParameters) {
- // This doesn't rely on the plugin having been registred and instead that
+ // This doesn't rely on the plugin having been registered and instead that
// the existence of --[name]_out is enough to make the --[name]_opt valid.
// However, running out of process plugins found via the search path (i.e. -
// not pre registered with --plugin) isn't support in this test suite, so we
@@ -2310,6 +2372,78 @@
ExpectErrorText("Missing value for flag: --test_out\n");
}
+TEST_F(CommandLineInterfaceTest, Proto3OptionalDisallowed) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto3\";\n"
+ "message Foo {\n"
+ " optional int32 i = 1;\n"
+ "}\n");
+
+ Run("protocol_compiler --proto_path=$tmpdir foo.proto -odescriptor.pb");
+
+ ExpectErrorSubstring("--experimental_allow_proto3_optional was not set");
+}
+
+TEST_F(CommandLineInterfaceTest, Proto3OptionalDisallowedDescriptor) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto3\";\n"
+ "message Foo {\n"
+ " optional int32 i = 1;\n"
+ "}\n");
+
+ Run("protocol_compiler --experimental_allow_proto3_optional "
+ "--proto_path=$tmpdir foo.proto "
+ " -o$tmpdir/descriptor.pb");
+ ExpectNoErrors();
+
+ Run("protocol_compiler --descriptor_set_in=$tmpdir/descriptor.pb foo.proto "
+ "--test_out=$tmpdir");
+ ExpectErrorSubstring("--experimental_allow_proto3_optional was not set");
+}
+
+TEST_F(CommandLineInterfaceTest, Proto3OptionalDisallowedGenCode) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto3\";\n"
+ "message Foo {\n"
+ " optional int32 i = 1;\n"
+ "}\n");
+
+ Run("protocol_compiler --proto_path=$tmpdir foo.proto --test_out=$tmpdir");
+
+ ExpectErrorSubstring("--experimental_allow_proto3_optional was not set");
+}
+
+TEST_F(CommandLineInterfaceTest, Proto3OptionalDisallowedNoCodegenSupport) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto3\";\n"
+ "message Foo {\n"
+ " optional int32 i = 1;\n"
+ "}\n");
+
+ CreateGeneratorWithMissingFeatures("--no_proto3_optional_out",
+ "Doesn't support proto3 optional",
+ CodeGenerator::FEATURE_PROTO3_OPTIONAL);
+
+ Run("protocol_compiler --experimental_allow_proto3_optional "
+ "--proto_path=$tmpdir foo.proto --no_proto3_optional_out=$tmpdir");
+
+ ExpectErrorSubstring(
+ "code generator --no_proto3_optional_out hasn't been updated to support "
+ "optional fields in proto3");
+}
+
+TEST_F(CommandLineInterfaceTest, Proto3OptionalAllowWithFlag) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto3\";\n"
+ "message Foo {\n"
+ " optional int32 i = 1;\n"
+ "}\n");
+
+ Run("protocol_compiler --experimental_allow_proto3_optional "
+ "--proto_path=$tmpdir foo.proto --test_out=$tmpdir");
+ ExpectNoErrors();
+}
+
TEST_F(CommandLineInterfaceTest, PrintFreeFieldNumbers) {
CreateTempFile("foo.proto",
"syntax = \"proto2\";\n"
diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
old mode 100755
new mode 100644
index dbef855..31fe5a6
--- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
@@ -76,8 +76,8 @@
// implements ErrorCollector ---------------------------------------
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
- strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line,
- column, message);
+ strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line, column,
+ message);
}
};
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc
index 8a661ea..06da3f3 100644
--- a/src/google/protobuf/compiler/cpp/cpp_extension.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc
@@ -94,7 +94,7 @@
variables_["constant_name"] = FieldConstantName(descriptor_);
variables_["field_type"] =
StrCat(static_cast<int>(descriptor_->type()));
- variables_["packed"] = descriptor_->options().packed() ? "true" : "false";
+ variables_["packed"] = descriptor_->is_packed() ? "true" : "false";
std::string scope =
IsScoped() ? ClassName(descriptor_->extension_scope(), false) + "::" : "";
@@ -157,6 +157,11 @@
StringReplace(variables_["scoped_name"], "::", "_", true) + "_default";
format("const std::string $1$($2$);\n", default_str,
DefaultValue(options_, descriptor_));
+ } else if (descriptor_->message_type()) {
+ // We have to initialize the default instance for extensions at registration
+ // time.
+ default_str =
+ FieldMessageTypeName(descriptor_, options_) + "::default_instance()";
} else {
default_str = DefaultValue(options_, descriptor_);
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.cc b/src/google/protobuf/compiler/cpp/cpp_field.cc
index 5b2ca15..f95e14e 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_field.cc
@@ -73,7 +73,7 @@
(*variables)["set_hasbit"] = "";
(*variables)["clear_hasbit"] = "";
- if (HasFieldPresence(descriptor->file())) {
+ if (HasHasbit(descriptor)) {
(*variables)["set_hasbit_io"] =
"_Internal::set_has_" + FieldName(descriptor) + "(&_has_bits_);";
} else {
@@ -90,7 +90,8 @@
}
void FieldGenerator::SetHasBitIndex(int32 has_bit_index) {
- if (!HasFieldPresence(descriptor_->file()) || has_bit_index == -1) {
+ if (!HasHasbit(descriptor_)) {
+ GOOGLE_CHECK_EQ(has_bit_index, -1);
return;
}
variables_["set_hasbit"] = StrCat(
@@ -155,7 +156,7 @@
default:
return new RepeatedPrimitiveFieldGenerator(field, options);
}
- } else if (field->containing_oneof()) {
+ } else if (field->real_containing_oneof()) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
return new MessageOneofFieldGenerator(field, options, scc_analyzer);
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc
index 45fd308..e2961e5 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_file.cc
@@ -34,6 +34,7 @@
#include <google/protobuf/compiler/cpp/cpp_file.h>
+#include <iostream>
#include <map>
#include <memory>
#include <set>
@@ -411,11 +412,6 @@
IncludeFile("net/proto2/public/reflection_ops.h", printer);
IncludeFile("net/proto2/public/wire_format.h", printer);
}
- if (IsProto2MessageSetFile(file_, options_)) {
- format(
- // Implementation of proto1 MessageSet API methods.
- "#include \"net/proto2/internal/message_set_util.h\"\n");
- }
if (options_.proto_h) {
// Use the smaller .proto.h files.
@@ -898,18 +894,21 @@
format("};\n");
// The DescriptorTable itself.
+ // Should be "bool eager = NeedsEagerDescriptorAssignment(file_, options_);"
+ // however this might cause a tsan failure in superroot b/148382879,
+ // so disable for now.
+ bool eager = false;
format(
"static ::$proto_ns$::internal::once_flag $desc_table$_once;\n"
- "static bool $desc_table$_initialized = false;\n"
"const ::$proto_ns$::internal::DescriptorTable $desc_table$ = {\n"
- " &$desc_table$_initialized, $1$, \"$filename$\", $2$,\n"
- " &$desc_table$_once, $desc_table$_sccs, $desc_table$_deps, $3$, $4$,\n"
+ " false, $1$, $2$, \"$filename$\", $3$,\n"
+ " &$desc_table$_once, $desc_table$_sccs, $desc_table$_deps, $4$, $5$,\n"
" schemas, file_default_instances, $tablename$::offsets,\n"
- " $file_level_metadata$, $5$, $file_level_enum_descriptors$, "
+ " $file_level_metadata$, $6$, $file_level_enum_descriptors$, "
"$file_level_service_descriptors$,\n"
"};\n\n",
- protodef_name, file_data.size(), sccs_.size(), num_deps,
- message_generators_.size());
+ eager ? "true" : "false", protodef_name, file_data.size(), sccs_.size(),
+ num_deps, message_generators_.size());
// For descriptor.proto we want to avoid doing any dynamic initialization,
// because in some situations that would otherwise pull in a lot of
@@ -918,8 +917,8 @@
if (file_->name() != "net/proto2/proto/descriptor.proto") {
format(
"// Force running AddDescriptors() at dynamic initialization time.\n"
- "static bool $1$ = ("
- " ::$proto_ns$::internal::AddDescriptors(&$desc_table$), true);\n",
+ "static bool $1$ = (static_cast<void>("
+ "::$proto_ns$::internal::AddDescriptors(&$desc_table$)), true);\n",
UniqueName("dynamic_init_dummy", file_, options_));
}
}
@@ -1185,7 +1184,7 @@
FlattenMessagesInFile(file_, &classes); // All messages need forward decls.
if (options_.proto_h) { // proto.h needs extra forward declarations.
- // All classes / enums refered to as field members
+ // All classes / enums referred to as field members
std::vector<const FieldDescriptor*> fields;
ListAllFields(file_, &fields);
for (int i = 0; i < fields.size(); i++) {
@@ -1297,12 +1296,10 @@
IncludeFile("net/proto2/public/generated_message_table_driven.h", printer);
IncludeFile("net/proto2/public/generated_message_util.h", printer);
IncludeFile("net/proto2/public/inlined_string_field.h", printer);
+ IncludeFile("net/proto2/public/metadata_lite.h", printer);
if (HasDescriptorMethods(file_, options_)) {
- IncludeFile("net/proto2/public/metadata.h", printer);
IncludeFile("net/proto2/public/generated_message_reflection.h", printer);
- } else {
- IncludeFile("net/proto2/public/metadata_lite.h", printer);
}
if (!message_generators_.empty()) {
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.h b/src/google/protobuf/compiler/cpp/cpp_file.h
index e81af42..da5e1de 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.h
+++ b/src/google/protobuf/compiler/cpp/cpp_file.h
@@ -148,7 +148,7 @@
// Generates extension identifiers.
void GenerateExtensionIdentifiers(io::Printer* printer);
- // Generates inline function defintions.
+ // Generates inline function definitions.
void GenerateInlineFunctionDefinitions(io::Printer* printer);
void GenerateProto2NamespaceEnumSpecializations(io::Printer* printer);
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/cpp_generator.cc
index 0d80ea2..2c45ca8 100644
--- a/src/google/protobuf/compiler/cpp/cpp_generator.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_generator.cc
@@ -93,6 +93,8 @@
file_options.annotation_guard_name = options[i].second;
} else if (options[i].first == "speed") {
file_options.enforce_mode = EnforceOptimizeMode::kSpeed;
+ } else if (options[i].first == "code_size") {
+ file_options.enforce_mode = EnforceOptimizeMode::kCodeSize;
} else if (options[i].first == "lite") {
file_options.enforce_mode = EnforceOptimizeMode::kLiteRuntime;
} else if (options[i].first == "lite_implicit_weak_fields") {
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.h b/src/google/protobuf/compiler/cpp/cpp_generator.h
index c5ff28a..85a5aab 100644
--- a/src/google/protobuf/compiler/cpp/cpp_generator.h
+++ b/src/google/protobuf/compiler/cpp/cpp_generator.h
@@ -81,7 +81,14 @@
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file, const std::string& parameter,
- GeneratorContext* generator_context, std::string* error) const;
+ GeneratorContext* generator_context,
+ std::string* error) const override;
+
+ uint64 GetSupportedFeatures() const override {
+ // We don't fully support this yet, but this is needed to unblock the tests,
+ // and we will have full support before the experimental flag is removed.
+ return FEATURE_PROTO3_OPTIONAL;
+ }
private:
bool opensource_runtime_ = true;
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
index 062ad6b..976823a 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
@@ -43,10 +43,13 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/compiler/cpp/cpp_options.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/scc.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/stubs/strutil.h>
@@ -244,6 +247,31 @@
(*variables)["string"] = "std::string";
}
+void SetUnknkownFieldsVariable(const Descriptor* descriptor,
+ const Options& options,
+ std::map<std::string, std::string>* variables) {
+ std::string proto_ns = ProtobufNamespace(options);
+ std::string unknown_fields_type;
+ if (UseUnknownFieldSet(descriptor->file(), options)) {
+ unknown_fields_type = "::" + proto_ns + "::UnknownFieldSet";
+ (*variables)["unknown_fields"] =
+ "_internal_metadata_.unknown_fields<" + unknown_fields_type + ">(" +
+ unknown_fields_type + "::default_instance)";
+ } else {
+ unknown_fields_type =
+ PrimitiveTypeName(options, FieldDescriptor::CPPTYPE_STRING);
+ (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields<" +
+ unknown_fields_type + ">(::" + proto_ns +
+ "::internal::GetEmptyString)";
+ }
+ (*variables)["unknown_fields_type"] = unknown_fields_type;
+ (*variables)["have_unknown_fields"] =
+ "_internal_metadata_.have_unknown_fields()";
+ (*variables)["mutable_unknown_fields"] =
+ "_internal_metadata_.mutable_unknown_fields<" + unknown_fields_type +
+ ">()";
+}
+
std::string UnderscoresToCamelCase(const std::string& input,
bool cap_next_letter) {
std::string result;
@@ -334,6 +362,16 @@
return QualifiedClassName(d, Options());
}
+std::string QualifiedExtensionName(const FieldDescriptor* d,
+ const Options& options) {
+ GOOGLE_DCHECK(d->is_extension());
+ return QualifiedFileLevelSymbol(d->file(), FieldName(d), options);
+}
+
+std::string QualifiedExtensionName(const FieldDescriptor* d) {
+ return QualifiedExtensionName(d, Options());
+}
+
std::string Namespace(const std::string& package) {
if (package.empty()) return "";
return "::" + DotsToColons(package);
@@ -757,10 +795,10 @@
if (IsAnyMessage(descriptor->containing_type(), options)) return false;
if (descriptor->containing_type()->options().map_entry()) return false;
- // Limit to proto2, as we rely on has bits to distinguish field presence for
- // release_$name$. On proto3, we cannot use the address of the string
- // instance when the field has been inlined.
- if (!HasFieldPresence(descriptor->file())) return false;
+ // We rely on has bits to distinguish field presence for release_$name$. When
+ // there is no hasbit, we cannot use the address of the string instance when
+ // the field has been inlined.
+ if (!HasHasbit(descriptor)) return false;
if (options.access_info_map) {
if (descriptor->is_required()) return true;
@@ -1113,7 +1151,7 @@
return UsingImplicitWeakFields(field->file(), options) &&
field->type() == FieldDescriptor::TYPE_MESSAGE &&
!field->is_required() && !field->is_map() && !field->is_extension() &&
- field->containing_oneof() == nullptr &&
+ !field->real_containing_oneof() &&
!IsWellKnownMessage(field->message_type()->file()) &&
field->message_type()->file()->name() !=
"net/proto2/proto/descriptor.proto" &&
@@ -1345,11 +1383,14 @@
format_.Set("GOOGLE_PROTOBUF", MacroPrefix(options_));
std::map<std::string, std::string> vars;
SetCommonVars(options_, &vars);
+ SetUnknkownFieldsVariable(descriptor, options_, &vars);
format_.AddMap(vars);
std::vector<const FieldDescriptor*> ordered_fields;
for (auto field : FieldRange(descriptor)) {
- ordered_fields.push_back(field);
+ if (IsFieldUsed(field, options_)) {
+ ordered_fields.push_back(field);
+ }
}
std::sort(ordered_fields.begin(), ordered_fields.end(),
[](const FieldDescriptor* a, const FieldDescriptor* b) {
@@ -1362,7 +1403,7 @@
"#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure\n");
format_.Indent();
int hasbits_size = 0;
- if (HasFieldPresence(descriptor->file())) {
+ if (num_hasbits_ > 0) {
hasbits_size = (num_hasbits_ + 31) / 32;
}
// For now only optimize small hasbits.
@@ -1375,12 +1416,13 @@
}
if (descriptor->file()->options().cc_enable_arenas()) {
- format_("$p_ns$::Arena* arena = GetArenaNoVirtual(); (void)arena;\n");
+ format_("$p_ns$::Arena* arena = GetArena(); (void)arena;\n");
}
GenerateParseLoop(descriptor, ordered_fields);
format_.Outdent();
format_("success:\n");
if (hasbits_size) format_(" _has_bits_.Or(has_bits);\n");
+
format_(
" return ptr;\n"
"failure:\n"
@@ -1400,7 +1442,7 @@
using WireFormatLite = internal::WireFormatLite;
void GenerateArenaString(const FieldDescriptor* field) {
- if (HasFieldPresence(field->file())) {
+ if (HasHasbit(field)) {
format_("_Internal::set_has_$1$(&$has_bits$);\n", FieldName(field));
}
std::string default_string =
@@ -1432,8 +1474,8 @@
GetOptimizeFor(field->file(), options_) != FileOptions::LITE_RUNTIME &&
// For now only use arena string for strings with empty defaults.
field->default_value_string().empty() &&
- !IsStringInlined(field, options_) &&
- field->containing_oneof() == nullptr && ctype == FieldOptions::STRING) {
+ !IsStringInlined(field, options_) && !field->real_containing_oneof() &&
+ ctype == FieldOptions::STRING) {
GenerateArenaString(field);
} else {
std::string name;
@@ -1495,12 +1537,20 @@
enum_validator =
StrCat(", ", QualifiedClassName(field->enum_type(), options_),
"_IsValid, &_internal_metadata_, ", field->number());
+ format_(
+ "ptr = "
+ "$pi_ns$::Packed$1$Parser<$unknown_fields_type$>(_internal_mutable_"
+ "$2$(), ptr, "
+ "ctx$3$);\n",
+ DeclaredTypeMethodName(field->type()), FieldName(field),
+ enum_validator);
+ } else {
+ format_(
+ "ptr = $pi_ns$::Packed$1$Parser(_internal_mutable_$2$(), ptr, "
+ "ctx$3$);\n",
+ DeclaredTypeMethodName(field->type()), FieldName(field),
+ enum_validator);
}
- format_(
- "ptr = $pi_ns$::Packed$1$Parser(_internal_mutable_$2$(), ptr, "
- "ctx$3$);\n",
- DeclaredTypeMethodName(field->type()), FieldName(field),
- enum_validator);
} else {
auto field_type = field->type();
switch (field_type) {
@@ -1515,10 +1565,12 @@
const FieldDescriptor* val =
field->message_type()->FindFieldByName("value");
GOOGLE_CHECK(val);
- if (HasFieldPresence(field->file()) &&
- val->type() == FieldDescriptor::TYPE_ENUM) {
+ if (val->type() == FieldDescriptor::TYPE_ENUM &&
+ !HasPreservingUnknownEnumSemantics(field)) {
format_(
- "auto object = ::$proto_ns$::internal::InitEnumParseWrapper("
+ "auto object = "
+ "::$proto_ns$::internal::InitEnumParseWrapper<$unknown_"
+ "fields_type$>("
"&$1$_, $2$_IsValid, $3$, &_internal_metadata_);\n"
"ptr = ctx->ParseMessage(&object, ptr);\n",
FieldName(field), QualifiedClassName(val->enum_type()),
@@ -1528,18 +1580,17 @@
FieldName(field));
}
} else if (IsLazy(field, options_)) {
- if (field->containing_oneof() != nullptr) {
+ if (field->real_containing_oneof()) {
format_(
"if (!_internal_has_$1$()) {\n"
" clear_$2$();\n"
" $2$_.$1$_ = ::$proto_ns$::Arena::CreateMessage<\n"
- " $pi_ns$::LazyField>("
- "GetArenaNoVirtual());\n"
+ " $pi_ns$::LazyField>(GetArena());\n"
" set_has_$1$();\n"
"}\n"
"ptr = ctx->ParseMessage($2$_.$1$_, ptr);\n",
FieldName(field), field->containing_oneof()->name());
- } else if (HasFieldPresence(field->file())) {
+ } else if (HasHasbit(field)) {
format_(
"_Internal::set_has_$1$(&$has_bits$);\n"
"ptr = ctx->ParseMessage(&$1$_, ptr);\n",
@@ -1605,7 +1656,7 @@
std::string prefix = field->is_repeated() ? "add" : "set";
if (field->type() == FieldDescriptor::TYPE_ENUM) {
format_(
- "$uint64$ val = $pi_ns$::ReadVarint(&ptr);\n"
+ "$uint64$ val = $pi_ns$::ReadVarint64(&ptr);\n"
"CHK_(ptr);\n");
if (!HasPreservingUnknownEnumSemantics(field)) {
format_("if (PROTOBUF_PREDICT_TRUE($1$_IsValid(val))) {\n",
@@ -1624,27 +1675,30 @@
field->number());
}
} else {
- int size = field->type() == FieldDescriptor::TYPE_SINT32 ? 32 : 64;
+ std::string size = (field->type() == FieldDescriptor::TYPE_SINT32 ||
+ field->type() == FieldDescriptor::TYPE_UINT32)
+ ? "32"
+ : "64";
std::string zigzag;
if ((field->type() == FieldDescriptor::TYPE_SINT32 ||
field->type() == FieldDescriptor::TYPE_SINT64)) {
- zigzag = StrCat("ZigZag", size);
+ zigzag = "ZigZag";
}
- if (field->is_repeated() || field->containing_oneof()) {
+ if (field->is_repeated() || field->real_containing_oneof()) {
std::string prefix = field->is_repeated() ? "add" : "set";
format_(
- "_internal_$1$_$2$($pi_ns$::ReadVarint$3$(&ptr));\n"
+ "_internal_$1$_$2$($pi_ns$::ReadVarint$3$$4$(&ptr));\n"
"CHK_(ptr);\n",
- prefix, FieldName(field), zigzag);
+ prefix, FieldName(field), zigzag, size);
} else {
- if (HasFieldPresence(field->file())) {
+ if (HasHasbit(field)) {
format_("_Internal::set_has_$1$(&$has_bits$);\n",
FieldName(field));
}
format_(
- "$1$_ = $pi_ns$::ReadVarint$2$(&ptr);\n"
+ "$1$_ = $pi_ns$::ReadVarint$2$$3$(&ptr);\n"
"CHK_(ptr);\n",
- FieldName(field), zigzag);
+ FieldName(field), zigzag, size);
}
}
break;
@@ -1652,14 +1706,14 @@
case WireFormatLite::WIRETYPE_FIXED32:
case WireFormatLite::WIRETYPE_FIXED64: {
std::string type = PrimitiveTypeName(options_, field->cpp_type());
- if (field->is_repeated() || field->containing_oneof()) {
+ if (field->is_repeated() || field->real_containing_oneof()) {
std::string prefix = field->is_repeated() ? "add" : "set";
format_(
"_internal_$1$_$2$($pi_ns$::UnalignedLoad<$3$>(ptr));\n"
"ptr += sizeof($3$);\n",
prefix, FieldName(field), type);
} else {
- if (HasFieldPresence(field->file())) {
+ if (HasHasbit(field)) {
format_("_Internal::set_has_$1$(&$has_bits$);\n", FieldName(field));
}
format_(
@@ -1807,7 +1861,10 @@
"}\n");
}
format_(
- " ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);\n"
+ " ptr = UnknownFieldParse(tag,\n"
+ " _internal_metadata_.mutable_unknown_fields<$unknown_"
+ "fields_type$>(),\n"
+ " ptr, ctx);\n"
" CHK_(ptr != nullptr);\n"
" continue;\n");
}
@@ -1827,6 +1884,130 @@
generator.GenerateParserLoop(descriptor);
}
+static bool HasExtensionFromFile(const Message& msg, const FileDescriptor* file,
+ const Options& options,
+ bool* has_opt_codesize_extension) {
+ std::vector<const FieldDescriptor*> fields;
+ auto reflection = msg.GetReflection();
+ reflection->ListFields(msg, &fields);
+ for (auto field : fields) {
+ const auto* field_msg = field->message_type();
+ if (field_msg == nullptr) {
+ // It so happens that enums Is_Valid are still generated so enums work.
+ // Only messages have potential problems.
+ continue;
+ }
+ // If this option has an extension set AND that extension is defined in the
+ // same file we have bootstrap problem.
+ if (field->is_extension()) {
+ const auto* msg_extension_file = field->message_type()->file();
+ if (msg_extension_file == file) return true;
+ if (has_opt_codesize_extension &&
+ GetOptimizeFor(msg_extension_file, options) ==
+ FileOptions::CODE_SIZE) {
+ *has_opt_codesize_extension = true;
+ }
+ }
+ // Recurse in this field to see if there is a problem in there
+ if (field->is_repeated()) {
+ for (int i = 0; i < reflection->FieldSize(msg, field); i++) {
+ if (HasExtensionFromFile(reflection->GetRepeatedMessage(msg, field, i),
+ file, options, has_opt_codesize_extension)) {
+ return true;
+ }
+ }
+ } else {
+ if (HasExtensionFromFile(reflection->GetMessage(msg, field), file,
+ options, has_opt_codesize_extension)) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+static bool HasBootstrapProblem(const FileDescriptor* file,
+ const Options& options,
+ bool* has_opt_codesize_extension) {
+ static auto& cache = *new std::unordered_map<const FileDescriptor*, bool>;
+ auto it = cache.find(file);
+ if (it != cache.end()) return it->second;
+ // In order to build the data structures for the reflective parse, it needs
+ // to parse the serialized descriptor describing all the messages defined in
+ // this file. Obviously this presents a bootstrap problem for descriptor
+ // messages.
+ if (file->name() == "net/proto2/proto/descriptor.proto" ||
+ file->name() == "google/protobuf/descriptor.proto") {
+ return true;
+ }
+ // Unfortunately we're not done yet. The descriptor option messages allow
+ // for extensions. So we need to be able to parse these extensions in order
+ // to parse the file descriptor for a file that has custom options. This is a
+ // problem when these custom options extensions are defined in the same file.
+ FileDescriptorProto linkedin_fd_proto;
+ const DescriptorPool* pool = file->pool();
+ const Descriptor* fd_proto_descriptor =
+ pool->FindMessageTypeByName(linkedin_fd_proto.GetTypeName());
+ // Not all pools have descriptor.proto in them. In these cases there for sure
+ // are no custom options.
+ if (fd_proto_descriptor == nullptr) return false;
+
+ // It's easier to inspect file as a proto, because we can use reflection on
+ // the proto to iterate over all content.
+ file->CopyTo(&linkedin_fd_proto);
+
+ // linkedin_fd_proto is a generated proto linked in the proto compiler. As
+ // such it doesn't know the extensions that are potentially present in the
+ // descriptor pool constructed from the protos that are being compiled. These
+ // custom options are therefore in the unknown fields.
+ // By building the corresponding FileDescriptorProto in the pool constructed
+ // by the protos that are being compiled, ie. file's pool, the unknown fields
+ // are converted to extensions.
+ DynamicMessageFactory factory(pool);
+ Message* fd_proto = factory.GetPrototype(fd_proto_descriptor)->New();
+ fd_proto->ParseFromString(linkedin_fd_proto.SerializeAsString());
+
+ bool& res = cache[file];
+ res = HasExtensionFromFile(*fd_proto, file, options,
+ has_opt_codesize_extension);
+ delete fd_proto;
+ return res;
+}
+
+FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file,
+ const Options& options,
+ bool* has_opt_codesize_extension) {
+ if (has_opt_codesize_extension) *has_opt_codesize_extension = false;
+ switch (options.enforce_mode) {
+ case EnforceOptimizeMode::kSpeed:
+ return FileOptions::SPEED;
+ case EnforceOptimizeMode::kLiteRuntime:
+ return FileOptions::LITE_RUNTIME;
+ case EnforceOptimizeMode::kCodeSize:
+ if (file->options().optimize_for() == FileOptions::LITE_RUNTIME) {
+ return FileOptions::LITE_RUNTIME;
+ }
+ if (HasBootstrapProblem(file, options, has_opt_codesize_extension)) {
+ return FileOptions::SPEED;
+ }
+ return FileOptions::CODE_SIZE;
+ case EnforceOptimizeMode::kNoEnforcement:
+ if (file->options().optimize_for() == FileOptions::CODE_SIZE) {
+ if (HasBootstrapProblem(file, options, has_opt_codesize_extension)) {
+ GOOGLE_LOG(WARNING) << "Proto states optimize_for = CODE_SIZE, but we "
+ "cannot honor that because it contains custom option "
+ "extensions defined in the same proto.";
+ return FileOptions::SPEED;
+ }
+ }
+ return file->options().optimize_for();
+ }
+
+ GOOGLE_LOG(FATAL) << "Unknown optimization enforcement requested.";
+ // The phony return below serves to silence a warning from GCC 8.
+ return FileOptions::SPEED;
+}
+
} // namespace cpp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h
index 28cf78e..988e609 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.h
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h
@@ -83,6 +83,10 @@
void SetCommonVars(const Options& options,
std::map<std::string, std::string>* variables);
+void SetUnknkownFieldsVariable(const Descriptor* descriptor,
+ const Options& options,
+ std::map<std::string, std::string>* variables);
+
bool GetBootstrapBasename(const Options& options, const std::string& basename,
std::string* bootstrap_basename);
bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context,
@@ -130,6 +134,10 @@
: ClassName(descriptor);
}
+std::string QualifiedExtensionName(const FieldDescriptor* d,
+ const Options& options);
+std::string QualifiedExtensionName(const FieldDescriptor* d);
+
// Type name of default instance.
std::string DefaultInstanceType(const Descriptor* descriptor,
const Options& options);
@@ -339,6 +347,12 @@
!options.opensource_runtime;
}
+// Returns true if "field" is used.
+inline bool IsFieldUsed(const FieldDescriptor* /*field*/,
+ const Options& /*options*/) {
+ return true;
+}
+
// Does the file contain any definitions that need extension_set.h?
bool HasExtensionsOrExtendableMessage(const FileDescriptor* file);
@@ -414,6 +428,22 @@
return file->syntax() != FileDescriptor::SYNTAX_PROTO3;
}
+inline bool HasHasbit(const FieldDescriptor* field) {
+ // This predicate includes proto3 message fields only if they have "optional".
+ // Foo submsg1 = 1; // HasHasbit() == false
+ // optional Foo submsg2 = 2; // HasHasbit() == true
+ // This is slightly odd, as adding "optional" to a singular proto3 field does
+ // not change the semantics or API. However whenever any field in a message
+ // has a hasbit, it forces reflection to include hasbit offsets for *all*
+ // fields, even if almost all of them are set to -1 (no hasbit). So to avoid
+ // causing a sudden size regression for ~all proto3 messages, we give proto3
+ // message fields a hasbit only if "optional" is present. If the user is
+ // explicitly writing "optional", it is likely they are writing it on
+ // primitive fields also.
+ return (field->has_optional_keyword() || field->is_required()) &&
+ !field->options().weak();
+}
+
// Returns true if 'enum' semantics are such that unknown values are preserved
// in the enum field itself, rather than going to the UnknownFieldSet.
inline bool HasPreservingUnknownEnumSemantics(const FieldDescriptor* field) {
@@ -475,16 +505,32 @@
}
}
+// Returns the OptimizeMode for this file, furthermore it updates a status
+// bool if has_opt_codesize_extension is non-null. If this status bool is true
+// it means this file contains an extension that itself is defined as
+// optimized_for = CODE_SIZE.
+FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file,
+ const Options& options,
+ bool* has_opt_codesize_extension);
inline FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file,
const Options& options) {
- switch (options.enforce_mode) {
- case EnforceOptimizeMode::kSpeed:
- return FileOptions::SPEED;
- case EnforceOptimizeMode::kLiteRuntime:
- return FileOptions::LITE_RUNTIME;
- case EnforceOptimizeMode::kNoEnforcement:
- default:
- return file->options().optimize_for();
+ return GetOptimizeFor(file, options, nullptr);
+}
+inline bool NeedsEagerDescriptorAssignment(const FileDescriptor* file,
+ const Options& options) {
+ bool has_opt_codesize_extension;
+ if (GetOptimizeFor(file, options, &has_opt_codesize_extension) ==
+ FileOptions::CODE_SIZE &&
+ has_opt_codesize_extension) {
+ // If this filedescriptor contains an extension from another file which
+ // is optimized_for = CODE_SIZE. We need to be careful in the ordering so
+ // we eagerly build the descriptors in the dependencies before building
+ // the descriptors of this file.
+ return true;
+ } else {
+ // If we have a generated code based parser we never need eager
+ // initialization of descriptors of our deps.
+ return false;
}
}
@@ -843,7 +889,9 @@
};
Iterator begin() const { return {0, descriptor}; }
- Iterator end() const { return {descriptor->oneof_decl_count(), descriptor}; }
+ Iterator end() const {
+ return {descriptor->real_oneof_decl_count(), descriptor};
+ }
const Descriptor* descriptor;
};
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
index bea315e..630c97e 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
@@ -29,6 +29,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/compiler/cpp/cpp_map_field.h>
+
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc
index b88c1f7..b9ba22f 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message.cc
@@ -35,6 +35,7 @@
#include <google/protobuf/compiler/cpp/cpp_message.h>
#include <algorithm>
+#include <functional>
#include <map>
#include <memory>
#include <unordered_map>
@@ -68,14 +69,40 @@
namespace {
+static constexpr int kNoHasbit = -1;
+
+// Create an expression that evaluates to
+// "for all i, (_has_bits_[i] & masks[i]) == masks[i]"
+// masks is allowed to be shorter than _has_bits_, but at least one element of
+// masks must be non-zero.
+std::string ConditionalToCheckBitmasks(
+ const std::vector<uint32>& masks, bool return_success = true,
+ StringPiece has_bits_var = "_has_bits_") {
+ std::vector<std::string> parts;
+ for (int i = 0; i < masks.size(); i++) {
+ if (masks[i] == 0) continue;
+ std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
+ // Each xor evaluates to 0 if the expected bits are present.
+ parts.push_back(
+ StrCat("((", has_bits_var, "[", i, "] & ", m, ") ^ ", m, ")"));
+ }
+ GOOGLE_CHECK(!parts.empty());
+ // If we have multiple parts, each expected to be 0, then bitwise-or them.
+ std::string result =
+ parts.size() == 1
+ ? parts[0]
+ : StrCat("(", Join(parts, "\n | "), ")");
+ return result + (return_success ? " == 0" : " != 0");
+}
+
void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field,
const std::vector<int>& has_bit_indices,
- io::Printer* printer, int* cached_has_bit_index) {
+ io::Printer* printer, int* cached_has_word_index) {
if (!field->options().weak()) {
int has_bit_index = has_bit_indices[field->index()];
- if (*cached_has_bit_index != (has_bit_index / 32)) {
- *cached_has_bit_index = (has_bit_index / 32);
- format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_bit_index);
+ if (*cached_has_word_index != (has_bit_index / 32)) {
+ *cached_has_word_index = (has_bit_index / 32);
+ format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_word_index);
}
const std::string mask =
StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
@@ -132,26 +159,53 @@
}
}
-// Helper for the code that emits the SharedCtor() method.
-bool CanConstructByZeroing(const FieldDescriptor* field,
- const Options& options) {
+// Helper for the code that emits the SharedCtor() and InternalSwap() methods.
+// Anything that is a POD or a "normal" message (represented by a pointer) can
+// be manipulated as raw bytes.
+bool CanBeManipulatedAsRawBytes(const FieldDescriptor* field,
+ const Options& options) {
bool ret = CanInitializeByZeroing(field);
// Non-repeated, non-lazy message fields are simply raw pointers, so we can
- // use memset to initialize these in SharedCtor. We cannot use this in
- // Clear, as we need to potentially delete the existing value.
+ // swap them or use memset to initialize these in SharedCtor. We cannot use
+ // this in Clear, as we need to potentially delete the existing value.
ret = ret || (!field->is_repeated() && !IsLazy(field, options) &&
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE);
return ret;
}
+// Finds runs of fields for which `predicate` is true.
+// 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.
+using RunMap = std::unordered_map<const FieldDescriptor*, size_t>;
+RunMap FindRuns(const std::vector<const FieldDescriptor*>& fields,
+ const std::function<bool(const FieldDescriptor*)>& predicate) {
+ RunMap runs;
+ const FieldDescriptor* last_start = nullptr;
+
+ for (auto field : fields) {
+ if (predicate(field)) {
+ if (last_start == nullptr) {
+ last_start = field;
+ }
+
+ runs[last_start]++;
+ } else {
+ last_start = nullptr;
+ }
+ }
+ return runs;
+}
+
// Emits an if-statement with a condition that evaluates to true if |field| is
// considered non-default (will be sent over the wire), for message types
// without true field presence. Should only be called if
-// !HasFieldPresence(message_descriptor).
+// !HasHasbit(field).
bool EmitFieldNonDefaultCondition(io::Printer* printer,
const std::string& prefix,
const FieldDescriptor* field) {
+ GOOGLE_CHECK(!HasHasbit(field));
Formatter format(printer);
format.Set("prefix", prefix);
format.Set("name", FieldName(field));
@@ -172,7 +226,7 @@
}
format.Indent();
return true;
- } else if (field->containing_oneof()) {
+ } else if (field->real_containing_oneof()) {
format("if (_internal_has_$name$()) {\n");
format.Indent();
return true;
@@ -188,7 +242,8 @@
}
// For message types without true field presence, only fields with a message
// type have a has_$name$() method.
- return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE;
+ return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
+ field->has_optional_keyword();
}
// Collects map entry message type information.
@@ -227,16 +282,15 @@
bool HasPrivateHasMethod(const FieldDescriptor* field) {
// Only for oneofs in message types with no field presence. has_$name$(),
// based on the oneof case, is still useful internally for generated code.
- return (!HasFieldPresence(field->file()) &&
- field->containing_oneof() != NULL);
+ return (!HasFieldPresence(field->file()) && field->real_containing_oneof());
}
// TODO(ckennelly): Cull these exclusions if/when these protos do not have
-// their methods overriden by subclasses.
+// their methods overridden by subclasses.
bool ShouldMarkClassAsFinal(const Descriptor* descriptor,
const Options& options) {
- return false;
+ return true;
}
bool ShouldMarkClearAsFinal(const Descriptor* descriptor,
@@ -278,10 +332,16 @@
// Consider table-driven parsing. We only do this if:
// - We have has_bits for fields. This avoids a check on every field we set
// when are present (the common case).
- if (!HasFieldPresence(descriptor->file())) {
- return false;
+ bool has_hasbit = false;
+ for (int i = 0; i < descriptor->field_count(); i++) {
+ if (HasHasbit(descriptor->field(i))) {
+ has_hasbit = true;
+ break;
+ }
}
+ if (!has_hasbit) return false;
+
const double table_sparseness = 0.5;
int max_field_number = 0;
for (auto field : FieldRange(descriptor)) {
@@ -320,23 +380,6 @@
return true;
}
-void SetUnknkownFieldsVariable(const Descriptor* descriptor,
- const Options& options,
- std::map<std::string, std::string>* variables) {
- std::string proto_ns = ProtobufNamespace(options);
- if (UseUnknownFieldSet(descriptor->file(), options)) {
- (*variables)["unknown_fields_type"] = "::" + proto_ns + "::UnknownFieldSet";
- } else {
- (*variables)["unknown_fields_type"] =
- PrimitiveTypeName(options, FieldDescriptor::CPPTYPE_STRING);
- }
- (*variables)["have_unknown_fields"] =
- "_internal_metadata_.have_unknown_fields()";
- (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields()";
- (*variables)["mutable_unknown_fields"] =
- "_internal_metadata_.mutable_unknown_fields()";
-}
-
bool IsCrossFileMapField(const FieldDescriptor* field) {
if (!field->is_map()) {
return false;
@@ -360,82 +403,17 @@
return v.front()->is_required();
}
-// Allows chunking repeated fields together and non-repeated fields if the
-// fields share the same has_byte index.
-// TODO(seongkim): use lambda with capture instead of functor.
-class MatchRepeatedAndHasByte {
- public:
- MatchRepeatedAndHasByte(const std::vector<int>* has_bit_indices,
- bool has_field_presence)
- : has_bit_indices_(*has_bit_indices),
- has_field_presence_(has_field_presence) {}
-
- // Returns true if the following conditions are met:
- // --both fields are repeated fields
- // --both fields are non-repeated fields with either has_field_presence is
- // false or have the same has_byte index.
- bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
- return a->is_repeated() == b->is_repeated() &&
- (!has_field_presence_ || a->is_repeated() ||
- has_bit_indices_[a->index()] / 8 ==
- has_bit_indices_[b->index()] / 8);
- }
-
- private:
- const std::vector<int>& has_bit_indices_;
- const bool has_field_presence_;
-};
-
-// Allows chunking required fields separately after chunking with
-// MatchRepeatedAndHasByte.
-class MatchRepeatedAndHasByteAndRequired : public MatchRepeatedAndHasByte {
- public:
- MatchRepeatedAndHasByteAndRequired(const std::vector<int>* has_bit_indices,
- bool has_field_presence)
- : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {}
-
- bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
- return MatchRepeatedAndHasByte::operator()(a, b) &&
- a->is_required() == b->is_required();
- }
-};
-
-// Allows chunking zero-initializable fields separately after chunking with
-// MatchRepeatedAndHasByte.
-class MatchRepeatedAndHasByteAndZeroInits : public MatchRepeatedAndHasByte {
- public:
- MatchRepeatedAndHasByteAndZeroInits(const std::vector<int>* has_bit_indices,
- bool has_field_presence)
- : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {}
-
- bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
- return MatchRepeatedAndHasByte::operator()(a, b) &&
- CanInitializeByZeroing(a) == CanInitializeByZeroing(b);
- }
-};
-
// Collects neighboring fields based on a given criteria (equivalent predicate).
template <typename Predicate>
std::vector<std::vector<const FieldDescriptor*>> CollectFields(
const std::vector<const FieldDescriptor*>& fields,
const Predicate& equivalent) {
std::vector<std::vector<const FieldDescriptor*>> chunks;
- if (fields.empty()) {
- return chunks;
- }
-
- const FieldDescriptor* last_field = fields.front();
- std::vector<const FieldDescriptor*> chunk;
for (auto field : fields) {
- if (!equivalent(last_field, field) && !chunk.empty()) {
- chunks.push_back(chunk);
- chunk.clear();
+ if (chunks.empty() || !equivalent(chunks.back().back(), field)) {
+ chunks.emplace_back();
}
- chunk.push_back(field);
- last_field = field;
- }
- if (!chunk.empty()) {
- chunks.push_back(chunk);
+ chunks.back().push_back(field);
}
return chunks;
}
@@ -475,20 +453,18 @@
ColdChunkSkipper(
const Options& options,
const std::vector<std::vector<const FieldDescriptor*>>& chunks,
- const std::vector<int>& has_bit_indices, const double cold_threshold,
- bool has_field_presence)
+ const std::vector<int>& has_bit_indices, const double cold_threshold)
: chunks_(chunks),
has_bit_indices_(has_bit_indices),
access_info_map_(options.access_info_map),
- cold_threshold_(cold_threshold),
- has_field_presence_(has_field_presence) {
+ cold_threshold_(cold_threshold) {
SetCommonVars(options, &variables_);
}
// May open an external if check for a batch of cold fields. "from" is the
// prefix to _has_bits_ to allow MergeFrom to use "from._has_bits_".
// Otherwise, it should be "".
- void OnStartChunk(int chunk, int cached_has_bit_index,
+ void OnStartChunk(int chunk, int cached_has_word_index,
const std::string& from, io::Printer* printer);
bool OnEndChunk(int chunk, io::Printer* printer);
@@ -505,7 +481,6 @@
const double cold_threshold_;
std::map<std::string, std::string> variables_;
int limit_chunk_ = -1;
- bool has_field_presence_;
};
// Tuning parameters for ColdChunkSkipper.
@@ -518,11 +493,11 @@
}
-void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_bit_index,
+void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_word_index,
const std::string& from,
io::Printer* printer) {
Formatter format(printer, variables_);
- if (!access_info_map_ || !has_field_presence_) {
+ if (!access_info_map_) {
return;
} else if (chunk < limit_chunk_) {
// We are already inside a run of cold chunks.
@@ -564,7 +539,7 @@
format(" ||\n ");
}
format.Set("mask", strings::Hex(mask, strings::ZERO_PAD_8));
- if (this_word == cached_has_bit_index) {
+ if (this_word == cached_has_word_index) {
format("(cached_has_bits & 0x$mask$u) != 0");
} else {
format("($1$_has_bits_[$2$] & 0x$mask$u) != 0", from, this_word);
@@ -616,26 +591,30 @@
// Compute optimized field order to be used for layout and initialization
// purposes.
for (auto field : FieldRange(descriptor_)) {
+ if (!IsFieldUsed(field, options_)) {
+ continue;
+ }
+
if (IsWeak(field, options_)) {
num_weak_fields_++;
- } else if (!field->containing_oneof()) {
+ } else if (!field->real_containing_oneof()) {
optimized_order_.push_back(field);
}
}
message_layout_helper_->OptimizeLayout(&optimized_order_, options_);
- if (HasFieldPresence(descriptor_->file())) {
- // We use -1 as a sentinel.
- has_bit_indices_.resize(descriptor_->field_count(), -1);
- for (auto field : optimized_order_) {
- // Skip fields that do not have has bits.
- if (field->is_repeated()) {
- continue;
+ // This message has hasbits iff one or more fields need one.
+ for (auto field : optimized_order_) {
+ if (HasHasbit(field)) {
+ if (has_bit_indices_.empty()) {
+ has_bit_indices_.resize(descriptor_->field_count(), kNoHasbit);
}
-
has_bit_indices_[field->index()] = max_has_bit_index_++;
}
+ }
+
+ if (!has_bit_indices_.empty()) {
field_generators_.SetHasBitIndices(has_bit_indices_);
}
@@ -664,6 +643,21 @@
return sizeof_has_bits;
}
+int MessageGenerator::HasBitIndex(const FieldDescriptor* field) const {
+ return has_bit_indices_.empty() ? kNoHasbit
+ : has_bit_indices_[field->index()];
+}
+
+int MessageGenerator::HasByteIndex(const FieldDescriptor* field) const {
+ int hasbit = HasBitIndex(field);
+ return hasbit == kNoHasbit ? kNoHasbit : hasbit / 8;
+}
+
+int MessageGenerator::HasWordIndex(const FieldDescriptor* field) const {
+ int hasbit = HasBitIndex(field);
+ return hasbit == kNoHasbit ? kNoHasbit : hasbit / 32;
+}
+
void MessageGenerator::AddGenerators(
std::vector<std::unique_ptr<EnumGenerator>>* enum_generators,
std::vector<std::unique_ptr<ExtensionGenerator>>* extension_generators) {
@@ -682,7 +676,7 @@
void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) {
Formatter format(printer, variables_);
// optimized_fields_ does not contain fields where
- // field->containing_oneof() != NULL
+ // field->real_containing_oneof()
// so we need to iterate over those as well.
//
// We place the non-oneof fields in optimized_order_, as that controls the
@@ -694,7 +688,8 @@
ordered_fields.insert(ordered_fields.begin(), optimized_order_.begin(),
optimized_order_.end());
for (auto field : FieldRange(descriptor_)) {
- if (field->containing_oneof() == NULL && !field->options().weak()) {
+ if (!field->real_containing_oneof() && !field->options().weak() &&
+ IsFieldUsed(field, options_)) {
continue;
}
ordered_fields.push_back(field);
@@ -722,28 +717,35 @@
format.AddMap(vars);
if (field->is_repeated()) {
- format(
- "$deprecated_attr$int ${1$$name$_size$}$() const;\n"
- "private:\n"
- "int ${1$_internal_$name$_size$}$() const;\n"
- "public:\n",
- field);
+ format("$deprecated_attr$int ${1$$name$_size$}$() const$2$\n", field,
+ IsFieldUsed(field, options_) ? ";" : " {__builtin_trap();}");
+ if (IsFieldUsed(field, options_)) {
+ format(
+ "private:\n"
+ "int ${1$_internal_$name$_size$}$() const;\n"
+ "public:\n",
+ field);
+ }
} else if (HasHasMethod(field)) {
- format(
- "$deprecated_attr$bool ${1$has_$name$$}$() const;\n"
- "private:\n"
- "bool _internal_has_$name$() const;\n"
- "public:\n",
- field);
+ format("$deprecated_attr$bool ${1$has_$name$$}$() const$2$\n", field,
+ IsFieldUsed(field, options_) ? ";" : " {__builtin_trap();}");
+ if (IsFieldUsed(field, options_)) {
+ format(
+ "private:\n"
+ "bool _internal_has_$name$() const;\n"
+ "public:\n");
+ }
} else if (HasPrivateHasMethod(field)) {
- format(
- "private:\n"
- "bool ${1$_internal_has_$name$$}$() const;\n"
- "public:\n",
- field);
+ if (IsFieldUsed(field, options_)) {
+ format(
+ "private:\n"
+ "bool ${1$_internal_has_$name$$}$() const;\n"
+ "public:\n",
+ field);
+ }
}
-
- format("$deprecated_attr$void ${1$clear_$name$$}$();\n", field);
+ format("$deprecated_attr$void ${1$clear_$name$$}$()$2$\n", field,
+ IsFieldUsed(field, options_) ? ";" : "{__builtin_trap();}");
// Generate type-specific accessor declarations.
field_generators_.get(field).GenerateAccessorDeclarations(printer);
@@ -778,6 +780,12 @@
void MessageGenerator::GenerateSingularFieldHasBits(
const FieldDescriptor* field, Formatter format) {
+ if (!IsFieldUsed(field, options_)) {
+ format(
+ "inline bool $classname$::has_$name$() const { "
+ "__builtin_trap(); }\n");
+ return;
+ }
if (field->options().weak()) {
format(
"inline bool $classname$::has_$name$() const {\n"
@@ -786,11 +794,9 @@
"}\n");
return;
}
- if (HasFieldPresence(descriptor_->file())) {
- // N.B.: without field presence, we do not use has-bits or generate
- // has_$name$() methods.
- int has_bit_index = has_bit_indices_[field->index()];
- GOOGLE_CHECK_GE(has_bit_index, 0);
+ if (HasHasbit(field)) {
+ int has_bit_index = HasBitIndex(field);
+ GOOGLE_CHECK_NE(has_bit_index, kNoHasbit);
format.Set("has_array_index", has_bit_index / 32);
format.Set("has_mask",
@@ -815,27 +821,25 @@
"$annotate_accessor$"
" return _internal_has_$name$();\n"
"}\n");
- } else {
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
// Message fields have a has_$name$() method.
- if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- if (IsLazy(field, options_)) {
- format(
- "inline bool $classname$::_internal_has_$name$() const {\n"
- " return !$name$_.IsCleared();\n"
- "}\n");
- } else {
- format(
- "inline bool $classname$::_internal_has_$name$() const {\n"
- " return this != internal_default_instance() "
- "&& $name$_ != nullptr;\n"
- "}\n");
- }
+ if (IsLazy(field, options_)) {
format(
- "inline bool $classname$::has_$name$() const {\n"
- "$annotate_accessor$"
- " return _internal_has_$name$();\n"
+ "inline bool $classname$::_internal_has_$name$() const {\n"
+ " return !$name$_.IsCleared();\n"
+ "}\n");
+ } else {
+ format(
+ "inline bool $classname$::_internal_has_$name$() const {\n"
+ " return this != internal_default_instance() "
+ "&& $name$_ != nullptr;\n"
"}\n");
}
+ format(
+ "inline bool $classname$::has_$name$() const {\n"
+ "$annotate_accessor$"
+ " return _internal_has_$name$();\n"
+ "}\n");
}
}
@@ -857,6 +861,17 @@
void MessageGenerator::GenerateOneofMemberHasBits(const FieldDescriptor* field,
const Formatter& format) {
+ if (!IsFieldUsed(field, options_)) {
+ if (HasHasMethod(field)) {
+ format(
+ "inline bool $classname$::has_$name$() const { "
+ "__builtin_trap(); }\n");
+ }
+ format(
+ "inline void $classname$::set_has_$name$() { __builtin_trap(); "
+ "}\n");
+ return;
+ }
// Singular field in a oneof
// N.B.: Without field presence, we do not use has-bits or generate
// has_$name$() methods, but oneofs still have set_has_$name$().
@@ -891,6 +906,11 @@
void MessageGenerator::GenerateFieldClear(const FieldDescriptor* field,
bool is_inline, Formatter format) {
+ if (!IsFieldUsed(field, options_)) {
+ format("void $classname$::clear_$name$() { __builtin_trap(); }\n");
+ return;
+ }
+
// Generate clear_$name$().
if (is_inline) {
format("inline ");
@@ -901,7 +921,7 @@
format.Indent();
- if (field->containing_oneof()) {
+ if (field->real_containing_oneof()) {
// Clear this field only if it is the active field in this oneof,
// otherwise ignore
format("if (_internal_has_$name$()) {\n");
@@ -912,16 +932,12 @@
format("}\n");
} else {
field_generators_.get(field).GenerateClearingCode(format.printer());
- if (HasFieldPresence(descriptor_->file())) {
- if (!field->is_repeated() && !field->options().weak()) {
- int has_bit_index = has_bit_indices_[field->index()];
- GOOGLE_CHECK_GE(has_bit_index, 0);
-
- format.Set("has_array_index", has_bit_index / 32);
- format.Set("has_mask",
- strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
- format("_has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n");
- }
+ if (HasHasbit(field)) {
+ int has_bit_index = HasBitIndex(field);
+ format.Set("has_array_index", has_bit_index / 32);
+ format.Set("has_mask",
+ strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
+ format("_has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n");
}
}
@@ -936,6 +952,10 @@
for (auto field : FieldRange(descriptor_)) {
PrintFieldComment(format, field);
+ if (!IsFieldUsed(field, options_)) {
+ continue;
+ }
+
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
@@ -944,19 +964,25 @@
// Generate has_$name$() or $name$_size().
if (field->is_repeated()) {
- format(
- "inline int $classname$::_internal_$name$_size() const {\n"
- " return $name$_$1$.size();\n"
- "}\n"
- "inline int $classname$::$name$_size() const {\n"
- "$annotate_accessor$"
- " return _internal_$name$_size();\n"
- "}\n",
- IsImplicitWeakField(field, options_, scc_analyzer_) &&
- field->message_type()
- ? ".weak"
- : "");
- } else if (field->containing_oneof()) {
+ if (!IsFieldUsed(field, options_)) {
+ format(
+ "inline int $classname$::$name$_size() const { "
+ "__builtin_trap(); }\n");
+ } else {
+ format(
+ "inline int $classname$::_internal_$name$_size() const {\n"
+ " return $name$_$1$.size();\n"
+ "}\n"
+ "inline int $classname$::$name$_size() const {\n"
+ "$annotate_accessor$"
+ " return _internal_$name$_size();\n"
+ "}\n",
+ IsImplicitWeakField(field, options_, scc_analyzer_) &&
+ field->message_type()
+ ? ".weak"
+ : "");
+ }
+ } else if (field->real_containing_oneof()) {
format.Set("field_name", UnderscoresToCamelCase(field->name(), true));
format.Set("oneof_name", field->containing_oneof()->name());
format.Set("oneof_index",
@@ -972,7 +998,9 @@
}
// Generate type-specific accessors.
- field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
+ if (IsFieldUsed(field, options_)) {
+ field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
+ }
format("\n");
}
@@ -983,8 +1011,9 @@
void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
Formatter format(printer, variables_);
- format.Set("class_final",
- ShouldMarkClassAsFinal(descriptor_, options_) ? "final" : "");
+ format.Set("class_final", ShouldMarkClassAsFinal(descriptor_, options_)
+ ? "PROTOBUF_FINAL"
+ : "");
if (IsMapEntryMessage(descriptor_)) {
std::map<std::string, std::string> vars;
@@ -1093,8 +1122,13 @@
format(" public:\n");
format.Indent();
+ if (SupportsArenas(descriptor_)) {
+ format("inline $classname$() : $classname$(nullptr) {};\n");
+ } else {
+ format("$classname$();\n");
+ }
+
format(
- "$classname$();\n"
"virtual ~$classname$();\n"
"\n"
"$classname$(const $classname$& from);\n"
@@ -1108,7 +1142,7 @@
" return *this;\n"
"}\n"
"inline $classname$& operator=($classname$&& from) noexcept {\n"
- " if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {\n"
+ " if (GetArena() == from.GetArena()) {\n"
" if (this != &from) InternalSwap(&from);\n"
" } else {\n"
" CopyFrom(from);\n"
@@ -1139,21 +1173,6 @@
"\n");
}
- // N.B.: We exclude GetArena() when arena support is disabled, falling back on
- // MessageLite's implementation which returns NULL rather than generating our
- // own method which returns NULL, in order to reduce code size.
- if (SupportsArenas(descriptor_)) {
- // virtual method version of GetArenaNoVirtual(), required for generic
- // dispatch given a MessageLite* (e.g., in RepeatedField::AddAllocated()).
- format(
- "inline ::$proto_ns$::Arena* GetArena() const final {\n"
- " return GetArenaNoVirtual();\n"
- "}\n"
- "inline void* GetMaybeArenaPointer() const final {\n"
- " return MaybeArenaPtr();\n"
- "}\n");
- }
-
// Only generate this member if it's not disabled.
if (HasDescriptorMethods(descriptor_->file(), options_) &&
!descriptor_->options().no_standard_descriptor_accessor()) {
@@ -1290,7 +1309,7 @@
format(
"inline void Swap($classname$* other) {\n"
" if (other == this) return;\n"
- " if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {\n"
+ " if (GetArena() == other->GetArena()) {\n"
" InternalSwap(other);\n"
" } else {\n"
" ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);\n"
@@ -1298,7 +1317,7 @@
"}\n"
"void UnsafeArenaSwap($classname$* other) {\n"
" if (other == this) return;\n"
- " $DCHK$(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n"
+ " $DCHK$(GetArena() == other->GetArena());\n"
" InternalSwap(other);\n"
"}\n");
} else {
@@ -1393,26 +1412,6 @@
"inline void RegisterArenaDtor(::$proto_ns$::Arena* arena);\n");
}
- if (SupportsArenas(descriptor_)) {
- format(
- "private:\n"
- "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n"
- " return _internal_metadata_.arena();\n"
- "}\n"
- "inline void* MaybeArenaPtr() const {\n"
- " return _internal_metadata_.raw_arena_ptr();\n"
- "}\n");
- } else {
- format(
- "private:\n"
- "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n"
- " return nullptr;\n"
- "}\n"
- "inline void* MaybeArenaPtr() const {\n"
- " return nullptr;\n"
- "}\n");
- }
-
format(
"public:\n"
"\n");
@@ -1482,11 +1481,10 @@
// TODO(seongkim): Remove hack to track field access and remove this class.
format("class _Internal;\n");
-
for (auto field : FieldRange(descriptor_)) {
// set_has_***() generated in all oneofs.
if (!field->is_repeated() && !field->options().weak() &&
- field->containing_oneof()) {
+ field->real_containing_oneof()) {
format("void set_has_$1$();\n", FieldName(field));
}
}
@@ -1536,16 +1534,6 @@
"\n");
}
- if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- format(
- "::$proto_ns$::internal::InternalMetadataWithArena "
- "_internal_metadata_;\n");
- } else {
- format(
- "::$proto_ns$::internal::InternalMetadataWithArenaLite "
- "_internal_metadata_;\n");
- }
-
if (SupportsArenas(descriptor_)) {
format(
"template <typename T> friend class "
@@ -1554,7 +1542,7 @@
"typedef void DestructorSkippable_;\n");
}
- if (HasFieldPresence(descriptor_->file())) {
+ if (!has_bit_indices_.empty()) {
// _has_bits_ is frequently accessed, so to reduce code size and improve
// speed, it should be close to the start of the object. Placing
// _cached_size_ together with _has_bits_ improves cache locality despite
@@ -1584,12 +1572,16 @@
camel_oneof_name);
format.Indent();
for (auto field : FieldRange(oneof)) {
- field_generators_.get(field).GeneratePrivateMembers(printer);
+ if (IsFieldUsed(field, options_)) {
+ field_generators_.get(field).GeneratePrivateMembers(printer);
+ }
}
format.Outdent();
format("} $1$_;\n", oneof->name());
for (auto field : FieldRange(oneof)) {
- field_generators_.get(field).GenerateStaticMembers(printer);
+ if (IsFieldUsed(field, options_)) {
+ field_generators_.get(field).GenerateStaticMembers(printer);
+ }
}
}
@@ -1601,11 +1593,11 @@
}
// Generate _oneof_case_.
- if (descriptor_->oneof_decl_count() > 0) {
+ if (descriptor_->real_oneof_decl_count() > 0) {
format(
"$uint32$ _oneof_case_[$1$];\n"
"\n",
- descriptor_->oneof_decl_count());
+ descriptor_->real_oneof_decl_count());
}
if (num_weak_fields_) {
@@ -1649,21 +1641,22 @@
// Generate oneof default instance and weak field instances for reflection
// usage.
Formatter format(printer, variables_);
- if (descriptor_->oneof_decl_count() > 0 || num_weak_fields_ > 0) {
- for (auto oneof : OneOfRange(descriptor_)) {
- for (auto field : FieldRange(oneof)) {
- if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
- (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
- EffectiveStringCType(field, options_) != FieldOptions::STRING)) {
- format("const ");
- }
- field_generators_.get(field).GeneratePrivateMembers(printer);
+ for (auto oneof : OneOfRange(descriptor_)) {
+ for (auto field : FieldRange(oneof)) {
+ if (!IsFieldUsed(field, options_)) {
+ continue;
}
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
+ (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
+ EffectiveStringCType(field, options_) != FieldOptions::STRING)) {
+ format("const ");
+ }
+ field_generators_.get(field).GeneratePrivateMembers(printer);
}
- for (auto field : FieldRange(descriptor_)) {
- if (field->options().weak()) {
- format(" const ::$proto_ns$::Message* $1$_;\n", FieldName(field));
- }
+ }
+ for (auto field : FieldRange(descriptor_)) {
+ if (field->options().weak() && IsFieldUsed(field, options_)) {
+ format(" const ::$proto_ns$::Message* $1$_;\n", FieldName(field));
}
}
}
@@ -1693,14 +1686,14 @@
"$3$,\n",
offset, aux_offset, max_field_number);
- if (!HasFieldPresence(descriptor_->file())) {
- // If we don't have field presence, then _has_bits_ does not exist.
+ if (has_bit_indices_.empty()) {
+ // If no fields have hasbits, then _has_bits_ does not exist.
format("-1,\n");
} else {
format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n");
}
- if (descriptor_->oneof_decl_count() > 0) {
+ if (descriptor_->real_oneof_decl_count() > 0) {
format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_),\n");
} else {
format("-1, // no _oneof_case_\n");
@@ -1732,10 +1725,9 @@
void MessageGenerator::GenerateSchema(io::Printer* printer, int offset,
int has_offset) {
Formatter format(printer, variables_);
- has_offset =
- HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)
- ? offset + has_offset
- : -1;
+ has_offset = !has_bit_indices_.empty() || IsMapEntryMessage(descriptor_)
+ ? offset + has_offset
+ : -1;
format("{ $1$, $2$, sizeof($classtype$)},\n", offset, has_offset);
}
@@ -1760,23 +1752,22 @@
type = internal::FieldMetadata::kStringPieceType;
}
}
- if (field->containing_oneof()) {
+
+ if (field->real_containing_oneof()) {
return internal::FieldMetadata::CalculateType(
type, internal::FieldMetadata::kOneOf);
- }
- if (field->is_packed()) {
+ } else if (field->is_packed()) {
return internal::FieldMetadata::CalculateType(
type, internal::FieldMetadata::kPacked);
} else if (field->is_repeated()) {
return internal::FieldMetadata::CalculateType(
type, internal::FieldMetadata::kRepeated);
- } else if (!HasFieldPresence(field->file()) &&
- field->containing_oneof() == NULL && !is_a_map) {
- return internal::FieldMetadata::CalculateType(
- type, internal::FieldMetadata::kNoPresence);
- } else {
+ } else if (HasHasbit(field) || field->real_containing_oneof() || is_a_map) {
return internal::FieldMetadata::CalculateType(
type, internal::FieldMetadata::kPresence);
+ } else {
+ return internal::FieldMetadata::CalculateType(
+ type, internal::FieldMetadata::kNoPresence);
}
}
@@ -1866,7 +1857,7 @@
}
std::string classfieldname = FieldName(field);
- if (field->containing_oneof()) {
+ if (field->real_containing_oneof()) {
classfieldname = field->containing_oneof()->name();
}
format.Set("field_name", classfieldname);
@@ -1902,10 +1893,9 @@
type = internal::FieldMetadata::kSpecial;
ptr = "reinterpret_cast<const void*>(::" + variables_["proto_ns"] +
"::internal::LazyFieldSerializer";
- if (field->containing_oneof()) {
+ if (field->real_containing_oneof()) {
ptr += "OneOf";
- } else if (!HasFieldPresence(descriptor_->file()) ||
- has_bit_indices_[field->index()] == -1) {
+ } else if (!HasHasbit(field)) {
ptr += "NoPresence";
}
ptr += ")";
@@ -1920,7 +1910,7 @@
"reinterpret_cast<const "
"void*>(::$proto_ns$::internal::WeakFieldSerializer)},\n",
tag);
- } else if (field->containing_oneof()) {
+ } else if (field->real_containing_oneof()) {
format.Set("oneofoffset",
sizeof(uint32) * field->containing_oneof()->index());
format(
@@ -1928,8 +1918,7 @@
" PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_) + "
"$oneofoffset$, $2$, $3$},\n",
tag, type, ptr);
- } else if (HasFieldPresence(descriptor_->file()) &&
- has_bit_indices_[field->index()] != -1) {
+ } else if (HasHasbit(field)) {
format.Set("hasbitsoffset", has_bit_indices_[field->index()]);
format(
"{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), "
@@ -1974,14 +1963,17 @@
// TODO(kenton): Maybe all message fields (even for non-default messages)
// should be initialized to point at default instances rather than NULL?
for (auto field : FieldRange(descriptor_)) {
+ if (!IsFieldUsed(field, options_)) {
+ continue;
+ }
Formatter::SaveState saver(&format);
if (!field->is_repeated() && !IsLazy(field, options_) &&
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
- (field->containing_oneof() == NULL ||
+ (!field->real_containing_oneof() ||
HasDescriptorMethods(descriptor_->file(), options_))) {
std::string name;
- if (field->containing_oneof() || field->options().weak()) {
+ if (field->real_containing_oneof() || field->options().weak()) {
name = "_" + classname_ + "_default_instance_.";
} else {
name =
@@ -2013,7 +2005,7 @@
" $1$::internal_default_instance());\n",
FieldMessageTypeName(field, options_));
}
- } else if (field->containing_oneof() &&
+ } else if (field->real_containing_oneof() &&
HasDescriptorMethods(descriptor_->file(), options_)) {
field_generators_.get(field).GenerateConstructorCode(printer);
}
@@ -2077,16 +2069,18 @@
"class $classname$::_Internal {\n"
" public:\n");
format.Indent();
- if (HasFieldPresence(descriptor_->file()) && HasBitsSize() != 0) {
+ if (!has_bit_indices_.empty()) {
format(
"using HasBits = decltype(std::declval<$classname$>()._has_bits_);\n");
}
for (auto field : FieldRange(descriptor_)) {
field_generators_.get(field).GenerateInternalAccessorDeclarations(printer);
- if (HasFieldPresence(descriptor_->file()) && !field->is_repeated() &&
- !field->options().weak() && !field->containing_oneof()) {
- int has_bit_index = has_bit_indices_[field->index()];
- GOOGLE_CHECK_GE(has_bit_index, 0);
+ if (!IsFieldUsed(field, options_)) {
+ continue;
+ }
+ if (HasHasbit(field)) {
+ int has_bit_index = HasBitIndex(field);
+ GOOGLE_CHECK_NE(has_bit_index, kNoHasbit) << field->full_name();
format(
"static void set_has_$1$(HasBits* has_bits) {\n"
" (*has_bits)[$2$] |= $3$u;\n"
@@ -2094,20 +2088,35 @@
FieldName(field), has_bit_index / 32, (1u << (has_bit_index % 32)));
}
}
+ if (num_required_fields_ > 0) {
+ const std::vector<uint32> masks_for_has_bits = RequiredFieldsBitMask();
+ format(
+ "static bool MissingRequiredFields(const HasBits& has_bits) "
+ "{\n"
+ " return $1$;\n"
+ "}\n",
+ ConditionalToCheckBitmasks(masks_for_has_bits, false, "has_bits"));
+ }
+
format.Outdent();
format("};\n\n");
for (auto field : FieldRange(descriptor_)) {
- field_generators_.get(field).GenerateInternalAccessorDefinitions(printer);
+ if (IsFieldUsed(field, options_)) {
+ field_generators_.get(field).GenerateInternalAccessorDefinitions(printer);
+ }
}
// Generate non-inline field definitions.
for (auto field : FieldRange(descriptor_)) {
+ if (!IsFieldUsed(field, options_)) {
+ continue;
+ }
field_generators_.get(field).GenerateNonInlineAccessorDefinitions(printer);
if (IsCrossFileMaybeMap(field)) {
Formatter::SaveState saver(&format);
std::map<std::string, std::string> vars;
SetCommonFieldVariables(field, &vars, options_);
- if (field->containing_oneof()) {
+ if (field->real_containing_oneof()) {
SetCommonOneofFieldVariables(field, &vars);
}
format.AddMap(vars);
@@ -2118,7 +2127,7 @@
GenerateStructors(printer);
format("\n");
- if (descriptor_->oneof_decl_count() > 0) {
+ if (descriptor_->real_oneof_decl_count() > 0) {
GenerateOneofClear(printer);
format("\n");
}
@@ -2139,6 +2148,9 @@
GenerateMergeFrom(printer);
format("\n");
+ GenerateClassSpecificMergeFrom(printer);
+ format("\n");
+
GenerateCopyFrom(printer);
format("\n");
@@ -2245,7 +2257,7 @@
processing_type |= static_cast<unsigned>(
field->is_repeated() ? internal::kRepeatedMask : 0);
processing_type |= static_cast<unsigned>(
- field->containing_oneof() ? internal::kOneofMask : 0);
+ field->real_containing_oneof() ? internal::kOneofMask : 0);
if (field->is_map()) {
processing_type = internal::TYPE_MAP;
@@ -2255,7 +2267,7 @@
WireFormat::TagSize(field->number(), field->type());
std::map<std::string, std::string> vars;
- if (field->containing_oneof() != NULL) {
+ if (field->real_containing_oneof()) {
vars["name"] = field->containing_oneof()->name();
vars["presence"] = StrCat(field->containing_oneof()->index());
} else {
@@ -2375,7 +2387,7 @@
io::Printer* printer) {
Formatter format(printer, variables_);
- if (HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)) {
+ if (!has_bit_indices_.empty() || IsMapEntryMessage(descriptor_)) {
format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n");
} else {
format("~0u, // no _has_bits_\n");
@@ -2386,7 +2398,7 @@
} else {
format("~0u, // no _extensions_\n");
}
- if (descriptor_->oneof_decl_count() > 0) {
+ if (descriptor_->real_oneof_decl_count() > 0) {
format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_[0]),\n");
} else {
format("~0u, // no _oneof_case_\n");
@@ -2396,12 +2408,21 @@
} else {
format("~0u, // no _weak_field_map_\n");
}
+ int num_stripped = 0;
+ for (auto field : FieldRange(descriptor_)) {
+ if (!IsFieldUsed(field, options_)) {
+ num_stripped++;
+ }
+ }
const int kNumGenericOffsets = 5; // the number of fixed offsets above
const size_t offsets = kNumGenericOffsets + descriptor_->field_count() +
- descriptor_->oneof_decl_count();
+ descriptor_->real_oneof_decl_count() - num_stripped;
size_t entries = offsets;
for (auto field : FieldRange(descriptor_)) {
- if (field->containing_oneof() || field->options().weak()) {
+ if (!IsFieldUsed(field, options_)) {
+ continue;
+ }
+ if (field->real_containing_oneof() || field->options().weak()) {
format("offsetof($classtype$DefaultTypeInternal, $1$_)",
FieldName(field));
} else {
@@ -2416,18 +2437,24 @@
format(",\n");
}
+ int count = 0;
for (auto oneof : OneOfRange(descriptor_)) {
format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_),\n", oneof->name());
+ count++;
}
+ GOOGLE_CHECK_EQ(count, descriptor_->real_oneof_decl_count());
if (IsMapEntryMessage(descriptor_)) {
entries += 2;
format(
"0,\n"
"1,\n");
- } else if (HasFieldPresence(descriptor_->file())) {
- entries += has_bit_indices_.size();
+ } else if (!has_bit_indices_.empty()) {
+ entries += has_bit_indices_.size() - num_stripped;
for (int i = 0; i < has_bit_indices_.size(); i++) {
+ if (!IsFieldUsed(descriptor_->field(i), options_)) {
+ continue;
+ }
const std::string index =
has_bit_indices_[i] >= 0 ? StrCat(has_bit_indices_[i]) : "~0u";
format("$1$,\n", index);
@@ -2465,7 +2492,7 @@
format("void $classname$::SharedDtor() {\n");
format.Indent();
if (SupportsArenas(descriptor_)) {
- format("$DCHK$(GetArenaNoVirtual() == nullptr);\n");
+ format("$DCHK$(GetArena() == nullptr);\n");
}
// Write the destructors for each field except oneof members.
// optimized_order_ does not contain oneof fields.
@@ -2522,7 +2549,8 @@
// and returns false for oneof fields.
for (auto oneof : OneOfRange(descriptor_)) {
for (auto field : FieldRange(oneof)) {
- if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) {
+ if (IsFieldUsed(field, options_) &&
+ field_generators_.get(field).GenerateArenaDestructorCode(printer)) {
need_registration = true;
}
}
@@ -2556,25 +2584,13 @@
std::vector<bool> processed,
bool copy_constructor) const {
Formatter format(printer, variables_);
- const FieldDescriptor* last_start = NULL;
- // RunMap maps from fields that start each run to the number of fields in that
- // run. This is optimized for the common case that there are very few runs in
- // a message and that most of the eligible fields appear together.
- typedef std::unordered_map<const FieldDescriptor*, size_t> RunMap;
- RunMap runs;
- for (auto field : optimized_order_) {
- if ((copy_constructor && IsPOD(field)) ||
- (!copy_constructor && CanConstructByZeroing(field, options_))) {
- if (last_start == NULL) {
- last_start = field;
- }
-
- runs[last_start]++;
- } else {
- last_start = NULL;
- }
- }
+ const RunMap runs = FindRuns(
+ optimized_order_, [copy_constructor, this](const FieldDescriptor* field) {
+ return (copy_constructor && IsPOD(field)) ||
+ (!copy_constructor &&
+ CanBeManipulatedAsRawBytes(field, options_));
+ });
std::string pod_template;
if (copy_constructor) {
@@ -2595,7 +2611,7 @@
}
const FieldDescriptor* field = optimized_order_[i];
- RunMap::const_iterator it = runs.find(field);
+ const auto 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.
@@ -2628,18 +2644,17 @@
std::string superclass;
superclass = SuperClassName(descriptor_, options_);
- std::string initializer_with_arena = superclass + "()";
+ std::string initializer_with_arena = superclass + "(arena)";
if (descriptor_->extension_range_count() > 0) {
initializer_with_arena += ",\n _extensions_(arena)";
}
- initializer_with_arena += ",\n _internal_metadata_(arena)";
-
// Initialize member variables with arena constructor.
for (auto field : optimized_order_) {
+ GOOGLE_DCHECK(IsFieldUsed(field, options_));
bool has_arena_constructor = field->is_repeated();
- if (field->containing_oneof() == NULL &&
+ if (!field->real_containing_oneof() &&
(IsLazy(field, options_) || IsStringPiece(field, options_))) {
has_arena_constructor = true;
}
@@ -2656,8 +2671,7 @@
initializer_with_arena += ", _weak_field_map_(arena)";
}
- std::string initializer_null =
- superclass + "(), _internal_metadata_(nullptr)";
+ std::string initializer_null = superclass + "()";
if (IsAnyMessage(descriptor_, options_)) {
initializer_null += ", _any_metadata_(&type_url_, &value_)";
}
@@ -2665,14 +2679,6 @@
initializer_null += ", _weak_field_map_(nullptr)";
}
- format(
- "$classname$::$classname$()\n"
- " : $1$ {\n"
- " SharedCtor();\n"
- " // @@protoc_insertion_point(constructor:$full_name$)\n"
- "}\n",
- initializer_null);
-
if (SupportsArenas(descriptor_)) {
format(
"$classname$::$classname$(::$proto_ns$::Arena* arena)\n"
@@ -2682,8 +2688,20 @@
" // @@protoc_insertion_point(arena_constructor:$full_name$)\n"
"}\n",
initializer_with_arena);
+ } else {
+ format(
+ "$classname$::$classname$()\n"
+ " : $1$ {\n"
+ " SharedCtor();\n"
+ " // @@protoc_insertion_point(constructor:$full_name$)\n"
+ "}\n",
+ initializer_null);
}
+ std::map<std::string, std::string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ format.AddMap(vars);
+
// Generate the copy constructor.
if (UsingImplicitWeakFields(descriptor_->file(), options_)) {
// If we are in lite mode and using implicit weak fields, we generate a
@@ -2702,12 +2720,9 @@
format.Indent();
format.Indent();
format.Indent();
- format(",\n_internal_metadata_(nullptr)");
- if (HasFieldPresence(descriptor_->file())) {
- if (!IsProto2MessageSet(descriptor_, options_)) {
- format(",\n_has_bits_(from._has_bits_)");
- }
+ if (!has_bit_indices_.empty()) {
+ format(",\n_has_bits_(from._has_bits_)");
}
std::vector<bool> processed(optimized_order_.size(), false);
@@ -2733,7 +2748,9 @@
format.Outdent();
format(" {\n");
- format("_internal_metadata_.MergeFrom(from._internal_metadata_);\n");
+ format(
+ "_internal_metadata_.MergeFrom<$unknown_fields_type$>(from._internal_"
+ "metadata_);\n");
if (descriptor_->extension_range_count() > 0) {
format("_extensions_.MergeFrom(from._extensions_);\n");
@@ -2751,7 +2768,9 @@
for (auto field : FieldRange(oneof)) {
format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
format.Indent();
- field_generators_.get(field).GenerateMergingCode(printer);
+ if (IsFieldUsed(field, options_)) {
+ field_generators_.get(field).GenerateMergingCode(printer);
+ }
format("break;\n");
format.Outdent();
format("}\n");
@@ -2780,6 +2799,7 @@
"$classname$::~$classname$() {\n"
" // @@protoc_insertion_point(destructor:$full_name$)\n"
" SharedDtor();\n"
+ " _internal_metadata_.Delete<$unknown_fields_type$>();\n"
"}\n"
"\n");
@@ -2819,7 +2839,9 @@
void MessageGenerator::GenerateClear(io::Printer* printer) {
Formatter format(printer, variables_);
- // Performance tuning parameters
+
+ // The maximum number of bytes we will memset to zero without checking their
+ // hasbit to see if a zero-init is necessary.
const int kMaxUnconditionalPrimitiveBytesClear = 4;
format(
@@ -2834,162 +2856,118 @@
"// Prevent compiler warnings about cached_has_bits being unused\n"
"(void) cached_has_bits;\n\n");
- int cached_has_bit_index = -1;
-
- // Step 1: Extensions
if (descriptor_->extension_range_count() > 0) {
format("_extensions_.Clear();\n");
}
- int unconditional_budget = kMaxUnconditionalPrimitiveBytesClear;
- for (int i = 0; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
-
- if (!CanInitializeByZeroing(field)) {
- continue;
+ // Collect fields into chunks. Each chunk may have an if() condition that
+ // checks all hasbits in the chunk and skips it if none are set.
+ int zero_init_bytes = 0;
+ for (const auto& field : optimized_order_) {
+ if (CanInitializeByZeroing(field)) {
+ zero_init_bytes += EstimateAlignmentSize(field);
}
-
- unconditional_budget -= EstimateAlignmentSize(field);
}
+ bool merge_zero_init = zero_init_bytes > kMaxUnconditionalPrimitiveBytesClear;
+ int chunk_count = 0;
- std::vector<std::vector<const FieldDescriptor*>> chunks_frag = CollectFields(
+ std::vector<std::vector<const FieldDescriptor*>> chunks = CollectFields(
optimized_order_,
- MatchRepeatedAndHasByteAndZeroInits(
- &has_bit_indices_, HasFieldPresence(descriptor_->file())));
+ [&](const FieldDescriptor* a, const FieldDescriptor* b) -> bool {
+ chunk_count++;
+ // This predicate guarantees that there is only a single zero-init
+ // (memset) per chunk, and if present it will be at the beginning.
+ bool same = HasByteIndex(a) == HasByteIndex(b) &&
+ a->is_repeated() == b->is_repeated() &&
+ (CanInitializeByZeroing(a) == CanInitializeByZeroing(b) ||
+ (CanInitializeByZeroing(a) &&
+ (chunk_count == 1 || merge_zero_init)));
+ if (!same) chunk_count = 0;
+ return same;
+ });
- // Merge next non-zero initializable chunk if it has the same has_byte index
- // and not meeting unconditional clear condition.
- std::vector<std::vector<const FieldDescriptor*>> chunks;
- if (!HasFieldPresence(descriptor_->file())) {
- // Don't bother with merging without has_bit field.
- chunks = chunks_frag;
- } else {
- // Note that only the next chunk is considered for merging.
- for (int i = 0; i < chunks_frag.size(); i++) {
- chunks.push_back(chunks_frag[i]);
- const FieldDescriptor* field = chunks_frag[i].front();
- const FieldDescriptor* next_field =
- (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : nullptr;
- if (CanInitializeByZeroing(field) &&
- (chunks_frag[i].size() == 1 || unconditional_budget < 0) &&
- next_field != nullptr &&
- has_bit_indices_[field->index()] / 8 ==
- has_bit_indices_[next_field->index()] / 8) {
- GOOGLE_CHECK(!CanInitializeByZeroing(next_field));
- // Insert next chunk to the current one and skip next chunk.
- chunks.back().insert(chunks.back().end(), chunks_frag[i + 1].begin(),
- chunks_frag[i + 1].end());
- i++;
- }
- }
- }
+ ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio);
+ int cached_has_word_index = -1;
- ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio,
- HasFieldPresence(descriptor_->file()));
for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
- GOOGLE_CHECK(!chunk.empty());
+ cold_skipper.OnStartChunk(chunk_index, cached_has_word_index, "", printer);
- // Step 2: Repeated fields don't use _has_bits_; emit code to clear them
- // here.
- if (chunk.front()->is_repeated()) {
- for (int i = 0; i < chunk.size(); i++) {
- const FieldDescriptor* field = chunk[i];
- const FieldGenerator& generator = field_generators_.get(field);
+ const FieldDescriptor* memset_start = nullptr;
+ const FieldDescriptor* memset_end = nullptr;
+ bool saw_non_zero_init = false;
- generator.GenerateMessageClearingCode(printer);
- }
- continue;
- }
-
- cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer);
-
- // Step 3: Non-repeated fields that can be cleared by memset-to-0, then
- // non-repeated, non-zero initializable fields.
- int last_chunk = HasFieldPresence(descriptor_->file())
- ? has_bit_indices_[chunk.front()->index()] / 8
- : 0;
- int last_chunk_start = 0;
- int memset_run_start = -1;
- int memset_run_end = -1;
-
- for (int i = 0; i < chunk.size(); i++) {
- const FieldDescriptor* field = chunk[i];
+ for (const auto& field : chunk) {
if (CanInitializeByZeroing(field)) {
- if (memset_run_start == -1) {
- memset_run_start = i;
- }
- memset_run_end = i;
+ GOOGLE_CHECK(!saw_non_zero_init);
+ if (!memset_start) memset_start = field;
+ memset_end = field;
+ } else {
+ saw_non_zero_init = true;
}
}
- const bool have_outer_if =
- HasFieldPresence(descriptor_->file()) && chunk.size() > 1 &&
- (memset_run_end != chunk.size() - 1 || unconditional_budget < 0);
+ // Whether we wrap this chunk in:
+ // if (cached_has_bits & <chunk hasbits) { /* chunk. */ }
+ // We can omit the if() for chunk size 1, or if our fields do not have
+ // hasbits. I don't understand the rationale for the last part of the
+ // condition, but it matches the old logic.
+ const bool have_outer_if = HasBitIndex(chunk.front()) != kNoHasbit &&
+ chunk.size() > 1 &&
+ (memset_end != chunk.back() || merge_zero_init);
if (have_outer_if) {
- uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
- const int count = popcnt(last_chunk_mask);
+ // Emit an if() that will let us skip the whole chunk if none are set.
+ uint32 chunk_mask = GenChunkMask(chunk, has_bit_indices_);
+ std::string chunk_mask_str =
+ StrCat(strings::Hex(chunk_mask, strings::ZERO_PAD_8));
// Check (up to) 8 has_bits at a time if we have more than one field in
// this chunk. Due to field layout ordering, we may check
// _has_bits_[last_chunk * 8 / 32] multiple times.
- GOOGLE_DCHECK_LE(2, count);
- GOOGLE_DCHECK_GE(8, count);
+ GOOGLE_DCHECK_LE(2, popcnt(chunk_mask));
+ GOOGLE_DCHECK_GE(8, popcnt(chunk_mask));
- if (cached_has_bit_index != last_chunk / 4) {
- cached_has_bit_index = last_chunk / 4;
- format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index);
+ if (cached_has_word_index != HasWordIndex(chunk.front())) {
+ cached_has_word_index = HasWordIndex(chunk.front());
+ format("cached_has_bits = _has_bits_[$1$];\n", cached_has_word_index);
}
- format("if (cached_has_bits & 0x$1$u) {\n",
- StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
+ format("if (cached_has_bits & 0x$1$u) {\n", chunk_mask_str);
format.Indent();
}
- if (memset_run_start != -1) {
- if (memset_run_start == memset_run_end) {
+ if (memset_start) {
+ if (memset_start == memset_end) {
// For clarity, do not memset a single field.
- const FieldGenerator& generator =
- field_generators_.get(chunk[memset_run_start]);
- generator.GenerateMessageClearingCode(printer);
+ field_generators_.get(memset_start)
+ .GenerateMessageClearingCode(printer);
} else {
- const std::string first_field_name = FieldName(chunk[memset_run_start]);
- const std::string last_field_name = FieldName(chunk[memset_run_end]);
-
format(
"::memset(&$1$_, 0, static_cast<size_t>(\n"
" reinterpret_cast<char*>(&$2$_) -\n"
" reinterpret_cast<char*>(&$1$_)) + sizeof($2$_));\n",
- first_field_name, last_field_name);
+ FieldName(memset_start), FieldName(memset_end));
}
-
- // Advance last_chunk_start to skip over the fields we zeroed/memset.
- last_chunk_start = memset_run_end + 1;
}
- // Go back and emit clears for each of the fields we processed.
- for (int j = last_chunk_start; j < chunk.size(); j++) {
- const FieldDescriptor* field = chunk[j];
- const FieldGenerator& generator = field_generators_.get(field);
-
+ // Clear all non-zero-initializable fields in the chunk.
+ for (const auto& field : chunk) {
+ if (CanInitializeByZeroing(field)) continue;
// It's faster to just overwrite primitive types, but we should only
// clear strings and messages if they were set.
//
// TODO(kenton): Let the CppFieldGenerator decide this somehow.
- bool should_check_bit =
- field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
- field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
+ bool have_enclosing_if =
+ HasBitIndex(field) != kNoHasbit &&
+ (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
+ field->cpp_type() == FieldDescriptor::CPPTYPE_STRING);
- bool have_enclosing_if = false;
- if (should_check_bit &&
- // If no field presence, then always clear strings/messages as well.
- HasFieldPresence(descriptor_->file())) {
+ if (have_enclosing_if) {
PrintPresenceCheck(format, field, has_bit_indices_, printer,
- &cached_has_bit_index);
- have_enclosing_if = true;
+ &cached_has_word_index);
}
- generator.GenerateMessageClearingCode(printer);
+ field_generators_.get(field).GenerateMessageClearingCode(printer);
if (have_enclosing_if) {
format.Outdent();
@@ -3004,7 +2982,7 @@
if (cold_skipper.OnEndChunk(chunk_index, printer)) {
// Reset here as it may have been updated in just closed if statement.
- cached_has_bit_index = -1;
+ cached_has_word_index = -1;
}
}
@@ -3017,12 +2995,15 @@
format("_weak_field_map_.ClearAll();\n");
}
- if (HasFieldPresence(descriptor_->file())) {
+ if (!has_bit_indices_.empty()) {
// Step 5: Everything else.
format("_has_bits_.Clear();\n");
}
- format("_internal_metadata_.Clear();\n");
+ std::map<std::string, std::string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ format.AddMap(vars);
+ format("_internal_metadata_.Clear<$unknown_fields_type$>();\n");
format.Outdent();
format("}\n");
@@ -3030,8 +3011,8 @@
void MessageGenerator::GenerateOneofClear(io::Printer* printer) {
// Generated function clears the active field and union case (e.g. foo_case_).
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- auto oneof = descriptor_->oneof_decl(i);
+ int i = 0;
+ for (auto oneof : OneOfRange(descriptor_)) {
Formatter format(printer, variables_);
format.Set("oneofname", oneof->name());
@@ -3045,7 +3026,7 @@
format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
format.Indent();
// We clear only allocated objects in oneofs
- if (!IsStringOrMessage(field)) {
+ if (!IsStringOrMessage(field) || !IsFieldUsed(field, options_)) {
format("// No need to clear\n");
} else {
field_generators_.get(field).GenerateClearingCode(printer);
@@ -3068,6 +3049,7 @@
format(
"}\n"
"\n");
+ i++;
}
}
@@ -3083,26 +3065,62 @@
format("_extensions_.Swap(&other->_extensions_);\n");
}
- format("_internal_metadata_.Swap(&other->_internal_metadata_);\n");
+ std::map<std::string, std::string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ format.AddMap(vars);
+ format(
+ "_internal_metadata_.Swap<$unknown_fields_type$>(&other->_internal_"
+ "metadata_);\n");
- if (HasFieldPresence(descriptor_->file())) {
+ if (!has_bit_indices_.empty()) {
for (int i = 0; i < HasBitsSize() / 4; ++i) {
format("swap(_has_bits_[$1$], other->_has_bits_[$1$]);\n", i);
}
}
- for (int i = 0; i < optimized_order_.size(); i++) {
- // optimized_order_ does not contain oneof fields, but the field
- // generators for these fields do not emit swapping code on their own.
+ // If possible, we swap several fields at once, including padding.
+ const RunMap runs =
+ FindRuns(optimized_order_, [this](const FieldDescriptor* field) {
+ return CanBeManipulatedAsRawBytes(field, options_);
+ });
+
+ for (int i = 0; i < optimized_order_.size(); ++i) {
const FieldDescriptor* field = optimized_order_[i];
- field_generators_.get(field).GenerateSwappingCode(printer);
+ const auto it = runs.find(field);
+
+ // We only apply the memswap technique to runs of more than one field, as
+ // `swap(field_, other.field_)` is better than
+ // `memswap<...>(&field_, &other.field_)` for generated code readability.
+ if (it != runs.end() && it->second > 1) {
+ // Use a memswap, then skip run_length fields.
+ const size_t run_length = it->second;
+ const std::string first_field_name = FieldName(field);
+ const std::string last_field_name =
+ FieldName(optimized_order_[i + run_length - 1]);
+
+ format.Set("first", first_field_name);
+ format.Set("last", last_field_name);
+
+ format(
+ "::PROTOBUF_NAMESPACE_ID::internal::memswap<\n"
+ " PROTOBUF_FIELD_OFFSET($classname$, $last$_)\n"
+ " + sizeof($classname$::$last$_)\n"
+ " - PROTOBUF_FIELD_OFFSET($classname$, $first$_)>(\n"
+ " reinterpret_cast<char*>(&$first$_),\n"
+ " reinterpret_cast<char*>(&other->$first$_));\n");
+
+ i += run_length - 1;
+ // ++i at the top of the loop.
+ } else {
+ field_generators_.get(field).GenerateSwappingCode(printer);
+ }
}
for (auto oneof : OneOfRange(descriptor_)) {
format("swap($1$_, other->$1$_);\n", oneof->name());
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
+ for (int i = 0; i < descriptor_->real_oneof_decl_count(); i++) {
format("swap(_oneof_case_[$1$], other->_oneof_case_[$1$]);\n", i);
}
@@ -3148,7 +3166,7 @@
"}\n");
format.Outdent();
- format("}\n\n");
+ format("}\n");
} else {
// Generate CheckTypeAndMergeFrom().
format(
@@ -3156,11 +3174,13 @@
" const ::$proto_ns$::MessageLite& from) {\n"
" MergeFrom(*::$proto_ns$::internal::DownCast<const $classname$*>(\n"
" &from));\n"
- "}\n"
- "\n");
+ "}\n");
}
+}
+void MessageGenerator::GenerateClassSpecificMergeFrom(io::Printer* printer) {
// Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
+ Formatter format(printer, variables_);
format(
"void $classname$::MergeFrom(const $classname$& from) {\n"
"// @@protoc_insertion_point(class_specific_merge_from_start:"
@@ -3171,91 +3191,94 @@
if (descriptor_->extension_range_count() > 0) {
format("_extensions_.MergeFrom(from._extensions_);\n");
}
-
+ std::map<std::string, std::string> vars;
+ SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ format.AddMap(vars);
format(
- "_internal_metadata_.MergeFrom(from._internal_metadata_);\n"
+ "_internal_metadata_.MergeFrom<$unknown_fields_type$>(from._internal_"
+ "metadata_);\n"
"$uint32$ cached_has_bits = 0;\n"
"(void) cached_has_bits;\n\n");
- if (HasFieldPresence(descriptor_->file())) {
- std::vector<std::vector<const FieldDescriptor*>> chunks = CollectFields(
- optimized_order_, MatchRepeatedAndHasByte(&has_bit_indices_, true));
+ std::vector<std::vector<const FieldDescriptor*>> chunks = CollectFields(
+ optimized_order_,
+ [&](const FieldDescriptor* a, const FieldDescriptor* b) -> bool {
+ return HasByteIndex(a) == HasByteIndex(b);
+ });
- ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_,
- kColdRatio, true);
+ ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio);
- // cached_has_bit_index maintains that:
- // cached_has_bits = from._has_bits_[cached_has_bit_index]
- // for cached_has_bit_index >= 0
- int cached_has_bit_index = -1;
+ // cached_has_word_index maintains that:
+ // cached_has_bits = from._has_bits_[cached_has_word_index]
+ // for cached_has_word_index >= 0
+ int cached_has_word_index = -1;
- for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
- const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
- GOOGLE_CHECK(!chunk.empty());
+ for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
+ const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
+ bool have_outer_if =
+ chunk.size() > 1 && HasByteIndex(chunk.front()) != kNoHasbit;
+ cold_skipper.OnStartChunk(chunk_index, cached_has_word_index, "from.",
+ printer);
- // Merge Repeated fields. These fields do not require a
- // check as we can simply iterate over them.
- if (chunk.front()->is_repeated()) {
- for (int i = 0; i < chunk.size(); i++) {
- const FieldDescriptor* field = chunk[i];
+ if (have_outer_if) {
+ // Emit an if() that will let us skip the whole chunk if none are set.
+ uint32 chunk_mask = GenChunkMask(chunk, has_bit_indices_);
+ std::string chunk_mask_str =
+ StrCat(strings::Hex(chunk_mask, strings::ZERO_PAD_8));
- const FieldGenerator& generator = field_generators_.get(field);
- generator.GenerateMergingCode(printer);
- }
- continue;
+ // Check (up to) 8 has_bits at a time if we have more than one field in
+ // this chunk. Due to field layout ordering, we may check
+ // _has_bits_[last_chunk * 8 / 32] multiple times.
+ GOOGLE_DCHECK_LE(2, popcnt(chunk_mask));
+ GOOGLE_DCHECK_GE(8, popcnt(chunk_mask));
+
+ if (cached_has_word_index != HasWordIndex(chunk.front())) {
+ cached_has_word_index = HasWordIndex(chunk.front());
+ format("cached_has_bits = from._has_bits_[$1$];\n",
+ cached_has_word_index);
}
- // Merge Optional and Required fields (after a _has_bit_ check).
- cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "from.",
- printer);
+ format("if (cached_has_bits & 0x$1$u) {\n", chunk_mask_str);
+ format.Indent();
+ }
- int last_chunk = has_bit_indices_[chunk.front()->index()] / 8;
- GOOGLE_DCHECK_NE(-1, last_chunk);
+ // Go back and emit merging code for each of the fields we processed.
+ bool deferred_has_bit_changes = false;
+ for (const auto field : chunk) {
+ const FieldGenerator& generator = field_generators_.get(field);
- const bool have_outer_if = chunk.size() > 1;
- if (have_outer_if) {
- uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
- const int count = popcnt(last_chunk_mask);
-
- // Check (up to) 8 has_bits at a time if we have more than one field in
- // this chunk. Due to field layout ordering, we may check
- // _has_bits_[last_chunk * 8 / 32] multiple times.
- GOOGLE_DCHECK_LE(2, count);
- GOOGLE_DCHECK_GE(8, count);
-
- if (cached_has_bit_index != last_chunk / 4) {
- cached_has_bit_index = last_chunk / 4;
- format("cached_has_bits = from._has_bits_[$1$];\n",
- cached_has_bit_index);
+ if (field->is_repeated()) {
+ generator.GenerateMergingCode(printer);
+ } else if (field->is_optional() && !HasHasbit(field)) {
+ // Merge semantics without true field presence: primitive fields are
+ // merged only if non-zero (numeric) or non-empty (string).
+ bool have_enclosing_if =
+ EmitFieldNonDefaultCondition(printer, "from.", field);
+ generator.GenerateMergingCode(printer);
+ if (have_enclosing_if) {
+ format.Outdent();
+ format("}\n");
}
- format("if (cached_has_bits & 0x$1$u) {\n",
- StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
+ } else if (field->options().weak() ||
+ cached_has_word_index != HasWordIndex(field)) {
+ // Check hasbit, not using cached bits.
+ GOOGLE_CHECK(HasHasbit(field));
+ format("if (from._internal_has_$1$()) {\n", FieldName(field));
format.Indent();
- }
-
- // Go back and emit merging code for each of the fields we processed.
- bool deferred_has_bit_changes = false;
- for (const auto field : chunk) {
- const FieldGenerator& generator = field_generators_.get(field);
-
- // Attempt to use the state of cached_has_bits, if possible.
+ generator.GenerateMergingCode(printer);
+ format.Outdent();
+ format("}\n");
+ } else {
+ // Check hasbit, using cached bits.
+ GOOGLE_CHECK(HasHasbit(field));
int has_bit_index = has_bit_indices_[field->index()];
- if (!field->options().weak() &&
- cached_has_bit_index == has_bit_index / 32) {
- const std::string mask = StrCat(
- strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
-
- format("if (cached_has_bits & 0x$1$u) {\n", mask);
- } else {
- format("if (from._internal_has_$1$()) {\n", FieldName(field));
- }
+ const std::string mask = StrCat(
+ strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
+ format("if (cached_has_bits & 0x$1$u) {\n", mask);
format.Indent();
if (have_outer_if && IsPOD(field)) {
- // GenerateCopyConstructorCode for enum and primitive scalar fields
- // does not do _has_bits_ modifications. We defer _has_bits_
- // manipulation until the end of the outer if.
- //
+ // Defer hasbit modification until the end of chunk.
// This can reduce the number of loads/stores by up to 7 per 8 fields.
deferred_has_bit_changes = true;
generator.GenerateCopyConstructorCode(printer);
@@ -3266,38 +3289,22 @@
format.Outdent();
format("}\n");
}
-
- if (have_outer_if) {
- if (deferred_has_bit_changes) {
- // Flush the has bits for the primitives we deferred.
- GOOGLE_CHECK_LE(0, cached_has_bit_index);
- format("_has_bits_[$1$] |= cached_has_bits;\n", cached_has_bit_index);
- }
-
- format.Outdent();
- format("}\n");
- }
-
- if (cold_skipper.OnEndChunk(chunk_index, printer)) {
- // Reset here as it may have been updated in just closed if statement.
- cached_has_bit_index = -1;
- }
}
- } else {
- // proto3
- for (const auto field : optimized_order_) {
- const FieldGenerator& generator = field_generators_.get(field);
- // Merge semantics without true field presence: primitive fields are
- // merged only if non-zero (numeric) or non-empty (string).
- bool have_enclosing_if =
- EmitFieldNonDefaultCondition(printer, "from.", field);
- generator.GenerateMergingCode(printer);
-
- if (have_enclosing_if) {
- format.Outdent();
- format("}\n");
+ if (have_outer_if) {
+ if (deferred_has_bit_changes) {
+ // Flush the has bits for the primitives we deferred.
+ GOOGLE_CHECK_LE(0, cached_has_word_index);
+ format("_has_bits_[$1$] |= cached_has_bits;\n", cached_has_word_index);
}
+
+ format.Outdent();
+ format("}\n");
+ }
+
+ if (cold_skipper.OnEndChunk(chunk_index, printer)) {
+ // Reset here as it may have been updated in just closed if statement.
+ cached_has_word_index = -1;
}
}
@@ -3308,7 +3315,9 @@
for (auto field : FieldRange(oneof)) {
format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
format.Indent();
- field_generators_.get(field).GenerateMergingCode(printer);
+ if (IsFieldUsed(field, options_)) {
+ field_generators_.get(field).GenerateMergingCode(printer);
+ }
format("break;\n");
format.Outdent();
format("}\n");
@@ -3455,9 +3464,9 @@
bool have_enclosing_if = false;
if (field->options().weak()) {
- } else if (!field->is_repeated() && HasFieldPresence(descriptor_->file())) {
+ } else if (HasHasbit(field)) {
// Attempt to use the state of cached_has_bits, if possible.
- int has_bit_index = has_bit_indices_[field->index()];
+ int has_bit_index = HasBitIndex(field);
if (cached_has_bits_index == has_bit_index / 32) {
const std::string mask =
StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
@@ -3469,7 +3478,7 @@
format.Indent();
have_enclosing_if = true;
- } else if (!HasFieldPresence(descriptor_->file())) {
+ } else if (field->is_optional() && !HasHasbit(field)) {
have_enclosing_if = EmitFieldNonDefaultCondition(printer, "this->", field);
}
@@ -3550,7 +3559,7 @@
: mg_(mg),
format_(printer),
eager_(!HasFieldPresence(mg->descriptor_->file())),
- cached_has_bit_index_(-1) {}
+ cached_has_bit_index_(kNoHasbit) {}
~LazySerializerEmitter() { Flush(); }
@@ -3560,7 +3569,7 @@
if (eager_ || MustFlush(field)) {
Flush();
}
- if (field->containing_oneof() == NULL) {
+ if (!field->real_containing_oneof()) {
// TODO(ckennelly): Defer non-oneof fields similarly to oneof fields.
if (!field->options().weak() && !field->is_repeated() && !eager_) {
@@ -3642,6 +3651,9 @@
(i < descriptor_->field_count() &&
ordered_fields[i]->number() < sorted_extensions[j]->start)) {
const FieldDescriptor* field = ordered_fields[i++];
+ if (!IsFieldUsed(field, options_)) {
+ continue;
+ }
if (field->options().weak()) {
last_weak_field = field;
PrintFieldComment(format, field);
@@ -3701,29 +3713,6 @@
return masks;
}
-// Create an expression that evaluates to
-// "for all i, (_has_bits_[i] & masks[i]) == masks[i]"
-// masks is allowed to be shorter than _has_bits_, but at least one element of
-// masks must be non-zero.
-static std::string ConditionalToCheckBitmasks(
- const std::vector<uint32>& masks) {
- std::vector<std::string> parts;
- for (int i = 0; i < masks.size(); i++) {
- if (masks[i] == 0) continue;
- std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
- // Each xor evaluates to 0 if the expected bits are present.
- parts.push_back(
- StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")"));
- }
- GOOGLE_CHECK(!parts.empty());
- // If we have multiple parts, each expected to be 0, then bitwise-or them.
- std::string result =
- parts.size() == 1
- ? parts[0]
- : StrCat("(", Join(parts, "\n | "), ")");
- return result + " == 0";
-}
-
void MessageGenerator::GenerateByteSize(io::Printer* printer) {
Formatter format(printer, variables_);
@@ -3748,7 +3737,7 @@
return;
}
- if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
+ if (num_required_fields_ > 1) {
// Emit a function (rarely used, we hope) that handles the required fields
// by checking for each one individually.
format(
@@ -3798,7 +3787,7 @@
// Handle required fields (if any). We expect all of them to be
// present, so emit one conditional that checks for that. If they are all
// present then the fast path executes; otherwise the slow path executes.
- if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
+ if (num_required_fields_ > 1) {
// The fast path works if all required fields are present.
const std::vector<uint32> masks_for_has_bits = RequiredFieldsBitMask();
format("if ($1$) { // All required fields are present.\n",
@@ -3832,75 +3821,45 @@
std::vector<std::vector<const FieldDescriptor*>> chunks = CollectFields(
optimized_order_,
- MatchRepeatedAndHasByteAndRequired(
- &has_bit_indices_, HasFieldPresence(descriptor_->file())));
+ [&](const FieldDescriptor* a, const FieldDescriptor* b) -> bool {
+ return a->label() == b->label() && HasByteIndex(a) == HasByteIndex(b);
+ });
// Remove chunks with required fields.
chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired),
chunks.end());
- ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio,
- HasFieldPresence(descriptor_->file()));
+ ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio);
+ int cached_has_word_index = -1;
format(
"$uint32$ cached_has_bits = 0;\n"
"// Prevent compiler warnings about cached_has_bits being unused\n"
"(void) cached_has_bits;\n\n");
- int cached_has_bit_index = -1;
-
for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
- GOOGLE_CHECK(!chunk.empty());
-
- // Handle repeated fields.
- if (chunk.front()->is_repeated()) {
- for (int i = 0; i < chunk.size(); i++) {
- const FieldDescriptor* field = chunk[i];
-
- PrintFieldComment(format, field);
- const FieldGenerator& generator = field_generators_.get(field);
- generator.GenerateByteSize(printer);
- format("\n");
- }
- continue;
- }
-
- cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer);
-
- // Handle optional (non-repeated/oneof) fields.
- //
- // These are handled in chunks of 8. The first chunk is
- // the non-requireds-non-repeateds-non-unions-non-extensions in
- // descriptor_->field(0), descriptor_->field(1), ... descriptor_->field(7),
- // and the second chunk is the same for
- // descriptor_->field(8), descriptor_->field(9), ...
- // descriptor_->field(15),
- // etc.
- int last_chunk = HasFieldPresence(descriptor_->file())
- ? has_bit_indices_[chunk.front()->index()] / 8
- : 0;
- GOOGLE_DCHECK_NE(-1, last_chunk);
-
const bool have_outer_if =
- HasFieldPresence(descriptor_->file()) && chunk.size() > 1;
+ chunk.size() > 1 && HasWordIndex(chunk[0]) != kNoHasbit;
+ cold_skipper.OnStartChunk(chunk_index, cached_has_word_index, "", printer);
if (have_outer_if) {
- uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
- const int count = popcnt(last_chunk_mask);
+ // Emit an if() that will let us skip the whole chunk if none are set.
+ uint32 chunk_mask = GenChunkMask(chunk, has_bit_indices_);
+ std::string chunk_mask_str =
+ StrCat(strings::Hex(chunk_mask, strings::ZERO_PAD_8));
// Check (up to) 8 has_bits at a time if we have more than one field in
// this chunk. Due to field layout ordering, we may check
// _has_bits_[last_chunk * 8 / 32] multiple times.
- GOOGLE_DCHECK_LE(2, count);
- GOOGLE_DCHECK_GE(8, count);
+ GOOGLE_DCHECK_LE(2, popcnt(chunk_mask));
+ GOOGLE_DCHECK_GE(8, popcnt(chunk_mask));
- if (cached_has_bit_index != last_chunk / 4) {
- cached_has_bit_index = last_chunk / 4;
- format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index);
+ if (cached_has_word_index != HasWordIndex(chunk.front())) {
+ cached_has_word_index = HasWordIndex(chunk.front());
+ format("cached_has_bits = _has_bits_[$1$];\n", cached_has_word_index);
}
- format("if (cached_has_bits & 0x$1$u) {\n",
- StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
+ format("if (cached_has_bits & 0x$1$u) {\n", chunk_mask_str);
format.Indent();
}
@@ -3908,13 +3867,17 @@
for (int j = 0; j < chunk.size(); j++) {
const FieldDescriptor* field = chunk[j];
const FieldGenerator& generator = field_generators_.get(field);
+ bool have_enclosing_if = false;
+ bool need_extra_newline = false;
PrintFieldComment(format, field);
- bool have_enclosing_if = false;
- if (HasFieldPresence(descriptor_->file())) {
+ if (field->is_repeated()) {
+ // No presence check is required.
+ need_extra_newline = true;
+ } else if (HasHasbit(field)) {
PrintPresenceCheck(format, field, has_bit_indices_, printer,
- &cached_has_bit_index);
+ &cached_has_word_index);
have_enclosing_if = true;
} else {
// Without field presence: field is serialized only if it has a
@@ -3931,6 +3894,9 @@
"}\n"
"\n");
}
+ if (need_extra_newline) {
+ format("\n");
+ }
}
if (have_outer_if) {
@@ -3940,7 +3906,7 @@
if (cold_skipper.OnEndChunk(chunk_index, printer)) {
// Reset here as it may have been updated in just closed if statement.
- cached_has_bit_index = -1;
+ cached_has_word_index = -1;
}
}
@@ -3953,7 +3919,9 @@
PrintFieldComment(format, field);
format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
format.Indent();
- field_generators_.get(field).GenerateByteSize(printer);
+ if (IsFieldUsed(field, options_)) {
+ field_generators_.get(field).GenerateByteSize(printer);
+ }
format("break;\n");
format.Outdent();
format("}\n");
@@ -4014,24 +3982,10 @@
"}\n\n");
}
- if (HasFieldPresence(descriptor_->file())) {
- // Check that all required fields in this message are set. We can do this
- // most efficiently by checking 32 "has bits" at a time.
- const std::vector<uint32> masks = RequiredFieldsBitMask();
-
- for (int i = 0; i < masks.size(); i++) {
- uint32 mask = masks[i];
- if (mask == 0) {
- continue;
- }
-
- // TODO(ckennelly): Consider doing something similar to ByteSizeLong(),
- // where we check all of the required fields in a single branch (assuming
- // that we aren't going to benefit from early termination).
- format("if ((_has_bits_[$1$] & 0x$2$) != 0x$2$) return false;\n",
- i, // 1
- StrCat(strings::Hex(mask, strings::ZERO_PAD_8))); // 2
- }
+ if (num_required_fields_ > 0) {
+ format(
+ "if (_Internal::MissingRequiredFields(_has_bits_))"
+ " return false;\n");
}
// Now check that all non-oneof embedded messages are initialized.
@@ -4057,7 +4011,7 @@
} else if (field->options().weak()) {
continue;
} else {
- GOOGLE_CHECK(!field->containing_oneof());
+ GOOGLE_CHECK(!field->real_containing_oneof());
format(
"if (_internal_has_$1$()) {\n"
" if (!$1$_->IsInitialized()) return false;\n"
@@ -4093,10 +4047,11 @@
format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
format.Indent();
- if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
+ if (IsFieldUsed(field, options_) &&
+ field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
scc_analyzer_->HasRequiredFields(field->message_type())) {
- GOOGLE_CHECK(!(field->options().weak() || !field->containing_oneof()));
+ GOOGLE_CHECK(!(field->options().weak() || !field->real_containing_oneof()));
if (field->options().weak()) {
// Just skip.
} else {
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h
index bc4febf..a212ff4 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message.h
@@ -144,6 +144,7 @@
void GenerateSerializeWithCachedSizesBody(io::Printer* printer);
void GenerateByteSize(io::Printer* printer);
void GenerateMergeFrom(io::Printer* printer);
+ void GenerateClassSpecificMergeFrom(io::Printer* printer);
void GenerateCopyFrom(io::Printer* printer);
void GenerateSwap(io::Printer* printer);
void GenerateIsInitialized(io::Printer* printer);
@@ -180,6 +181,10 @@
bool copy_constructor) const;
size_t HasBitsSize() const;
+ int HasBitIndex(const FieldDescriptor* a) const;
+ int HasByteIndex(const FieldDescriptor* a) const;
+ int HasWordIndex(const FieldDescriptor* a) const;
+ bool SameHasByte(const FieldDescriptor* a, const FieldDescriptor* b) const;
std::vector<uint32> RequiredFieldsBitMask() const;
const Descriptor* descriptor_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
index 12c6524..38fcb52 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
@@ -66,10 +66,10 @@
(*variables)["type_default_instance_ptr"] =
QualifiedDefaultInstancePtr(descriptor->message_type(), options);
(*variables)["type_reference_function"] =
- implicit_weak
- ? (" " + (*variables)["proto_ns"] + "::internal::StrongReference(" +
- (*variables)["type_default_instance"] + ");\n")
- : "";
+ implicit_weak ? (" ::" + (*variables)["proto_ns"] +
+ "::internal::StrongReference(" +
+ (*variables)["type_default_instance"] + ");\n")
+ : "";
// NOTE: Escaped here to unblock proto1->proto2 migration.
// TODO(liujisi): Extend this to apply for other conflicting methods.
(*variables)["release_name"] =
@@ -104,17 +104,43 @@
void MessageFieldGenerator::GenerateAccessorDeclarations(
io::Printer* printer) const {
Formatter format(printer, variables_);
+ if (!IsFieldUsed(descriptor_, options_)) {
+ format(
+ "$deprecated_attr$const $type$& ${1$$name$$}$() const { "
+ "__builtin_trap(); }\n"
+ "$deprecated_attr$$type$* ${1$$release_name$$}$() { "
+ "__builtin_trap(); }\n"
+ "$deprecated_attr$$type$* ${1$mutable_$name$$}$() { "
+ "__builtin_trap(); }\n"
+ "$deprecated_attr$void ${1$set_allocated_$name$$}$"
+ "($type$* $name$) { __builtin_trap(); }\n",
+ descriptor_);
+ if (SupportsArenas(descriptor_)) {
+ format(
+ "$deprecated_attr$void "
+ "${1$unsafe_arena_set_allocated_$name$$}$(\n"
+ " $type$* $name$) { __builtin_trap(); }\n"
+ "$deprecated_attr$$type$* ${1$unsafe_arena_release_$name$$}$() { "
+ "__builtin_trap(); }\n",
+ descriptor_);
+ }
+ return;
+ }
format(
"$deprecated_attr$const $type$& ${1$$name$$}$() const;\n"
"$deprecated_attr$$type$* ${1$$release_name$$}$();\n"
"$deprecated_attr$$type$* ${1$mutable_$name$$}$();\n"
"$deprecated_attr$void ${1$set_allocated_$name$$}$"
- "($type$* $name$);\n"
- "private:\n"
- "const $type$& ${1$_internal_$name$$}$() const;\n"
- "$type$* ${1$_internal_mutable_$name$$}$();\n"
- "public:\n",
+ "($type$* $name$);\n",
descriptor_);
+ if (IsFieldUsed(descriptor_, options_)) {
+ format(
+ "private:\n"
+ "const $type$& ${1$_internal_$name$$}$() const;\n"
+ "$type$* ${1$_internal_mutable_$name$$}$();\n"
+ "public:\n",
+ descriptor_);
+ }
if (SupportsArenas(descriptor_)) {
format(
"$deprecated_attr$void "
@@ -127,27 +153,6 @@
void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
io::Printer* printer) const {
- Formatter format(printer, variables_);
- if (SupportsArenas(descriptor_)) {
- format(
- "void $classname$::unsafe_arena_set_allocated_$name$(\n"
- " $type$* $name$) {\n"
- "$annotate_accessor$"
- // If we're not on an arena, free whatever we were holding before.
- // (If we are on arena, we can just forget the earlier pointer.)
- " if (GetArenaNoVirtual() == nullptr) {\n"
- " delete $name$_;\n"
- " }\n"
- " $name$_ = $name$;\n"
- " if ($name$) {\n"
- " $set_hasbit$\n"
- " } else {\n"
- " $clear_hasbit$\n"
- " }\n"
- " // @@protoc_insertion_point(field_unsafe_arena_set_allocated"
- ":$full_name$)\n"
- "}\n");
- }
}
void MessageFieldGenerator::GenerateInlineAccessorDefinitions(
@@ -168,9 +173,37 @@
if (SupportsArenas(descriptor_)) {
format(
+ "inline void $classname$::unsafe_arena_set_allocated_$name$(\n"
+ " $type$* $name$) {\n"
+ "$annotate_accessor$"
+ // If we're not on an arena, free whatever we were holding before.
+ // (If we are on arena, we can just forget the earlier pointer.)
+ " if (GetArena() == nullptr) {\n"
+ " delete reinterpret_cast<::$proto_ns$::MessageLite*>($name$_);\n"
+ " }\n");
+ if (implicit_weak_field_) {
+ format(
+ " $name$_ = "
+ "reinterpret_cast<::$proto_ns$::MessageLite*>($name$);\n");
+ } else {
+ format(" $name$_ = $name$;\n");
+ }
+ format(
+ " if ($name$) {\n"
+ " $set_hasbit$\n"
+ " } else {\n"
+ " $clear_hasbit$\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_unsafe_arena_set_allocated"
+ ":$full_name$)\n"
+ "}\n");
+ format(
"inline $type$* $classname$::$release_name$() {\n"
- " auto temp = unsafe_arena_release_$name$();\n"
- " if (GetArenaNoVirtual() != nullptr) {\n"
+ "$type_reference_function$"
+ " $clear_hasbit$\n"
+ " $type$* temp = $casted_member$;\n"
+ " $name$_ = nullptr;\n"
+ " if (GetArena() != nullptr) {\n"
" temp = ::$proto_ns$::internal::DuplicateIfNonNull(temp);\n"
" }\n"
" return temp;\n"
@@ -194,7 +227,7 @@
"$type_reference_function$"
" $set_hasbit$\n"
" if ($name$_ == nullptr) {\n"
- " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n");
+ " auto* p = CreateMaybeMessage<$type$>(GetArena());\n");
if (implicit_weak_field_) {
format(" $name$_ = reinterpret_cast<::$proto_ns$::MessageLite*>(p);\n");
} else {
@@ -215,7 +248,7 @@
format(
"inline void $classname$::set_allocated_$name$($type$* $name$) {\n"
"$annotate_accessor$"
- " ::$proto_ns$::Arena* message_arena = GetArenaNoVirtual();\n");
+ " ::$proto_ns$::Arena* message_arena = GetArena();\n");
format(" if (message_arena == nullptr) {\n");
if (IsCrossFileMessage(descriptor_)) {
format(
@@ -309,12 +342,11 @@
" if ($type_default_instance_ptr$ == nullptr) {\n"
" msg->$name$_ = ::$proto_ns$::Arena::CreateMessage<\n"
" ::$proto_ns$::internal::ImplicitWeakMessage>(\n"
- " msg->GetArenaNoVirtual());\n"
+ " msg->GetArena());\n"
" } else {\n"
" msg->$name$_ = reinterpret_cast<const "
"::$proto_ns$::MessageLite*>(\n"
- " $type_default_instance_ptr$)->New("
- "msg->GetArenaNoVirtual());\n"
+ " $type_default_instance_ptr$)->New(msg->GetArena());\n"
" }\n"
" }\n"
" return msg->$name$_;\n"
@@ -353,12 +385,14 @@
}
void MessageFieldGenerator::GenerateClearingCode(io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
if (!HasFieldPresence(descriptor_->file())) {
// If we don't have has-bits, message presence is indicated only by ptr !=
// NULL. Thus on clear, we need to delete the object.
format(
- "if (GetArenaNoVirtual() == nullptr && $name$_ != nullptr) {\n"
+ "if (GetArena() == nullptr && $name$_ != nullptr) {\n"
" delete $name$_;\n"
"}\n"
"$name$_ = nullptr;\n");
@@ -369,12 +403,14 @@
void MessageFieldGenerator::GenerateMessageClearingCode(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
if (!HasFieldPresence(descriptor_->file())) {
// If we don't have has-bits, message presence is indicated only by ptr !=
// NULL. Thus on clear, we need to delete the object.
format(
- "if (GetArenaNoVirtual() == nullptr && $name$_ != nullptr) {\n"
+ "if (GetArena() == nullptr && $name$_ != nullptr) {\n"
" delete $name$_;\n"
"}\n"
"$name$_ = nullptr;\n");
@@ -386,6 +422,8 @@
}
void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
if (implicit_weak_field_) {
format(
@@ -399,11 +437,15 @@
}
void MessageFieldGenerator::GenerateSwappingCode(io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format("swap($name$_, other->$name$_);\n");
}
void MessageFieldGenerator::GenerateDestructorCode(io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
if (options_.opensource_runtime) {
// TODO(gerbens) Remove this when we don't need to destruct default
@@ -418,12 +460,16 @@
void MessageFieldGenerator::GenerateConstructorCode(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format("$name$_ = nullptr;\n");
}
void MessageFieldGenerator::GenerateCopyConstructorCode(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format(
"if (from._internal_has_$name$()) {\n"
@@ -435,6 +481,8 @@
void MessageFieldGenerator::GenerateSerializeWithCachedSizesToArray(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format(
"target = stream->EnsureSpace(target);\n"
@@ -444,6 +492,8 @@
}
void MessageFieldGenerator::GenerateByteSize(io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format(
"total_size += $tag_size$ +\n"
@@ -468,7 +518,7 @@
format(
"void $classname$::set_allocated_$name$($type$* $name$) {\n"
"$annotate_accessor$"
- " ::$proto_ns$::Arena* message_arena = GetArenaNoVirtual();\n"
+ " ::$proto_ns$::Arena* message_arena = GetArena();\n"
" clear_$oneof_name$();\n"
" if ($name$) {\n");
if (SupportsArenas(descriptor_->message_type()) &&
@@ -510,7 +560,7 @@
" $type$* temp = $field_member$;\n");
if (SupportsArenas(descriptor_)) {
format(
- " if (GetArenaNoVirtual() != nullptr) {\n"
+ " if (GetArena() != nullptr) {\n"
" temp = ::$proto_ns$::internal::DuplicateIfNonNull(temp);\n"
" }\n");
}
@@ -570,8 +620,7 @@
" if (!_internal_has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
- " $field_member$ = CreateMaybeMessage< $type$ >(\n"
- " GetArenaNoVirtual());\n"
+ " $field_member$ = CreateMaybeMessage< $type$ >(GetArena());\n"
" }\n"
" return $field_member$;\n"
"}\n"
@@ -584,10 +633,12 @@
void MessageOneofFieldGenerator::GenerateClearingCode(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
format(
- "if (GetArenaNoVirtual() == nullptr) {\n"
+ "if (GetArena() == nullptr) {\n"
" delete $field_member$;\n"
"}\n");
} else {
@@ -643,14 +694,35 @@
void RepeatedMessageFieldGenerator::GenerateAccessorDeclarations(
io::Printer* printer) const {
Formatter format(printer, variables_);
+ if (!IsFieldUsed(descriptor_, options_)) {
+ format(
+ "$deprecated_attr$$type$* ${1$mutable_$name$$}$(int index) { "
+ "__builtin_trap(); }\n"
+ "$deprecated_attr$::$proto_ns$::RepeatedPtrField< $type$ >*\n"
+ " ${1$mutable_$name$$}$() { __builtin_trap(); }\n"
+ "$deprecated_attr$const $type$& ${1$$name$$}$(int index) const { "
+ "__builtin_trap(); }\n"
+ "$deprecated_attr$$type$* ${1$add_$name$$}$() { "
+ "__builtin_trap(); }\n"
+ "$deprecated_attr$const ::$proto_ns$::RepeatedPtrField< $type$ >&\n"
+ " ${1$$name$$}$() const { __builtin_trap(); }\n",
+ descriptor_);
+ return;
+ }
format(
"$deprecated_attr$$type$* ${1$mutable_$name$$}$(int index);\n"
"$deprecated_attr$::$proto_ns$::RepeatedPtrField< $type$ >*\n"
- " ${1$mutable_$name$$}$();\n"
- "private:\n"
- "const $type$& ${1$_internal_$name$$}$(int index) const;\n"
- "$type$* ${1$_internal_add_$name$$}$();\n"
- "public:\n"
+ " ${1$mutable_$name$$}$();\n",
+ descriptor_);
+ if (IsFieldUsed(descriptor_, options_)) {
+ format(
+ "private:\n"
+ "const $type$& ${1$_internal_$name$$}$(int index) const;\n"
+ "$type$* ${1$_internal_add_$name$$}$();\n"
+ "public:\n",
+ descriptor_);
+ }
+ format(
"$deprecated_attr$const $type$& ${1$$name$$}$(int index) const;\n"
"$deprecated_attr$$type$* ${1$add_$name$$}$();\n"
"$deprecated_attr$const ::$proto_ns$::RepeatedPtrField< $type$ >&\n"
@@ -722,18 +794,24 @@
void RepeatedMessageFieldGenerator::GenerateClearingCode(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format("$name$_.Clear();\n");
}
void RepeatedMessageFieldGenerator::GenerateMergingCode(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format("$name$_.MergeFrom(from.$name$_);\n");
}
void RepeatedMessageFieldGenerator::GenerateSwappingCode(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format("$name$_.InternalSwap(&other->$name$_);\n");
}
@@ -745,6 +823,8 @@
void RepeatedMessageFieldGenerator::GenerateSerializeWithCachedSizesToArray(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
if (implicit_weak_field_) {
format(
@@ -770,6 +850,8 @@
void RepeatedMessageFieldGenerator::GenerateByteSize(
io::Printer* printer) const {
+ GOOGLE_CHECK(IsFieldUsed(descriptor_, options_));
+
Formatter format(printer, variables_);
format(
"total_size += $tag_size$UL * this->_internal_$name$_size();\n"
diff --git a/src/google/protobuf/compiler/cpp/cpp_options.h b/src/google/protobuf/compiler/cpp/cpp_options.h
index d8fe3a7..92b5548 100644
--- a/src/google/protobuf/compiler/cpp/cpp_options.h
+++ b/src/google/protobuf/compiler/cpp/cpp_options.h
@@ -44,7 +44,8 @@
enum class EnforceOptimizeMode {
kNoEnforcement, // Use the runtime specified by the file specific options.
- kSpeed, // This is the full runtime.
+ kSpeed, // Full runtime with a generated code implementation.
+ kCodeSize, // Full runtime with a reflective implementation.
kLiteRuntime,
};
@@ -62,6 +63,7 @@
bool bootstrap = false;
bool opensource_runtime = false;
bool annotate_accessor = false;
+ bool unused_field_stripping = false;
std::string runtime_include_base;
int num_cc_files = 0;
std::string annotation_pragma_name;
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
index 847f76c..ca365e7 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
@@ -237,13 +237,13 @@
"inline void $classname$::_internal_set_$name$(const std::string& "
"value) {\n"
" $set_hasbit$\n"
- " $name$_.Set$lite$($default_variable$, value, GetArenaNoVirtual());\n"
+ " $name$_.Set$lite$($default_variable$, value, GetArena());\n"
"}\n"
"inline void $classname$::set_$name$(std::string&& value) {\n"
"$annotate_accessor$"
" $set_hasbit$\n"
" $name$_.Set$lite$(\n"
- " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
+ " $default_variable$, ::std::move(value), GetArena());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"inline void $classname$::set_$name$(const char* value) {\n"
@@ -251,7 +251,7 @@
" $null_check$"
" $set_hasbit$\n"
" $name$_.Set$lite$($default_variable$, $string_piece$(value),\n"
- " GetArenaNoVirtual());\n"
+ " GetArena());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n");
if (!options_.opensource_runtime) {
@@ -259,8 +259,7 @@
"inline void $classname$::set_$name$(::StringPiece value) {\n"
"$annotate_accessor$"
" $set_hasbit$\n"
- " $name$_.Set$lite$($default_variable$, value, "
- "GetArenaNoVirtual());\n"
+ " $name$_.Set$lite$($default_variable$, value,GetArena());\n"
" // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
"}\n");
}
@@ -271,31 +270,28 @@
"$annotate_accessor$"
" $set_hasbit$\n"
" $name$_.Set$lite$($default_variable$, $string_piece$(\n"
- " reinterpret_cast<const char*>(value), size), "
- "GetArenaNoVirtual());\n"
+ " reinterpret_cast<const char*>(value), size), GetArena());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline std::string* $classname$::_internal_mutable_$name$() {\n"
" $set_hasbit$\n"
- " return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n"
+ " return $name$_.Mutable($default_variable$, GetArena());\n"
"}\n"
"inline std::string* $classname$::$release_name$() {\n"
"$annotate_accessor$"
" // @@protoc_insertion_point(field_release:$full_name$)\n");
- if (HasFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
format(
" if (!_internal_has_$name$()) {\n"
" return nullptr;\n"
" }\n"
" $clear_hasbit$\n"
" return $name$_.ReleaseNonDefault("
- "$default_variable$, GetArenaNoVirtual());\n");
+ "$default_variable$, GetArena());\n");
} else {
format(
- " $clear_hasbit$\n"
- " return $name$_.Release($default_variable$, "
- "GetArenaNoVirtual());\n");
+ " return $name$_.Release($default_variable$, GetArena());\n");
}
format(
@@ -308,7 +304,7 @@
" $clear_hasbit$\n"
" }\n"
" $name$_.SetAllocated($default_variable$, $name$,\n"
- " GetArenaNoVirtual());\n"
+ " GetArena());\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
if (options_.opensource_runtime) {
@@ -317,22 +313,22 @@
"$annotate_accessor$"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
- " $DCHK$(GetArenaNoVirtual() != nullptr);\n"
+ " $DCHK$(GetArena() != nullptr);\n"
" $clear_hasbit$\n"
" return $name$_.UnsafeArenaRelease($default_variable$,\n"
- " GetArenaNoVirtual());\n"
+ " GetArena());\n"
"}\n"
"inline void $classname$::unsafe_arena_set_allocated_$name$(\n"
"$annotate_accessor$"
" std::string* $name$) {\n"
- " $DCHK$(GetArenaNoVirtual() != nullptr);\n"
+ " $DCHK$(GetArena() != nullptr);\n"
" if ($name$ != nullptr) {\n"
" $set_hasbit$\n"
" } else {\n"
" $clear_hasbit$\n"
" }\n"
" $name$_.UnsafeArenaSetAllocated($default_variable$,\n"
- " $name$, GetArenaNoVirtual());\n"
+ " $name$, GetArena());\n"
" // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
"$full_name$)\n"
"}\n");
@@ -389,7 +385,7 @@
"$annotate_accessor$"
" // @@protoc_insertion_point(field_release:$full_name$)\n");
- if (HasFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
format(
" if (!_internal_has_$name$()) {\n"
" return nullptr;\n"
@@ -436,11 +432,9 @@
// below methods are inlined one-liners)!
if (SupportsArenas(descriptor_)) {
if (descriptor_->default_value_string().empty()) {
- format(
- "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
+ format("$name$_.ClearToEmpty($default_variable$, GetArena());\n");
} else {
- format(
- "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n");
+ format("$name$_.ClearToDefault($default_variable$, GetArena());\n");
}
} else {
if (descriptor_->default_value_string().empty()) {
@@ -459,10 +453,10 @@
// the minimal number of branches / amount of extraneous code at runtime
// (given that the below methods are inlined one-liners)!
- // If we have field presence, then the Clear() method of the protocol buffer
+ // If we have a hasbit, then the Clear() method of the protocol buffer
// will have checked that this field is set. If so, we can avoid redundant
// checks against default_variable.
- const bool must_be_present = HasFieldPresence(descriptor_->file());
+ const bool must_be_present = HasHasbit(descriptor_);
if (inlined_ && must_be_present) {
// Calling mutable_$name$() gives us a string reference and sets the has bit
@@ -481,14 +475,12 @@
if (must_be_present) {
format("$name$_.ClearNonDefaultToEmpty();\n");
} else {
- format(
- "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
+ format("$name$_.ClearToEmpty($default_variable$, GetArena());\n");
}
} else {
// Clear to a non-empty default is more involved, as we try to use the
// Arena if one is present and may need to reallocate the string.
- format(
- "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n");
+ format("$name$_.ClearToDefault($default_variable$, GetArena());\n");
}
} else if (must_be_present) {
// When Arenas are disabled and field presence has been checked, we can
@@ -509,7 +501,7 @@
void StringFieldGenerator::GenerateMergingCode(io::Printer* printer) const {
Formatter format(printer, variables_);
- if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) {
+ if (SupportsArenas(descriptor_) || descriptor_->real_containing_oneof()) {
// TODO(gpike): improve this
format("_internal_set_$name$(from._internal_$name$());\n");
} else {
@@ -524,9 +516,7 @@
if (inlined_) {
format("$name$_.Swap(&other->$name$_);\n");
} else {
- format(
- "$name$_.Swap(&other->$name$_, $default_variable$,\n"
- " GetArenaNoVirtual());\n");
+ format("$name$_.Swap(&other->$name$_, $default_variable$, GetArena());\n");
}
}
@@ -547,7 +537,7 @@
Formatter format(printer, variables_);
GenerateConstructorCode(printer);
- if (HasFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
format("if (from._internal_has_$name$()) {\n");
} else {
format("if (!from._internal_$name$().empty()) {\n");
@@ -555,11 +545,11 @@
format.Indent();
- if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) {
+ if (SupportsArenas(descriptor_) || descriptor_->real_containing_oneof()) {
// TODO(gpike): improve this
format(
"$name$_.Set$lite$($default_variable$, from._internal_$name$(),\n"
- " GetArenaNoVirtual());\n");
+ " GetArena());\n");
} else {
format("$name$_.AssignWithDefault($default_variable$, from.$name$_);\n");
}
@@ -682,8 +672,7 @@
" set_has_$name$();\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " $field_member$.Set$lite$($default_variable$, value,\n"
- " GetArenaNoVirtual());\n"
+ " $field_member$.Set$lite$($default_variable$, value, GetArena());\n"
"}\n"
"inline void $classname$::set_$name$(std::string&& value) {\n"
"$annotate_accessor$"
@@ -694,7 +683,7 @@
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $field_member$.Set$lite$(\n"
- " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
+ " $default_variable$, ::std::move(value), GetArena());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"inline void $classname$::set_$name$(const char* value) {\n"
@@ -706,7 +695,7 @@
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $field_member$.Set$lite$($default_variable$,\n"
- " $string_piece$(value), GetArenaNoVirtual());\n"
+ " $string_piece$(value), GetArena());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n");
if (!options_.opensource_runtime) {
@@ -719,7 +708,7 @@
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $field_member$.Set$lite$($default_variable$, value,\n"
- " GetArenaNoVirtual());\n"
+ " GetArena());\n"
" // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
"}\n");
}
@@ -736,7 +725,7 @@
" $field_member$.Set$lite$(\n"
" $default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size),\n"
- " GetArenaNoVirtual());\n"
+ " GetArena());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"inline std::string* $classname$::_internal_mutable_$name$() {\n"
@@ -745,16 +734,14 @@
" set_has_$name$();\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
- " return $field_member$.Mutable($default_variable$,\n"
- " GetArenaNoVirtual());\n"
+ " return $field_member$.Mutable($default_variable$, GetArena());\n"
"}\n"
"inline std::string* $classname$::$release_name$() {\n"
"$annotate_accessor$"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (_internal_has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
- " return $field_member$.Release($default_variable$,\n"
- " GetArenaNoVirtual());\n"
+ " return $field_member$.Release($default_variable$, GetArena());\n"
" } else {\n"
" return nullptr;\n"
" }\n"
@@ -767,6 +754,10 @@
" if ($name$ != nullptr) {\n"
" set_has_$name$();\n"
" $field_member$.UnsafeSetDefault($name$);\n"
+ " ::$proto_ns$::Arena* arena = GetArena();\n"
+ " if (arena != nullptr) {\n"
+ " arena->Own($name$);\n"
+ " }\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
@@ -776,11 +767,11 @@
"$annotate_accessor$"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
- " $DCHK$(GetArenaNoVirtual() != nullptr);\n"
+ " $DCHK$(GetArena() != nullptr);\n"
" if (_internal_has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
" return $field_member$.UnsafeArenaRelease(\n"
- " $default_variable$, GetArenaNoVirtual());\n"
+ " $default_variable$, GetArena());\n"
" } else {\n"
" return nullptr;\n"
" }\n"
@@ -788,7 +779,7 @@
"inline void $classname$::unsafe_arena_set_allocated_$name$("
"std::string* $name$) {\n"
"$annotate_accessor$"
- " $DCHK$(GetArenaNoVirtual() != nullptr);\n"
+ " $DCHK$(GetArena() != nullptr);\n"
" if (!_internal_has_$name$()) {\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
@@ -796,7 +787,7 @@
" if ($name$) {\n"
" set_has_$name$();\n"
" $field_member$.UnsafeArenaSetAllocated($default_variable$, "
- "$name$, GetArenaNoVirtual());\n"
+ "$name$, GetArena());\n"
" }\n"
" // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
"$full_name$)\n"
@@ -906,9 +897,7 @@
io::Printer* printer) const {
Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
- format(
- "$field_member$.Destroy($default_variable$,\n"
- " GetArenaNoVirtual());\n");
+ format("$field_member$.Destroy($default_variable$, GetArena());\n");
} else {
format("$field_member$.DestroyNoArena($default_variable$);\n");
}
@@ -932,15 +921,6 @@
" $default_variable$);\n");
}
-void StringOneofFieldGenerator::GenerateDestructorCode(
- io::Printer* printer) const {
- Formatter format(printer, variables_);
- format(
- "if (_internal_has_$name$()) {\n"
- " $field_member$.DestroyNoArena($default_variable$);\n"
- "}\n");
-}
-
// ===================================================================
RepeatedStringFieldGenerator::RepeatedStringFieldGenerator(
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h
index f39a93a..0192b3d 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h
@@ -95,7 +95,6 @@
void GenerateMessageClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
- void GenerateDestructorCode(io::Printer* printer) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator);
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/cpp_unittest.inc
index 2efbd6d..c36a0b8 100644
--- a/src/google/protobuf/compiler/cpp/cpp_unittest.inc
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.inc
@@ -44,11 +44,10 @@
// correctly and produces the interfaces we expect, which is why this test
// is written this way.
-#include <google/protobuf/compiler/cpp/cpp_unittest.h>
-
#include <memory>
#include <vector>
+#include <google/protobuf/compiler/cpp/cpp_unittest.h>
#include <google/protobuf/unittest_no_arena.pb.h>
#include <google/protobuf/stubs/strutil.h>
#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
@@ -100,8 +99,8 @@
// implements ErrorCollector ---------------------------------------
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
- strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
- filename, line, column, message);
+ strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line, column,
+ message);
}
};
@@ -1683,6 +1682,26 @@
EXPECT_EQ(kHello, message.foo_string());
}
+TEST_F(OneofTest, ArenaSetAllocatedString) {
+ // Check that set_allocated_foo() works for strings.
+ Arena arena;
+ UNITTEST::TestOneof2* message =
+ Arena::CreateMessage<UNITTEST::TestOneof2>(&arena);
+
+ EXPECT_FALSE(message->has_foo_string());
+ const std::string kHello("hello");
+ message->set_foo_string(kHello);
+ EXPECT_TRUE(message->has_foo_string());
+
+ message->set_allocated_foo_string(NULL);
+ EXPECT_FALSE(message->has_foo_string());
+ EXPECT_EQ("", message->foo_string());
+
+ message->set_allocated_foo_string(new std::string(kHello));
+ EXPECT_TRUE(message->has_foo_string());
+ EXPECT_EQ(kHello, message->foo_string());
+}
+
TEST_F(OneofTest, SetMessage) {
// Check that setting a message field works
diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc
index 454f4cb..c69e248 100644
--- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc
@@ -96,13 +96,13 @@
(*variables)["default_value"] = default_value();
(*variables)["capitalized_type_name"] = capitalized_type_name();
(*variables)["number"] = number();
- if (has_default_value() && !IsProto2(descriptor_->file())) {
+ if (has_default_value() && !SupportsPresenceApi(descriptor_)) {
(*variables)["name_def_message"] =
(*variables)["name"] + "_ = " + (*variables)["default_value"];
} else {
(*variables)["name_def_message"] = (*variables)["name"] + "_";
}
- if (IsProto2(descriptor_->file())) {
+ if (SupportsPresenceApi(descriptor_)) {
(*variables)["has_property_check"] = "Has" + (*variables)["property_name"];
(*variables)["other_has_property_check"] = "other.Has" + (*variables)["property_name"];
(*variables)["has_not_property_check"] = "!" + (*variables)["has_property_check"];
@@ -125,7 +125,7 @@
void FieldGeneratorBase::SetCommonOneofFieldVariables(
std::map<string, string>* variables) {
(*variables)["oneof_name"] = oneof_name();
- if (IsProto2(descriptor_->file())) {
+ if (SupportsPresenceApi(descriptor_)) {
(*variables)["has_property_check"] = "Has" + property_name();
} else {
(*variables)["has_property_check"] =
diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.cc b/src/google/protobuf/compiler/csharp/csharp_generator.cc
index b335522..c2170f1 100644
--- a/src/google/protobuf/compiler/csharp/csharp_generator.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_generator.cc
@@ -48,6 +48,13 @@
namespace compiler {
namespace csharp {
+Generator::Generator() {}
+Generator::~Generator() {}
+
+uint64 Generator::GetSupportedFeatures() const {
+ return CodeGenerator::Feature::FEATURE_PROTO3_OPTIONAL;
+}
+
void GenerateFile(const FileDescriptor* file, io::Printer* printer,
const Options* options) {
ReflectionClassGenerator reflectionClassGenerator(file, options);
diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.h b/src/google/protobuf/compiler/csharp/csharp_generator.h
index da72e0e..76806db 100644
--- a/src/google/protobuf/compiler/csharp/csharp_generator.h
+++ b/src/google/protobuf/compiler/csharp/csharp_generator.h
@@ -50,11 +50,14 @@
// CodeGenerator with the CommandLineInterface in your main() function.
class PROTOC_EXPORT Generator : public CodeGenerator {
public:
- virtual bool Generate(
- const FileDescriptor* file,
- const string& parameter,
- GeneratorContext* generator_context,
- string* error) const;
+ Generator();
+ ~Generator();
+ bool Generate(
+ const FileDescriptor* file,
+ const string& parameter,
+ GeneratorContext* generator_context,
+ string* error) const override;
+ uint64 GetSupportedFeatures() const override;
};
} // namespace csharp
diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.cc b/src/google/protobuf/compiler/csharp/csharp_helpers.cc
index 98aa246..c7a0d4f 100644
--- a/src/google/protobuf/compiler/csharp/csharp_helpers.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_helpers.cc
@@ -515,13 +515,13 @@
}
} else {
if (IsWrapperType(descriptor)) {
- if (descriptor->containing_oneof()) {
+ if (descriptor->real_containing_oneof()) {
return new WrapperOneofFieldGenerator(descriptor, presenceIndex, options);
} else {
return new WrapperFieldGenerator(descriptor, presenceIndex, options);
}
} else {
- if (descriptor->containing_oneof()) {
+ if (descriptor->real_containing_oneof()) {
return new MessageOneofFieldGenerator(descriptor, presenceIndex, options);
} else {
return new MessageFieldGenerator(descriptor, presenceIndex, options);
@@ -532,7 +532,7 @@
if (descriptor->is_repeated()) {
return new RepeatedEnumFieldGenerator(descriptor, presenceIndex, options);
} else {
- if (descriptor->containing_oneof()) {
+ if (descriptor->real_containing_oneof()) {
return new EnumOneofFieldGenerator(descriptor, presenceIndex, options);
} else {
return new EnumFieldGenerator(descriptor, presenceIndex, options);
@@ -542,7 +542,7 @@
if (descriptor->is_repeated()) {
return new RepeatedPrimitiveFieldGenerator(descriptor, presenceIndex, options);
} else {
- if (descriptor->containing_oneof()) {
+ if (descriptor->real_containing_oneof()) {
return new PrimitiveOneofFieldGenerator(descriptor, presenceIndex, options);
} else {
return new PrimitiveFieldGenerator(descriptor, presenceIndex, options);
diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.h b/src/google/protobuf/compiler/csharp/csharp_helpers.h
index 6354e9e..90ead89 100644
--- a/src/google/protobuf/compiler/csharp/csharp_helpers.h
+++ b/src/google/protobuf/compiler/csharp/csharp_helpers.h
@@ -158,6 +158,33 @@
return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2;
}
+inline bool SupportsPresenceApi(const FieldDescriptor* descriptor) {
+ // Unlike most languages, we don't generate Has/Clear members for message
+ // types, because they can always be set to null in C#. They're not really
+ // needed for oneof fields in proto2 either, as everything can be done via
+ // oneof case, but we follow the convention from other languages. Proto3
+ // oneof fields never have Has/Clear members - but will also never have
+ // the explicit optional keyword either.
+ //
+ // None of the built-in helpers (descriptor->has_presence() etc) describe
+ // quite the behavior we want, so the rules are explicit below.
+
+ if (descriptor->is_repeated() ||
+ descriptor->type() == FieldDescriptor::TYPE_MESSAGE) {
+ return false;
+ }
+ // has_optional_keyword() has more complex rules for proto2, but that
+ // doesn't matter given the first part of this condition.
+ return IsProto2(descriptor->file()) || descriptor->has_optional_keyword();
+}
+
+inline bool RequiresPresenceBit(const FieldDescriptor* descriptor) {
+ return SupportsPresenceApi(descriptor) &&
+ !IsNullable(descriptor) &&
+ !descriptor->is_extension() &&
+ !descriptor->real_containing_oneof();
+}
+
} // namespace csharp
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/csharp/csharp_map_field.cc b/src/google/protobuf/compiler/csharp/csharp_map_field.cc
index f3f09ea..9f3db76 100644
--- a/src/google/protobuf/compiler/csharp/csharp_map_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_map_field.cc
@@ -96,7 +96,7 @@
void MapFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
- "$name$_.AddEntriesFrom(input, _map_$name$_codec);\n");
+ "$name$_.AddEntriesFrom(ref input, _map_$name$_codec);\n");
}
void MapFieldGenerator::GenerateSerializationCode(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc
index 67f2892..4ff0c7b 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_message.cc
@@ -72,15 +72,13 @@
std::sort(fields_by_number_.begin(), fields_by_number_.end(),
CompareFieldNumbers);
- if (IsProto2(descriptor_->file())) {
- int primitiveCount = 0;
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
- if (!IsNullable(field)) {
- primitiveCount++;
- if (has_bit_field_count_ == 0 || (primitiveCount % 32) == 0) {
- has_bit_field_count_++;
- }
+ int presence_bit_count = 0;
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* field = descriptor_->field(i);
+ if (RequiresPresenceBit(field)) {
+ presence_bit_count++;
+ if (has_bit_field_count_ == 0 || (presence_bit_count % 32) == 0) {
+ has_bit_field_count_++;
}
}
}
@@ -132,6 +130,7 @@
else {
printer->Print(vars, "pb::IMessage<$class_name$>");
}
+ printer->Print(", pb::IBufferMessage");
printer->Print(" {\n");
printer->Indent();
@@ -222,11 +221,12 @@
printer->Print("\n");
}
- // oneof properties
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false);
- vars["property_name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true);
- vars["original_name"] = descriptor_->oneof_decl(i)->name();
+ // oneof properties (for real oneofs, which come before synthetic ones)
+ for (int i = 0; i < descriptor_->real_oneof_decl_count(); i++) {
+ const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
+ vars["name"] = UnderscoresToCamelCase(oneof->name(), false);
+ vars["property_name"] = UnderscoresToCamelCase(oneof->name(), true);
+ vars["original_name"] = oneof->name();
printer->Print(
vars,
"private object $name$_;\n"
@@ -234,8 +234,8 @@
"public enum $property_name$OneofCase {\n");
printer->Indent();
printer->Print("None = 0,\n");
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ for (int j = 0; j < oneof->field_count(); j++) {
+ const FieldDescriptor* field = oneof->field(j);
printer->Print("$field_property_name$ = $index$,\n",
"field_property_name", GetPropertyName(field),
"index", StrCat(field->number()));
@@ -382,23 +382,24 @@
for (int i = 0; i < has_bit_field_count_; i++) {
printer->Print("_hasBits$i$ = other._hasBits$i$;\n", "i", StrCat(i));
}
- // Clone non-oneof fields first
+ // Clone non-oneof fields first (treating optional proto3 fields as non-oneof)
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
- std::unique_ptr<FieldGeneratorBase> generator(
- CreateFieldGeneratorInternal(descriptor_->field(i)));
- generator->GenerateCloningCode(printer);
+ const FieldDescriptor* field = descriptor_->field(i);
+ if (field->real_containing_oneof()) {
+ continue;
}
+ std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
+ generator->GenerateCloningCode(printer);
}
- // Clone just the right field for each oneof
- for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
- vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false);
- vars["property_name"] = UnderscoresToCamelCase(
- descriptor_->oneof_decl(i)->name(), true);
+ // Clone just the right field for each real oneof
+ for (int i = 0; i < descriptor_->real_oneof_decl_count(); ++i) {
+ const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
+ vars["name"] = UnderscoresToCamelCase(oneof->name(), false);
+ vars["property_name"] = UnderscoresToCamelCase(oneof->name(), true);
printer->Print(vars, "switch (other.$property_name$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);
+ for (int j = 0; j < oneof->field_count(); j++) {
+ const FieldDescriptor* field = oneof->field(j);
std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
vars["field_property_name"] = GetPropertyName(field);
printer->Print(
@@ -461,9 +462,9 @@
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->WriteEquals(printer);
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print("if ($property_name$Case != other.$property_name$Case) return false;\n",
- "property_name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true));
+ for (int i = 0; i < descriptor_->real_oneof_decl_count(); i++) {
+ printer->Print("if ($property_name$Case != other.$property_name$Case) return false;\n",
+ "property_name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true));
}
if (has_extension_ranges_) {
printer->Print(
@@ -488,9 +489,9 @@
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->WriteHash(printer);
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print("hash ^= (int) $name$Case_;\n",
- "name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false));
+ for (int i = 0; i < descriptor_->real_oneof_decl_count(); i++) {
+ printer->Print("hash ^= (int) $name$Case_;\n",
+ "name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false));
}
if (has_extension_ranges_) {
printer->Print(
@@ -589,22 +590,24 @@
"if (other == null) {\n"
" return;\n"
"}\n");
- // Merge non-oneof fields
+ // Merge non-oneof fields, treating optional proto3 fields as normal fields
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
- std::unique_ptr<FieldGeneratorBase> generator(
- CreateFieldGeneratorInternal(descriptor_->field(i)));
- generator->GenerateMergingCode(printer);
+ const FieldDescriptor* field = descriptor_->field(i);
+ if (field->real_containing_oneof()) {
+ continue;
}
+ std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
+ generator->GenerateMergingCode(printer);
}
- // Merge oneof fields
- for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
- vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false);
- vars["property_name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true);
+ // Merge oneof fields (for non-synthetic oneofs)
+ for (int i = 0; i < descriptor_->real_oneof_decl_count(); ++i) {
+ const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
+ vars["name"] = UnderscoresToCamelCase(oneof->name(), false);
+ vars["property_name"] = UnderscoresToCamelCase(oneof->name(), true);
printer->Print(vars, "switch (other.$property_name$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);
+ for (int j = 0; j < oneof->field_count(); j++) {
+ const FieldDescriptor* field = oneof->field(j);
vars["field_property_name"] = GetPropertyName(field);
printer->Print(
vars,
@@ -634,6 +637,13 @@
WriteGeneratedCodeAttributes(printer);
printer->Print("public void MergeFrom(pb::CodedInputStream input) {\n");
printer->Indent();
+ printer->Print("input.ReadRawMessage(this);\n");
+ printer->Outdent();
+ printer->Print("}\n\n");
+
+ WriteGeneratedCodeAttributes(printer);
+ printer->Print("void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {\n");
+ printer->Indent();
printer->Print(
"uint tag;\n"
"while ((tag = input.ReadTag()) != 0) {\n"
@@ -649,14 +659,14 @@
if (has_extension_ranges_) {
printer->Print(
"default:\n"
- " if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) {\n"
- " _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n"
+ " if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) {\n"
+ " _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);\n"
" }\n"
" break;\n");
} else {
printer->Print(
"default:\n"
- " _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n"
+ " _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);\n"
" break;\n");
}
for (int i = 0; i < fields_by_number().size(); i++) {
@@ -698,8 +708,7 @@
// it's a waste of space to track presence for all values, so we only track them if they're not nullable
int MessageGenerator::GetPresenceIndex(const FieldDescriptor* descriptor) {
- if (IsNullable(descriptor) || !IsProto2(descriptor->file()) ||
- descriptor->is_extension()) {
+ if (!RequiresPresenceBit(descriptor)) {
return -1;
}
@@ -709,7 +718,7 @@
if (field == descriptor) {
return index;
}
- if (!IsNullable(field)) {
+ if (RequiresPresenceBit(field)) {
index++;
}
}
diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc
index 4125798..034fbd9 100644
--- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc
@@ -53,7 +53,7 @@
int presenceIndex,
const Options *options)
: FieldGeneratorBase(descriptor, presenceIndex, options) {
- if (!IsProto2(descriptor_->file())) {
+ if (!SupportsPresenceApi(descriptor_)) {
variables_["has_property_check"] = name() + "_ != null";
variables_["has_not_property_check"] = name() + "_ == null";
}
@@ -77,7 +77,7 @@
" $name$_ = value;\n"
" }\n"
"}\n");
- if (IsProto2(descriptor_->file())) {
+ if (SupportsPresenceApi(descriptor_)) {
printer->Print(
variables_,
"/// <summary>Gets whether the $descriptor_name$ field is set</summary>\n");
@@ -228,7 +228,7 @@
" $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n"
" }\n"
"}\n");
- if (IsProto2(descriptor_->file())) {
+ if (SupportsPresenceApi(descriptor_)) {
printer->Print(
variables_,
"/// <summary>Gets whether the \"$descriptor_name$\" field is set</summary>\n");
diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc
index eb7f70d..9df1dd6 100644
--- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc
@@ -53,7 +53,7 @@
// TODO(jonskeet): Make this cleaner...
is_value_type = descriptor->type() != FieldDescriptor::TYPE_STRING
&& descriptor->type() != FieldDescriptor::TYPE_BYTES;
- if (!is_value_type && !IsProto2(descriptor_->file())) {
+ if (!is_value_type && !SupportsPresenceApi(descriptor_)) {
variables_["has_property_check"] = variables_["property_name"] + ".Length != 0";
variables_["other_has_property_check"] = "other." + variables_["property_name"] + ".Length != 0";
}
@@ -63,42 +63,65 @@
}
void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) {
- // TODO(jonskeet): Work out whether we want to prevent the fields from ever being
- // null, or whether we just handle it, in the cases of bytes and string.
- // (Basically, should null-handling code be in the getter or the setter?)
+
+ // Note: in multiple places, this code assumes that all fields
+ // that support presence are either nullable, or use a presence field bit.
+ // Fields which are oneof members are not generated here; they're generated in PrimitiveOneofFieldGenerator below.
+ // Extensions are not generated here either.
+
+
+ // Proto2 allows different default values to be specified. These are retained
+ // via static fields. They don't particularly need to be, but we don't need
+ // to change that. In Proto3 the default value we don't generate these
+ // fields, just using the literal instead.
if (IsProto2(descriptor_->file())) {
+ // Note: "private readonly static" isn't as idiomatic as
+ // "private static readonly", but changing this now would create a lot of
+ // churn in generated code with near-to-zero benefit.
printer->Print(
variables_,
"private readonly static $type_name$ $property_name$DefaultValue = $default_value$;\n\n");
+ variables_["default_value_access"] =
+ variables_["property_name"] + "DefaultValue";
+ } else {
+ variables_["default_value_access"] = variables_["default_value"];
}
+ // Declare the field itself.
printer->Print(
variables_,
"private $type_name$ $name_def_message$;\n");
WritePropertyDocComment(printer, descriptor_);
AddPublicMemberAttributes(printer);
- if (IsProto2(descriptor_->file())) {
- if (presenceIndex_ == -1) {
+
+ // Most of the work is done in the property:
+ // Declare the property itself (the same for all options)
+ printer->Print(variables_, "$access_level$ $type_name$ $property_name$ {\n");
+
+ // Specify the "getter", which may need to check for a presence field.
+ if (SupportsPresenceApi(descriptor_)) {
+ if (IsNullable(descriptor_)) {
printer->Print(
variables_,
- "$access_level$ $type_name$ $property_name$ {\n"
- " get { return $name$_ ?? $property_name$DefaultValue; }\n"
- " set {\n");
+ " get { return $name$_ ?? $default_value_access$; }\n");
} else {
printer->Print(
variables_,
- "$access_level$ $type_name$ $property_name$ {\n"
- " get { if ($has_field_check$) { return $name$_; } else { return $property_name$DefaultValue; } }\n"
- " set {\n");
+ // Note: it's possible that this could be rewritten as a
+ // conditional ?: expression, but there's no significant benefit
+ // to changing it.
+ " get { if ($has_field_check$) { return $name$_; } else { return $default_value_access$; } }\n");
}
} else {
printer->Print(
variables_,
- "$access_level$ $type_name$ $property_name$ {\n"
- " get { return $name$_; }\n"
- " set {\n");
+ " get { return $name$_; }\n");
}
+
+ // Specify the "setter", which may need to set a field bit as well as the
+ // value.
+ printer->Print(" set {\n");
if (presenceIndex_ != -1) {
printer->Print(
variables_,
@@ -116,8 +139,11 @@
printer->Print(
" }\n"
"}\n");
- if (IsProto2(descriptor_->file())) {
- printer->Print(variables_, "/// <summary>Gets whether the \"$descriptor_name$\" field is set</summary>\n");
+
+ // The "HasFoo" property, where required.
+ if (SupportsPresenceApi(descriptor_)) {
+ printer->Print(variables_,
+ "/// <summary>Gets whether the \"$descriptor_name$\" field is set</summary>\n");
AddPublicMemberAttributes(printer);
printer->Print(
variables_,
@@ -133,8 +159,11 @@
"$has_field_check$; }\n}\n");
}
}
- if (IsProto2(descriptor_->file())) {
- printer->Print(variables_, "/// <summary>Clears the value of the \"$descriptor_name$\" field</summary>\n");
+
+ // The "ClearFoo" method, where required.
+ if (SupportsPresenceApi(descriptor_)) {
+ printer->Print(variables_,
+ "/// <summary>Clears the value of the \"$descriptor_name$\" field</summary>\n");
AddPublicMemberAttributes(printer);
printer->Print(
variables_,
@@ -270,7 +299,7 @@
" $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"
" }\n"
"}\n");
- if (IsProto2(descriptor_->file())) {
+ if (SupportsPresenceApi(descriptor_)) {
printer->Print(
variables_,
"/// <summary>Gets whether the \"$descriptor_name$\" field is set</summary>\n");
diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc
index 73309a7..aae7091 100644
--- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc
@@ -80,7 +80,7 @@
void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
- "$name$_.AddEntriesFrom(input, _repeated_$name$_codec);\n");
+ "$name$_.AddEntriesFrom(ref input, _repeated_$name$_codec);\n");
}
void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc
index 4b4b37d..2e2cfa8 100644
--- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc
@@ -95,7 +95,7 @@
void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
- "$name$_.AddEntriesFrom(input, _repeated_$name$_codec);\n");
+ "$name$_.AddEntriesFrom(ref input, _repeated_$name$_codec);\n");
}
void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc
index c1444ea..d4ff302 100644
--- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc
@@ -80,7 +80,7 @@
void RepeatedPrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
- "$name$_.AddEntriesFrom(input, _repeated_$name$_codec);\n");
+ "$name$_.AddEntriesFrom(ref input, _repeated_$name$_codec);\n");
}
void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc
index add20ab..cada81c 100644
--- a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc
@@ -81,7 +81,7 @@
" $name$_ = value;\n"
" }\n"
"}\n\n");
- if (IsProto2(descriptor_->file())) {
+ if (SupportsPresenceApi(descriptor_)) {
printer->Print(
variables_,
"/// <summary>Gets whether the $descriptor_name$ field is set</summary>\n");
@@ -116,7 +116,7 @@
void WrapperFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
- "$type_name$ value = _single_$name$_codec.Read(input);\n"
+ "$type_name$ value = _single_$name$_codec.Read(ref input);\n"
"if ($has_not_property_check$ || value != $default_value$) {\n"
" $property_name$ = value;\n"
"}\n");
@@ -219,7 +219,7 @@
" $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n"
" }\n"
"}\n");
- if (IsProto2(descriptor_->file())) {
+ if (SupportsPresenceApi(descriptor_)) {
printer->Print(
variables_,
"/// <summary>Gets whether the \"$descriptor_name$\" field is set</summary>\n");
@@ -250,7 +250,7 @@
void WrapperOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
- "$property_name$ = _oneof_$name$_codec.Read(input);\n");
+ "$property_name$ = _oneof_$name$_codec.Read(ref input);\n");
}
void WrapperOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc
index 400d5d0..3b42d95 100644
--- a/src/google/protobuf/compiler/importer.cc
+++ b/src/google/protobuf/compiler/importer.cc
@@ -231,8 +231,9 @@
return pool_.FindFileByName(filename);
}
-void Importer::AddUnusedImportTrackFile(const std::string& file_name) {
- pool_.AddUnusedImportTrackFile(file_name);
+void Importer::AddUnusedImportTrackFile(const std::string& file_name,
+ bool is_error) {
+ pool_.AddUnusedImportTrackFile(file_name, is_error);
}
void Importer::ClearUnusedImportTrackFiles() {
diff --git a/src/google/protobuf/compiler/importer.h b/src/google/protobuf/compiler/importer.h
index 1a0b47a..db4a876 100644
--- a/src/google/protobuf/compiler/importer.h
+++ b/src/google/protobuf/compiler/importer.h
@@ -178,7 +178,8 @@
// contents are stored.
inline const DescriptorPool* pool() const { return &pool_; }
- void AddUnusedImportTrackFile(const std::string& file_name);
+ void AddUnusedImportTrackFile(const std::string& file_name,
+ bool is_error = false);
void ClearUnusedImportTrackFiles();
@@ -254,7 +255,7 @@
// and then you do:
// Open("bar/qux");
// the DiskSourceTree will first try to open foo/bar/qux, then baz/bar/qux,
- // returning the first one that opens successfuly.
+ // returning the first one that opens successfully.
//
// disk_path may be an absolute path or relative to the current directory,
// just like a path you'd pass to open().
diff --git a/src/google/protobuf/compiler/importer_unittest.cc b/src/google/protobuf/compiler/importer_unittest.cc
index 111d66f..dc5c692 100644
--- a/src/google/protobuf/compiler/importer_unittest.cc
+++ b/src/google/protobuf/compiler/importer_unittest.cc
@@ -74,14 +74,14 @@
// implements ErrorCollector ---------------------------------------
void AddError(const std::string& filename, int line, int column,
const std::string& message) {
- strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line,
- column, message);
+ strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", filename, line, column,
+ message);
}
void AddWarning(const std::string& filename, int line, int column,
const std::string& message) {
- strings::SubstituteAndAppend(&warning_text_, "$0:$1:$2: $3\n", filename,
- line, column, message);
+ strings::SubstituteAndAppend(&warning_text_, "$0:$1:$2: $3\n", filename, line,
+ column, message);
}
};
diff --git a/src/google/protobuf/compiler/java/java_enum.cc b/src/google/protobuf/compiler/java/java_enum.cc
index 9415eb5..8622ff0 100644
--- a/src/google/protobuf/compiler/java/java_enum.cc
+++ b/src/google/protobuf/compiler/java/java_enum.cc
@@ -142,9 +142,13 @@
vars["number"] = StrCat(descriptor_->value(i)->number());
vars["{"] = "";
vars["}"] = "";
+ vars["deprecation"] = descriptor_->value(i)->options().deprecated()
+ ? "@java.lang.Deprecated "
+ : "";
WriteEnumValueDocComment(printer, descriptor_->value(i));
printer->Print(vars,
- "public static final int ${$$name$_VALUE$}$ = $number$;\n");
+ "$deprecation$public static final int ${$$name$_VALUE$}$ = "
+ "$number$;\n");
printer->Annotate("{", "}", descriptor_->value(i));
}
printer->Print("\n");
@@ -228,7 +232,25 @@
if (HasDescriptorMethods(descriptor_, context_->EnforceLite())) {
printer->Print(
"public final com.google.protobuf.Descriptors.EnumValueDescriptor\n"
- " getValueDescriptor() {\n"
+ " getValueDescriptor() {\n");
+ if (SupportUnknownEnumValue(descriptor_->file())) {
+ if (ordinal_is_index) {
+ printer->Print(
+ " if (this == UNRECOGNIZED) {\n"
+ " throw new java.lang.IllegalStateException(\n"
+ " \"Can't get the descriptor of an unrecognized enum "
+ "value.\");\n"
+ " }\n");
+ } else {
+ printer->Print(
+ " if (index == -1) {\n"
+ " throw new java.lang.IllegalStateException(\n"
+ " \"Can't get the descriptor of an unrecognized enum "
+ "value.\");\n"
+ " }\n");
+ }
+ }
+ printer->Print(
" return getDescriptor().getValues().get($index_text$);\n"
"}\n"
"public final com.google.protobuf.Descriptors.EnumDescriptor\n"
@@ -279,15 +301,22 @@
// for every enum.
printer->Print("values();\n");
} else {
+ printer->Print("getStaticValuesArray();\n");
+ printer->Print("private static $classname$[] getStaticValuesArray() {\n",
+ "classname", descriptor_->name());
+ printer->Indent();
printer->Print(
- "{\n"
- " ");
+ "return new $classname$[] {\n"
+ " ",
+ "classname", descriptor_->name());
for (int i = 0; i < descriptor_->value_count(); i++) {
printer->Print("$name$, ", "name", descriptor_->value(i)->name());
}
printer->Print(
"\n"
"};\n");
+ printer->Outdent();
+ printer->Print("}");
}
printer->Print(
diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/java_enum_field.cc
index 65dd353..32cff15 100644
--- a/src/google/protobuf/compiler/java/java_enum_field.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field.cc
@@ -81,7 +81,7 @@
// with v2.5.0/v2.6.1, and remove the @SuppressWarnings annotations.
(*variables)["for_number"] = "valueOf";
- if (SupportFieldPresence(descriptor->file())) {
+ if (SupportFieldPresence(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
(*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
@@ -105,7 +105,7 @@
".getNumber()";
}
- // For repated builders, one bit is used for whether the array is immutable.
+ // For repeated builders, one bit is used for whether the array is immutable.
(*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex);
(*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex);
(*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex);
@@ -145,7 +145,7 @@
ImmutableEnumFieldGenerator::~ImmutableEnumFieldGenerator() {}
int ImmutableEnumFieldGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ return SupportFieldPresence(descriptor_) ? 1 : 0;
}
int ImmutableEnumFieldGenerator::GetNumBitsForBuilder() const {
@@ -154,7 +154,7 @@
void ImmutableEnumFieldGenerator::GenerateInterfaceMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
@@ -171,27 +171,28 @@
void ImmutableEnumFieldGenerator::GenerateMembers(io::Printer* printer) const {
printer->Print(variables_, "private int $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
- printer->Print(
- variables_,
- "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
- " return $get_has_field_bit_message$;\n"
- "}\n");
+ printer->Print(variables_,
+ "@java.lang.Override $deprecation$public boolean "
+ "${$has$capitalized_name$$}$() {\n"
+ " return $get_has_field_bit_message$;\n"
+ "}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldEnumValueAccessorDocComment(printer, descriptor_, GETTER);
- printer->Print(
- variables_,
- "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
- " return $name$_;\n"
- "}\n");
+ printer->Print(variables_,
+ "@java.lang.Override $deprecation$public int "
+ "${$get$capitalized_name$Value$}$() {\n"
+ " return $name$_;\n"
+ "}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
- "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
+ "@java.lang.Override $deprecation$public $type$ "
+ "${$get$capitalized_name$$}$() {\n"
" @SuppressWarnings(\"deprecation\")\n"
" $type$ result = $type$.$for_number$($name$_);\n"
" return result == null ? $unknown$ : result;\n"
@@ -202,28 +203,29 @@
void ImmutableEnumFieldGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
printer->Print(variables_, "private int $name$_ = $default_number$;\n");
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
- printer->Print(
- variables_,
- "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
- " return $get_has_field_bit_builder$;\n"
- "}\n");
+ printer->Print(variables_,
+ "@java.lang.Override $deprecation$public boolean "
+ "${$has$capitalized_name$$}$() {\n"
+ " return $get_has_field_bit_builder$;\n"
+ "}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldEnumValueAccessorDocComment(printer, descriptor_, GETTER);
- printer->Print(
- variables_,
- "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
- " return $name$_;\n"
- "}\n");
+ printer->Print(variables_,
+ "@java.lang.Override $deprecation$public int "
+ "${$get$capitalized_name$Value$}$() {\n"
+ " return $name$_;\n"
+ "}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldEnumValueAccessorDocComment(printer, descriptor_, SETTER,
/* builder */ true);
printer->Print(variables_,
"$deprecation$public Builder "
"${$set$capitalized_name$Value$}$(int value) {\n"
+ " $set_has_field_bit_builder$\n"
" $name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
@@ -232,6 +234,7 @@
}
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" @SuppressWarnings(\"deprecation\")\n"
" $type$ result = $type$.$for_number$($name$_);\n"
@@ -284,7 +287,7 @@
void ImmutableEnumFieldGenerator::GenerateMergingCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
printer->Print(variables_,
"if (other.has$capitalized_name$()) {\n"
" set$capitalized_name$(other.get$capitalized_name$());\n"
@@ -302,7 +305,7 @@
void ImmutableEnumFieldGenerator::GenerateBuildingCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
printer->Print(variables_,
"if ($get_has_field_bit_from_local$) {\n"
" $set_has_field_bit_to_local$;\n"
@@ -386,7 +389,7 @@
void ImmutableEnumOneofFieldGenerator::GenerateMembers(
io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -423,10 +426,11 @@
void ImmutableEnumOneofFieldGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
@@ -436,6 +440,7 @@
WriteFieldEnumValueAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ((java.lang.Integer) $oneof_name$_).intValue();\n"
@@ -457,6 +462,7 @@
}
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" @SuppressWarnings(\"deprecation\")\n"
@@ -650,6 +656,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
@@ -659,6 +666,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, LIST_COUNT);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
@@ -666,6 +674,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, LIST_INDEXED_GETTER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.get(index));\n"
"}\n");
@@ -673,6 +682,7 @@
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldEnumValueAccessorDocComment(printer, descriptor_, LIST_GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.Integer>\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return $name$_;\n"
@@ -681,6 +691,7 @@
WriteFieldEnumValueAccessorDocComment(printer, descriptor_,
LIST_INDEXED_GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public int "
"${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.get(index);\n"
diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/src/google/protobuf/compiler/java/java_enum_field_lite.cc
index 5c137ca..23aea9b 100644
--- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field_lite.cc
@@ -83,7 +83,7 @@
descriptor->options().deprecated() ? "@java.lang.Deprecated " : "";
(*variables)["required"] = descriptor->is_required() ? "true" : "false";
- if (SupportFieldPresence(descriptor->file())) {
+ if (SupportFieldPresence(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
@@ -103,9 +103,6 @@
".getNumber()";
}
- // For repeated builders, the underlying list tracks mutability state.
- (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()";
-
(*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex);
(*variables)["set_has_field_bit_to_local"] =
@@ -140,12 +137,12 @@
ImmutableEnumFieldLiteGenerator::~ImmutableEnumFieldLiteGenerator() {}
int ImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ return SupportFieldPresence(descriptor_) ? 1 : 0;
}
void ImmutableEnumFieldLiteGenerator::GenerateInterfaceMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
@@ -163,7 +160,7 @@
io::Printer* printer) const {
printer->Print(variables_, "private int $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -217,7 +214,7 @@
void ImmutableEnumFieldLiteGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -288,11 +285,11 @@
WriteIntToUtf16CharSequence(descriptor_->number(), output);
WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_),
output);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
WriteIntToUtf16CharSequence(messageBitIndex_, output);
}
printer->Print(variables_, "\"$name$_\",\n");
- if (SupportFieldPresence(descriptor_->file())) {
+ if (!SupportUnknownEnumValue((descriptor_))) {
PrintEnumVerifierLogic(printer, descriptor_, variables_,
/*var_name=*/"$type$",
/*terminating_string=*/",\n",
@@ -319,7 +316,7 @@
void ImmutableEnumOneofFieldLiteGenerator::GenerateMembers(
io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -386,7 +383,7 @@
WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_),
output);
WriteIntToUtf16CharSequence(descriptor_->containing_oneof()->index(), output);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (!SupportUnknownEnumValue(descriptor_)) {
PrintEnumVerifierLogic(printer, descriptor_, variables_,
/*var_name=*/"$type$",
/*terminating_string=*/",\n",
@@ -396,7 +393,7 @@
void ImmutableEnumOneofFieldLiteGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -572,9 +569,11 @@
printer->Print(
variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
- " if (!$is_mutable$) {\n"
+ // Use a temporary to avoid a redundant iget-object.
+ " com.google.protobuf.Internal.IntList tmp = $name$_;\n"
+ " if (!tmp.isModifiable()) {\n"
" $name$_ =\n"
- " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"
+ " com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);\n"
" }\n"
"}\n");
WriteFieldAccessorDocComment(printer, descriptor_, LIST_INDEXED_SETTER);
@@ -640,7 +639,7 @@
WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_),
output);
printer->Print(variables_, "\"$name$_\",\n");
- if (SupportFieldPresence(descriptor_->file())) {
+ if (!SupportUnknownEnumValue(descriptor_->file())) {
PrintEnumVerifierLogic(printer, descriptor_, variables_,
/*var_name=*/"$type$",
/*terminating_string=*/",\n",
diff --git a/src/google/protobuf/compiler/java/java_enum_lite.cc b/src/google/protobuf/compiler/java/java_enum_lite.cc
index 69bd26c..226fa4f 100644
--- a/src/google/protobuf/compiler/java/java_enum_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_lite.cc
@@ -124,9 +124,13 @@
vars["number"] = StrCat(descriptor_->value(i)->number());
vars["{"] = "";
vars["}"] = "";
+ vars["deprecation"] = descriptor_->value(i)->options().deprecated()
+ ? "@java.lang.Deprecated "
+ : "";
WriteEnumValueDocComment(printer, descriptor_->value(i));
printer->Print(vars,
- "public static final int ${$$name$_VALUE$}$ = $number$;\n");
+ "$deprecation$public static final int ${$$name$_VALUE$}$ = "
+ "$number$;\n");
printer->Annotate("{", "}", descriptor_->value(i));
}
printer->Print("\n");
diff --git a/src/google/protobuf/compiler/java/java_field.cc b/src/google/protobuf/compiler/java/java_field.cc
index 96ed234..2f775a6 100644
--- a/src/google/protobuf/compiler/java/java_field.cc
+++ b/src/google/protobuf/compiler/java/java_field.cc
@@ -87,7 +87,7 @@
field, messageBitIndex, builderBitIndex, context);
}
} else {
- if (field->containing_oneof()) {
+ if (IsRealOneof(field)) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
return new ImmutableMessageOneofFieldGenerator(
@@ -144,7 +144,7 @@
field, messageBitIndex, context);
}
} else {
- if (field->containing_oneof()) {
+ if (IsRealOneof(field)) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
return new ImmutableMessageOneofFieldLiteGenerator(
@@ -251,6 +251,7 @@
(*variables)["disambiguated_reason"] = info->disambiguated_reason;
(*variables)["constant_name"] = FieldConstantName(descriptor);
(*variables)["number"] = StrCat(descriptor->number());
+ (*variables)["kt_dsl_builder"] = "_builder";
// These variables are placeholders to pick out the beginning and ends of
// identifiers for annotations (when doing so with existing variables would
// be ambiguous or impossible). They should never be set to anything but the
diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc
index 4a96a36..2fc7aad 100644
--- a/src/google/protobuf/compiler/java/java_file.cc
+++ b/src/google/protobuf/compiler/java/java_file.cc
@@ -76,6 +76,7 @@
typedef std::set<const FieldDescriptor*, FieldDescriptorCompare>
FieldDescriptorSet;
+
// Recursively searches the given message to collect extensions.
// Returns true if all the extensions can be recognized. The extensions will be
// appended in to the extensions parameter.
@@ -85,13 +86,17 @@
const Reflection* reflection = message.GetReflection();
// There are unknown fields that could be extensions, thus this call fails.
- if (reflection->GetUnknownFields(message).field_count() > 0) return false;
+ UnknownFieldSet unknown_fields;
+ unknown_fields.MergeFrom(reflection->GetUnknownFields(message));
+ if (unknown_fields.field_count() > 0) return false;
std::vector<const FieldDescriptor*> fields;
reflection->ListFields(message, &fields);
for (int i = 0; i < fields.size(); i++) {
- if (fields[i]->is_extension()) extensions->insert(fields[i]);
+ if (fields[i]->is_extension()) {
+ extensions->insert(fields[i]);
+ }
if (GetJavaType(fields[i]) == JAVATYPE_MESSAGE) {
if (fields[i]->is_repeated()) {
diff --git a/src/google/protobuf/compiler/java/java_generator.cc b/src/google/protobuf/compiler/java/java_generator.cc
index 5045cfd..11b04b8 100644
--- a/src/google/protobuf/compiler/java/java_generator.cc
+++ b/src/google/protobuf/compiler/java/java_generator.cc
@@ -58,6 +58,10 @@
JavaGenerator::JavaGenerator() {}
JavaGenerator::~JavaGenerator() {}
+uint64 JavaGenerator::GetSupportedFeatures() const {
+ return CodeGenerator::Feature::FEATURE_PROTO3_OPTIONAL;
+}
+
bool JavaGenerator::Generate(const FileDescriptor* file,
const std::string& parameter,
GeneratorContext* context,
diff --git a/src/google/protobuf/compiler/java/java_generator.h b/src/google/protobuf/compiler/java/java_generator.h
index be63ac4..a4e1708 100644
--- a/src/google/protobuf/compiler/java/java_generator.h
+++ b/src/google/protobuf/compiler/java/java_generator.h
@@ -58,7 +58,9 @@
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file, const std::string& parameter,
- GeneratorContext* context, std::string* error) const;
+ GeneratorContext* context, std::string* error) const override;
+
+ uint64 GetSupportedFeatures() const override;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator);
diff --git a/src/google/protobuf/compiler/java/java_helpers.cc b/src/google/protobuf/compiler/java/java_helpers.cc
index 41cd524..2b9b039 100644
--- a/src/google/protobuf/compiler/java/java_helpers.cc
+++ b/src/google/protobuf/compiler/java/java_helpers.cc
@@ -308,7 +308,7 @@
std::string FieldConstantName(const FieldDescriptor* field) {
std::string name = field->name() + "_FIELD_NUMBER";
- UpperString(&name);
+ ToUpper(&name);
return name;
}
@@ -428,6 +428,7 @@
return BoxedPrimitiveTypeName(GetJavaType(descriptor));
}
+
std::string GetOneofStoredType(const FieldDescriptor* field) {
const JavaType javaType = GetJavaType(field);
switch (javaType) {
@@ -963,6 +964,7 @@
static const int kUtf8CheckBit = 0x200;
static const int kCheckInitialized = 0x400;
static const int kMapWithProto2EnumValue = 0x800;
+ static const int kHasHasBit = 0x1000;
int extra_bits = field->is_required() ? kRequiredBit : 0;
if (field->type() == FieldDescriptor::TYPE_STRING && CheckUtf8(field)) {
extra_bits |= kUtf8CheckBit;
@@ -971,9 +973,12 @@
HasRequiredFields(field->message_type()))) {
extra_bits |= kCheckInitialized;
}
+ if (HasHasbit(field)) {
+ extra_bits |= kHasHasBit;
+ }
if (field->is_map()) {
- if (SupportFieldPresence(field->file())) {
+ if (!SupportUnknownEnumValue(field)) {
const FieldDescriptor* value =
field->message_type()->FindFieldByName("value");
if (GetJavaType(value) == JAVATYPE_ENUM) {
@@ -985,7 +990,7 @@
return GetExperimentalJavaFieldTypeForPacked(field);
} else if (field->is_repeated()) {
return GetExperimentalJavaFieldTypeForRepeated(field) | extra_bits;
- } else if (field->containing_oneof() != NULL) {
+ } else if (IsRealOneof(field)) {
return (GetExperimentalJavaFieldTypeForSingular(field) +
kOneofFieldTypeOffset) |
extra_bits;
diff --git a/src/google/protobuf/compiler/java/java_helpers.h b/src/google/protobuf/compiler/java/java_helpers.h
index 1193cec..046fe7e 100644
--- a/src/google/protobuf/compiler/java/java_helpers.h
+++ b/src/google/protobuf/compiler/java/java_helpers.h
@@ -86,7 +86,7 @@
// Same as UnderscoresToCamelCase, but checks for reserved keywords
std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field);
-// Similar to UnderscoresToCamelCase, but guarentees that the result is a
+// Similar to UnderscoresToCamelCase, but guarantees that the result is a
// complete Java identifier by adding a _ if needed.
std::string CamelCaseFieldName(const FieldDescriptor* field);
@@ -188,9 +188,11 @@
void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer,
Descriptor* descriptor, bool immutable,
const std::string& suffix = "") {
- if (context->options().annotate_code && IsOwnFile(descriptor, immutable)) {
+ if (IsOwnFile(descriptor, immutable)) {
PrintGeneratedAnnotation(printer, '$',
- AnnotationFileName(descriptor, suffix));
+ context->options().annotate_code
+ ? AnnotationFileName(descriptor, suffix)
+ : "");
}
}
@@ -224,6 +226,7 @@
// types.
const char* BoxedPrimitiveTypeName(JavaType type);
+
// Get the name of the java enum constant representing this type. E.g.,
// "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full
// name is "com.google.protobuf.WireFormat.FieldType.INT32".
@@ -352,9 +355,30 @@
// them has a required field. Return true if a required field is found.
bool HasRequiredFields(const Descriptor* descriptor);
-// Whether a .proto file supports field presence test for non-message types.
-inline bool SupportFieldPresence(const FileDescriptor* descriptor) {
- return descriptor->syntax() != FileDescriptor::SYNTAX_PROTO3;
+inline bool IsProto2(const FileDescriptor* descriptor) {
+ return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2;
+}
+
+inline bool SupportFieldPresence(const FieldDescriptor* descriptor) {
+ // Note that while proto3 oneofs do conceptually support present, we return
+ // false for them because they do not offer a public hazzer. Therefore this
+ // method could be named HasHazzer().
+ return !descriptor->is_repeated() &&
+ (descriptor->message_type() || descriptor->has_optional_keyword() ||
+ IsProto2(descriptor->file()));
+}
+
+inline bool IsRealOneof(const FieldDescriptor* descriptor) {
+ return descriptor->containing_oneof() &&
+ !descriptor->containing_oneof()->is_synthetic();
+}
+
+inline bool HasHasbit(const FieldDescriptor* descriptor) {
+ // Note that currently message fields inside oneofs have hasbits. This is
+ // surprising, as the oneof case should avoid any need for a hasbit. But if
+ // you change this method to remove hasbits for oneofs, a few tests fail.
+ return !descriptor->is_repeated() &&
+ (descriptor->has_optional_keyword() || IsProto2(descriptor->file()));
}
// Whether generate classes expose public PARSER instances.
@@ -370,6 +394,10 @@
return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO3;
}
+inline bool SupportUnknownEnumValue(const FieldDescriptor* field) {
+ return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3;
+}
+
// Check whether a message has repeated fields.
bool HasRepeatedFields(const Descriptor* descriptor);
diff --git a/src/google/protobuf/compiler/java/java_map_field.cc b/src/google/protobuf/compiler/java/java_map_field.cc
index 5353745..5db199d 100644
--- a/src/google/protobuf/compiler/java/java_map_field.cc
+++ b/src/google/protobuf/compiler/java/java_map_field.cc
@@ -483,6 +483,7 @@
printer->Print(
variables_,
"$deprecation$\n"
+ "@java.lang.Override\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
@@ -494,6 +495,7 @@
"/**\n"
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
+ "@java.lang.Override\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"${$get$capitalized_name$$}$() {\n"
@@ -502,6 +504,7 @@
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"${$get$capitalized_name$Map$}$() {\n"
@@ -512,6 +515,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -527,6 +531,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -545,6 +550,7 @@
"/**\n"
" * Use {@link #get$capitalized_name$ValueMap()} instead.\n"
" */\n"
+ "@java.lang.Override\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"${$get$capitalized_name$Value$}$() {\n"
@@ -554,6 +560,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"${$get$capitalized_name$ValueMap$}$() {\n"
@@ -563,6 +570,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
@@ -576,6 +584,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -594,6 +603,7 @@
"/**\n"
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
+ "@java.lang.Override\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$$}$() {\n"
@@ -602,6 +612,7 @@
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
@@ -611,6 +622,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -623,6 +635,7 @@
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.cc b/src/google/protobuf/compiler/java/java_map_field_lite.cc
index 8236f3a..4fa939f 100644
--- a/src/google/protobuf/compiler/java/java_map_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc
@@ -508,7 +508,7 @@
printer->Print(variables_,
"\"$name$_\",\n"
"$default_entry$,\n");
- if (SupportFieldPresence(descriptor_->file()) &&
+ if (!SupportUnknownEnumValue(descriptor_) &&
GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
PrintEnumVerifierLogic(printer, ValueField(descriptor_), variables_,
/*var_name=*/"$value_enum_type$",
diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc
index dbf62e5..0192e4b 100644
--- a/src/google/protobuf/compiler/java/java_message.cc
+++ b/src/google/protobuf/compiler/java/java_message.cc
@@ -75,7 +75,13 @@
// ===================================================================
MessageGenerator::MessageGenerator(const Descriptor* descriptor)
- : descriptor_(descriptor) {}
+ : descriptor_(descriptor) {
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ if (IsRealOneof(descriptor_->field(i))) {
+ oneofs_.insert(descriptor_->field(i)->containing_oneof());
+ }
+ }
+}
MessageGenerator::~MessageGenerator() {}
@@ -206,7 +212,7 @@
// 6 bytes per field and oneof
*bytecode_estimate +=
- 10 + 6 * descriptor_->field_count() + 6 * descriptor_->oneof_decl_count();
+ 10 + 6 * descriptor_->field_count() + 6 * oneofs_.size();
}
int ImmutableMessageGenerator::GenerateFieldAccessorTableInitializer(
@@ -225,6 +231,7 @@
bytecode_estimate += 6;
printer->Print("\"$field_name$\", ", "field_name", info->capitalized_name);
}
+ // We reproduce synthetic oneofs here since proto reflection needs these.
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
const OneofGeneratorInfo* info = context_->GetOneofGeneratorInfo(oneof);
@@ -269,15 +276,13 @@
field_generators_.get(descriptor_->field(i))
.GenerateInterfaceMembers(printer);
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
+ for (auto oneof : oneofs_) {
printer->Print(
"\n"
"public $classname$.$oneof_capitalized_name$Case "
"get$oneof_capitalized_name$Case();\n",
"oneof_capitalized_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->capitalized_name,
- "classname",
+ context_->GetOneofGeneratorInfo(oneof)->capitalized_name, "classname",
context_->GetNameResolver()->GetImmutableClassName(descriptor_));
}
printer->Outdent();
@@ -291,7 +296,7 @@
bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true);
std::map<std::string, std::string> variables;
- variables["static"] = is_own_file ? " " : " static ";
+ variables["static"] = is_own_file ? "" : "static ";
variables["classname"] = descriptor_->name();
variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_);
variables["ver"] = GeneratedCodeVersionSuffix();
@@ -330,7 +335,7 @@
" $classname$OrBuilder {\n");
builder_type =
strings::Substitute("com.google.protobuf.GeneratedMessage$0.Builder<?>",
- GeneratedCodeVersionSuffix());
+ GeneratedCodeVersionSuffix());
}
printer->Print("private static final long serialVersionUID = 0L;\n");
@@ -403,13 +408,11 @@
// oneof
std::map<std::string, std::string> vars;
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- vars["oneof_name"] =
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name;
+ for (auto oneof : oneofs_) {
+ vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name;
vars["oneof_capitalized_name"] =
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->capitalized_name;
- vars["oneof_index"] = StrCat(descriptor_->oneof_decl(i)->index());
+ context_->GetOneofGeneratorInfo(oneof)->capitalized_name;
+ vars["oneof_index"] = StrCat((oneof)->index());
// oneofCase_ and oneof_
printer->Print(vars,
"private int $oneof_name$Case_ = 0;\n"
@@ -423,8 +426,8 @@
" implements com.google.protobuf.Internal.EnumLite,\n"
" com.google.protobuf.AbstractMessage.InternalOneOfEnum {\n");
printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ for (int j = 0; j < (oneof)->field_count(); j++) {
+ const FieldDescriptor* field = (oneof)->field(j);
printer->Print(
"$deprecation$$field_name$($field_number$),\n", "deprecation",
field->options().deprecated() ? "@java.lang.Deprecated " : "",
@@ -452,8 +455,8 @@
"\n"
"public static $oneof_capitalized_name$Case forNumber(int value) {\n"
" switch (value) {\n");
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ for (int j = 0; j < (oneof)->field_count(); j++) {
+ const FieldDescriptor* field = (oneof)->field(j);
printer->Print(" case $field_number$: return $field_name$;\n",
"field_number", StrCat(field->number()),
"field_name", ToUpper(field->name()));
@@ -912,19 +915,8 @@
"name", info->capitalized_name);
break;
case FieldDescriptor::LABEL_OPTIONAL:
- if (!SupportFieldPresence(descriptor_->file()) &&
- field->containing_oneof() != NULL) {
- const OneofDescriptor* oneof = field->containing_oneof();
- const OneofGeneratorInfo* oneof_info =
- context_->GetOneofGeneratorInfo(oneof);
- printer->Print("if ($oneof_name$Case_ == $field_number$) {\n",
- "oneof_name", oneof_info->name, "field_number",
- StrCat(field->number()));
- } else {
- printer->Print("if (has$name$()) {\n", "name",
- info->capitalized_name);
- }
printer->Print(
+ "if (has$name$()) {\n"
" if (!get$name$().isInitialized()) {\n"
" memoizedIsInitialized = 0;\n"
" return false;\n"
@@ -987,11 +979,10 @@
if (field->is_repeated()) {
return false;
}
- if (SupportFieldPresence(field->file())) {
+ if (HasHasbit(field)) {
return true;
}
- return GetJavaType(field) == JAVATYPE_MESSAGE &&
- field->containing_oneof() == NULL;
+ return GetJavaType(field) == JAVATYPE_MESSAGE && !IsRealOneof(field);
}
} // namespace
@@ -1015,7 +1006,7 @@
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
- if (field->containing_oneof() == NULL) {
+ if (!IsRealOneof(field)) {
const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field);
if (check_has_bits) {
@@ -1034,19 +1025,17 @@
}
// Compare oneofs.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
+ for (auto oneof : oneofs_) {
printer->Print(
"if (!get$oneof_capitalized_name$Case().equals("
"other.get$oneof_capitalized_name$Case())) return false;\n",
"oneof_capitalized_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->capitalized_name);
- printer->Print(
- "switch ($oneof_name$Case_) {\n", "oneof_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name);
+ context_->GetOneofGeneratorInfo(oneof)->capitalized_name);
+ printer->Print("switch ($oneof_name$Case_) {\n", "oneof_name",
+ context_->GetOneofGeneratorInfo(oneof)->name);
printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ for (int j = 0; j < (oneof)->field_count(); j++) {
+ const FieldDescriptor* field = (oneof)->field(j);
printer->Print("case $field_number$:\n", "field_number",
StrCat(field->number()));
printer->Indent();
@@ -1099,7 +1088,7 @@
// hashCode non-oneofs.
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
- if (field->containing_oneof() == NULL) {
+ if (!IsRealOneof(field)) {
const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field);
if (check_has_bits) {
@@ -1115,13 +1104,12 @@
}
// hashCode oneofs.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "switch ($oneof_name$Case_) {\n", "oneof_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name);
+ for (auto oneof : oneofs_) {
+ printer->Print("switch ($oneof_name$Case_) {\n", "oneof_name",
+ context_->GetOneofGeneratorInfo(oneof)->name);
printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ for (int j = 0; j < (oneof)->field_count(); j++) {
+ const FieldDescriptor* field = (oneof)->field(j);
printer->Print("case $field_number$:\n", "field_number",
StrCat(field->number()));
printer->Indent();
@@ -1360,7 +1348,7 @@
// ===================================================================
void ImmutableMessageGenerator::GenerateInitializers(io::Printer* printer) {
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
+ if (!IsRealOneof(descriptor_->field(i))) {
field_generators_.get(descriptor_->field(i))
.GenerateInitializationCode(printer);
}
diff --git a/src/google/protobuf/compiler/java/java_message.h b/src/google/protobuf/compiler/java/java_message.h
index de2f359..87b9df5 100644
--- a/src/google/protobuf/compiler/java/java_message.h
+++ b/src/google/protobuf/compiler/java/java_message.h
@@ -88,6 +88,7 @@
protected:
const Descriptor* descriptor_;
+ std::set<const OneofDescriptor*> oneofs_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc
index 16e63af..320852b 100644
--- a/src/google/protobuf/compiler/java/java_message_builder.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder.cc
@@ -76,6 +76,11 @@
GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite()))
<< "Generator factory error: A non-lite message generator is used to "
"generate lite messages.";
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ if (IsRealOneof(descriptor_->field(i))) {
+ oneofs_.insert(descriptor_->field(i)->containing_oneof());
+ }
+ }
}
MessageBuilderGenerator::~MessageBuilderGenerator() {}
@@ -115,13 +120,11 @@
// oneof
std::map<std::string, std::string> vars;
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- vars["oneof_name"] =
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name;
+ for (auto oneof : oneofs_) {
+ vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name;
vars["oneof_capitalized_name"] =
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->capitalized_name;
- vars["oneof_index"] = StrCat(descriptor_->oneof_decl(i)->index());
+ context_->GetOneofGeneratorInfo(oneof)->capitalized_name;
+ vars["oneof_index"] = StrCat(oneof->index());
// oneofCase_ and oneof_
printer->Print(vars,
"private int $oneof_name$Case_ = 0;\n"
@@ -308,7 +311,7 @@
printer->Indent();
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
+ if (!IsRealOneof(descriptor_->field(i))) {
field_generators_.get(descriptor_->field(i))
.GenerateFieldBuilderInitializationCode(printer);
}
@@ -328,18 +331,17 @@
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
+ if (!IsRealOneof(descriptor_->field(i))) {
field_generators_.get(descriptor_->field(i))
.GenerateBuilderClearCode(printer);
}
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
+ for (auto oneof : oneofs_) {
printer->Print(
"$oneof_name$Case_ = 0;\n"
"$oneof_name$_ = null;\n",
- "oneof_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name);
+ "oneof_name", context_->GetOneofGeneratorInfo(oneof)->name);
}
printer->Outdent();
@@ -423,10 +425,9 @@
"bit_field_name", GetBitFieldName(i));
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "result.$oneof_name$Case_ = $oneof_name$Case_;\n", "oneof_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name);
+ for (auto oneof : oneofs_) {
+ printer->Print("result.$oneof_name$Case_ = $oneof_name$Case_;\n",
+ "oneof_name", context_->GetOneofGeneratorInfo(oneof)->name);
}
printer->Outdent();
@@ -535,21 +536,20 @@
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
+ if (!IsRealOneof(descriptor_->field(i))) {
field_generators_.get(descriptor_->field(i))
.GenerateMergingCode(printer);
}
}
// Merge oneof fields.
- for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
+ for (auto oneof : oneofs_) {
printer->Print("switch (other.get$oneof_capitalized_name$Case()) {\n",
"oneof_capitalized_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->capitalized_name);
+ context_->GetOneofGeneratorInfo(oneof)->capitalized_name);
printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
+ for (int j = 0; j < oneof->field_count(); j++) {
+ const FieldDescriptor* field = oneof->field(j);
printer->Print("case $field_name$: {\n", "field_name",
ToUpper(field->name()));
printer->Indent();
@@ -563,9 +563,7 @@
" break;\n"
"}\n",
"cap_oneof_name",
- ToUpper(
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->name));
+ ToUpper(context_->GetOneofGeneratorInfo(oneof)->name));
printer->Outdent();
printer->Print("}\n");
}
@@ -655,19 +653,8 @@
"name", info->capitalized_name);
break;
case FieldDescriptor::LABEL_OPTIONAL:
- if (!SupportFieldPresence(descriptor_->file()) &&
- field->containing_oneof() != NULL) {
- const OneofDescriptor* oneof = field->containing_oneof();
- const OneofGeneratorInfo* oneof_info =
- context_->GetOneofGeneratorInfo(oneof);
- printer->Print("if ($oneof_name$Case_ == $field_number$) {\n",
- "oneof_name", oneof_info->name, "field_number",
- StrCat(field->number()));
- } else {
- printer->Print("if (has$name$()) {\n", "name",
- info->capitalized_name);
- }
printer->Print(
+ "if (has$name$()) {\n"
" if (!get$name$().isInitialized()) {\n"
" return false;\n"
" }\n"
diff --git a/src/google/protobuf/compiler/java/java_message_builder.h b/src/google/protobuf/compiler/java/java_message_builder.h
index a31d0ba..fcd73b3 100644
--- a/src/google/protobuf/compiler/java/java_message_builder.h
+++ b/src/google/protobuf/compiler/java/java_message_builder.h
@@ -76,6 +76,7 @@
Context* context_;
ClassNameResolver* name_resolver_;
FieldGeneratorMap<ImmutableFieldGenerator> field_generators_;
+ std::set<const OneofDescriptor*> oneofs_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageBuilderGenerator);
};
diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.cc b/src/google/protobuf/compiler/java/java_message_builder_lite.cc
index 6e78fb7..7b69a9a 100644
--- a/src/google/protobuf/compiler/java/java_message_builder_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder_lite.cc
@@ -67,6 +67,11 @@
GOOGLE_CHECK(!HasDescriptorMethods(descriptor->file(), context->EnforceLite()))
<< "Generator factory error: A lite message generator is used to "
"generate non-lite messages.";
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ if (IsRealOneof(descriptor_->field(i))) {
+ oneofs_.insert(descriptor_->field(i)->containing_oneof());
+ }
+ }
}
MessageBuilderLiteGenerator::~MessageBuilderLiteGenerator() {}
@@ -88,13 +93,11 @@
// oneof
std::map<std::string, std::string> vars;
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- vars["oneof_name"] =
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name;
+ for (auto oneof : oneofs_) {
+ vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name;
vars["oneof_capitalized_name"] =
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->capitalized_name;
- vars["oneof_index"] = StrCat(descriptor_->oneof_decl(i)->index());
+ context_->GetOneofGeneratorInfo(oneof)->capitalized_name;
+ vars["oneof_index"] = StrCat(oneof->index());
// oneofCase() and clearOneof()
printer->Print(vars,
diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.h b/src/google/protobuf/compiler/java/java_message_builder_lite.h
index e0a48dc..3402adf 100644
--- a/src/google/protobuf/compiler/java/java_message_builder_lite.h
+++ b/src/google/protobuf/compiler/java/java_message_builder_lite.h
@@ -73,6 +73,7 @@
Context* context_;
ClassNameResolver* name_resolver_;
FieldGeneratorMap<ImmutableFieldLiteGenerator> field_generators_;
+ std::set<const OneofDescriptor*> oneofs_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageBuilderLiteGenerator);
};
diff --git a/src/google/protobuf/compiler/java/java_message_field.cc b/src/google/protobuf/compiler/java/java_message_field.cc
index 273faec..67273fa 100644
--- a/src/google/protobuf/compiler/java/java_message_field.cc
+++ b/src/google/protobuf/compiler/java/java_message_field.cc
@@ -74,7 +74,7 @@
ExposePublicParser(descriptor->message_type()->file()) ? "PARSER"
: "parser()";
- if (SupportFieldPresence(descriptor->file())) {
+ if (HasHasbit(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
(*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
@@ -97,7 +97,7 @@
(*variables)["name"] + "_ != null";
}
- // For repated builders, one bit is used for whether the array is immutable.
+ // For repeated builders, one bit is used for whether the array is immutable.
(*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex);
(*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex);
(*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex);
@@ -131,7 +131,7 @@
ImmutableMessageFieldGenerator::~ImmutableMessageFieldGenerator() {}
int ImmutableMessageFieldGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ return HasHasbit(descriptor_) ? 1 : 0;
}
int ImmutableMessageFieldGenerator::GetNumBitsForBuilder() const {
@@ -160,10 +160,11 @@
printer->Print(variables_, "private $type$ $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
@@ -171,6 +172,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
@@ -179,6 +181,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
@@ -188,6 +191,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$_ != null;\n"
"}\n");
@@ -195,6 +199,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
@@ -202,6 +207,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$() {\n"
" return get$capitalized_name$();\n"
@@ -246,7 +252,7 @@
// non-nested builder case. It only creates a nested builder lazily on
// demand and then forever delegates to it after creation.
- bool support_field_presence = SupportFieldPresence(descriptor_->file());
+ bool has_hasbit = HasHasbit(descriptor_);
printer->Print(variables_, "private $type$ $name$_;\n");
@@ -262,7 +268,7 @@
// boolean hasField()
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
- if (support_field_presence) {
+ if (has_hasbit) {
printer->Print(
variables_,
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
@@ -323,7 +329,7 @@
printer,
"$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)",
- support_field_presence
+ has_hasbit
? "if ($get_has_field_bit_builder$ &&\n"
" $name$_ != null &&\n"
" $name$_ != $type$.getDefaultInstance()) {\n"
@@ -354,9 +360,9 @@
"$name$_ = null;\n"
"$on_changed$\n",
- support_field_presence ? "$name$Builder_.clear();\n"
- : "$name$_ = null;\n"
- "$name$Builder_ = null;\n",
+ has_hasbit ? "$name$Builder_.clear();\n"
+ : "$name$_ = null;\n"
+ "$name$Builder_ = null;\n",
"$clear_has_field_bit_builder$\n"
"return this;\n");
@@ -402,7 +408,7 @@
void ImmutableMessageFieldGenerator::GenerateFieldBuilderInitializationCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
printer->Print(variables_, "get$capitalized_name$FieldBuilder();\n");
}
}
@@ -412,7 +418,7 @@
void ImmutableMessageFieldGenerator::GenerateBuilderClearCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
PrintNestedBuilderCondition(printer, "$name$_ = null;\n",
"$name$Builder_.clear();\n");
@@ -435,7 +441,7 @@
void ImmutableMessageFieldGenerator::GenerateBuildingCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n");
printer->Indent();
PrintNestedBuilderCondition(printer, "result.$name$_ = $name$_;\n",
@@ -537,12 +543,14 @@
PrintExtraFieldInfo(variables_, printer);
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
@@ -553,6 +561,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$() {\n"
" if ($has_oneof_case_message$) {\n"
@@ -581,6 +590,7 @@
// boolean hasField()
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
@@ -589,7 +599,9 @@
// Field getField()
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
PrintNestedBuilderFunction(
- printer, "$deprecation$public $type$ ${$get$capitalized_name$$}$()",
+ printer,
+ "@java.lang.Override\n"
+ "$deprecation$public $type$ ${$get$capitalized_name$$}$()",
"if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
@@ -687,6 +699,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$() {\n"
" if (($has_oneof_case_message$) && ($name$Builder_ != null)) {\n"
@@ -846,6 +859,7 @@
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
@@ -854,6 +868,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
" ${$get$capitalized_name$OrBuilderList$}$() {\n"
" return $name$_;\n"
@@ -862,6 +877,7 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
@@ -869,12 +885,14 @@
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$(\n"
" int index) {\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 cb5f3c0..b17859d 100644
--- a/src/google/protobuf/compiler/java/java_message_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc
@@ -70,7 +70,7 @@
descriptor->options().deprecated() ? "@java.lang.Deprecated " : "";
(*variables)["required"] = descriptor->is_required() ? "true" : "false";
- if (SupportFieldPresence(descriptor->file())) {
+ if (HasHasbit(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
@@ -89,9 +89,6 @@
(*variables)["name"] + "_ != null";
}
- // For repeated builders, the underlying list tracks mutability state.
- (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()";
-
(*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex);
(*variables)["set_has_field_bit_to_local"] =
@@ -119,7 +116,11 @@
ImmutableMessageFieldLiteGenerator::~ImmutableMessageFieldLiteGenerator() {}
int ImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ // TODO(dweis): We don't need a has bit for messages as they have null
+ // sentinels and no user should be reflecting on this. We could save some
+ // bits by setting to 0 and updating the runtimes but this might come at a
+ // runtime performance cost since we can't memoize has-bit reads.
+ return HasHasbit(descriptor_) ? 1 : 0;
}
void ImmutableMessageFieldLiteGenerator::GenerateInterfaceMembers(
@@ -136,7 +137,7 @@
printer->Print(variables_, "private $type$ $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
@@ -279,7 +280,7 @@
WriteIntToUtf16CharSequence(descriptor_->number(), output);
WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_),
output);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
WriteIntToUtf16CharSequence(messageBitIndex_, output);
}
printer->Print(variables_, "\"$name$_\",\n");
@@ -528,9 +529,11 @@
printer->Print(
variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
- " if (!$is_mutable$) {\n"
+ // Use a temporary to avoid a redundant iget-object.
+ " com.google.protobuf.Internal.ProtobufList<$type$> tmp = $name$_;\n"
+ " if (!tmp.isModifiable()) {\n"
" $name$_ =\n"
- " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"
+ " com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);\n"
" }\n"
"}\n"
"\n");
diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc
index c223311..4afffdc 100644
--- a/src/google/protobuf/compiler/java/java_message_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_lite.cc
@@ -73,6 +73,11 @@
GOOGLE_CHECK(!HasDescriptorMethods(descriptor->file(), context->EnforceLite()))
<< "Generator factory error: A lite message generator is used to "
"generate non-lite messages.";
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ if (IsRealOneof(descriptor_->field(i))) {
+ oneofs_.insert(descriptor_->field(i)->containing_oneof());
+ }
+ }
}
ImmutableMessageLiteGenerator::~ImmutableMessageLiteGenerator() {}
@@ -134,15 +139,13 @@
field_generators_.get(descriptor_->field(i))
.GenerateInterfaceMembers(printer);
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
+ for (auto oneof : oneofs_) {
printer->Print(
"\n"
"public $classname$.$oneof_capitalized_name$Case "
"get$oneof_capitalized_name$Case();\n",
"oneof_capitalized_name",
- context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
- ->capitalized_name,
- "classname",
+ context_->GetOneofGeneratorInfo(oneof)->capitalized_name, "classname",
context_->GetNameResolver()->GetImmutableClassName(descriptor_));
}
printer->Outdent();
@@ -224,12 +227,11 @@
// oneof
std::map<std::string, std::string> vars;
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
+ for (auto oneof : oneofs_) {
vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name;
vars["oneof_capitalized_name"] =
context_->GetOneofGeneratorInfo(oneof)->capitalized_name;
- vars["oneof_index"] = StrCat(oneof->index());
+ vars["oneof_index"] = StrCat((oneof)->index());
// oneofCase_ and oneof_
printer->Print(vars,
"private int $oneof_name$Case_ = 0;\n"
@@ -237,8 +239,8 @@
// OneofCase enum
printer->Print(vars, "public enum $oneof_capitalized_name$Case {\n");
printer->Indent();
- for (int j = 0; j < oneof->field_count(); j++) {
- const FieldDescriptor* field = oneof->field(j);
+ for (int j = 0; j < (oneof)->field_count(); j++) {
+ const FieldDescriptor* field = (oneof)->field(j);
printer->Print("$field_name$($field_number$),\n", "field_name",
ToUpper(field->name()), "field_number",
StrCat(field->number()));
@@ -262,8 +264,8 @@
"\n"
"public static $oneof_capitalized_name$Case forNumber(int value) {\n"
" switch (value) {\n");
- for (int j = 0; j < oneof->field_count(); j++) {
- const FieldDescriptor* field = oneof->field(j);
+ for (int j = 0; j < (oneof)->field_count(); j++) {
+ const FieldDescriptor* field = (oneof)->field(j);
printer->Print(" case $field_number$: return $field_name$;\n",
"field_number", StrCat(field->number()),
"field_name", ToUpper(field->name()));
@@ -472,7 +474,7 @@
std::vector<uint16> chars;
int flags = 0;
- if (SupportFieldPresence(descriptor_->file())) {
+ if (IsProto2(descriptor_->file())) {
flags |= 0x1;
}
if (descriptor_->options().message_set_wire_format()) {
@@ -489,9 +491,8 @@
printer->Indent();
// Record the number of oneofs.
- WriteIntToUtf16CharSequence(descriptor_->oneof_decl_count(), &chars);
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
+ WriteIntToUtf16CharSequence(oneofs_.size(), &chars);
+ for (auto oneof : oneofs_) {
printer->Print(
"\"$oneof_name$_\",\n"
"\"$oneof_name$Case_\",\n",
@@ -715,7 +716,7 @@
// ===================================================================
void ImmutableMessageLiteGenerator::GenerateInitializers(io::Printer* printer) {
for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
+ if (!IsRealOneof(descriptor_->field(i))) {
field_generators_.get(descriptor_->field(i))
.GenerateInitializationCode(printer);
}
diff --git a/src/google/protobuf/compiler/java/java_names.h b/src/google/protobuf/compiler/java/java_names.h
index a8efbb4..73a340e 100644
--- a/src/google/protobuf/compiler/java/java_names.h
+++ b/src/google/protobuf/compiler/java/java_names.h
@@ -90,7 +90,7 @@
// Requires:
// descriptor != NULL
// Returns:
-// Captialized camel case name field name.
+// Capitalized camel case name field name.
std::string CapitalizedFieldName(const FieldDescriptor* descriptor);
// Requires:
diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/java_primitive_field.cc
index d06b534..2572aee 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field.cc
@@ -133,7 +133,7 @@
}
(*variables)["on_changed"] = "onChanged();";
- if (SupportFieldPresence(descriptor->file())) {
+ if (SupportFieldPresence(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
(*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
@@ -161,7 +161,7 @@
}
}
- // For repated builders, one bit is used for whether the array is immutable.
+ // For repeated builders, one bit is used for whether the array is immutable.
(*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex);
(*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex);
(*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex);
@@ -195,7 +195,7 @@
ImmutablePrimitiveFieldGenerator::~ImmutablePrimitiveFieldGenerator() {}
int ImmutablePrimitiveFieldGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ return SupportFieldPresence(descriptor_) ? 1 : 0;
}
int ImmutablePrimitiveFieldGenerator::GetNumBitsForBuilder() const {
@@ -204,7 +204,7 @@
void ImmutablePrimitiveFieldGenerator::GenerateInterfaceMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
@@ -217,10 +217,11 @@
io::Printer* printer) const {
printer->Print(variables_, "private $field_type$ $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
@@ -229,6 +230,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
@@ -239,10 +241,11 @@
io::Printer* printer) const {
printer->Print(variables_, "private $field_type$ $name$_ $default_init$;\n");
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
@@ -251,6 +254,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
@@ -292,6 +296,7 @@
"}\n");
}
+
void ImmutablePrimitiveFieldGenerator::GenerateFieldBuilderInitializationCode(
io::Printer* printer) const {
// noop for primitives
@@ -313,7 +318,7 @@
void ImmutablePrimitiveFieldGenerator::GenerateMergingCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
printer->Print(variables_,
"if (other.has$capitalized_name$()) {\n"
" set$capitalized_name$(other.get$capitalized_name$());\n"
@@ -328,7 +333,7 @@
void ImmutablePrimitiveFieldGenerator::GenerateBuildingCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
if (IsDefaultValueJavaDefault(descriptor_)) {
printer->Print(variables_,
"if ($get_has_field_bit_from_local$) {\n"
@@ -492,10 +497,11 @@
void ImmutablePrimitiveOneofFieldGenerator::GenerateMembers(
io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
@@ -504,6 +510,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
@@ -515,7 +522,7 @@
void ImmutablePrimitiveOneofFieldGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -663,6 +670,7 @@
PrintExtraFieldInfo(variables_, printer);
WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.util.List<$boxed_type$>\n"
" ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
index f038412..53366b2 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
@@ -32,6 +32,8 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <google/protobuf/compiler/java/java_primitive_field_lite.h>
+
#include <map>
#include <string>
@@ -41,7 +43,6 @@
#include <google/protobuf/compiler/java/java_doc_comment.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
-#include <google/protobuf/compiler/java/java_primitive_field_lite.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
@@ -139,7 +140,7 @@
(*variables)["fixed_size"] = StrCat(fixed_size);
}
- if (SupportFieldPresence(descriptor->file())) {
+ if (SupportFieldPresence(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
@@ -164,9 +165,6 @@
}
}
- // For repeated builders, the underlying list tracks mutability state.
- (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()";
-
(*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex);
(*variables)["set_has_field_bit_to_local"] =
@@ -190,12 +188,12 @@
ImmutablePrimitiveFieldLiteGenerator::~ImmutablePrimitiveFieldLiteGenerator() {}
int ImmutablePrimitiveFieldLiteGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ return SupportFieldPresence(descriptor_) ? 1 : 0;
}
void ImmutablePrimitiveFieldLiteGenerator::GenerateInterfaceMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
@@ -215,7 +213,7 @@
}
printer->Print(variables_, "private $field_type$ $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -261,7 +259,7 @@
void ImmutablePrimitiveFieldLiteGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -303,12 +301,13 @@
printer->Annotate("{", "}", descriptor_);
}
+
void ImmutablePrimitiveFieldLiteGenerator::GenerateFieldInfo(
io::Printer* printer, std::vector<uint16>* output) const {
WriteIntToUtf16CharSequence(descriptor_->number(), output);
WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_),
output);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
WriteIntToUtf16CharSequence(messageBitIndex_, output);
}
printer->Print(variables_, "\"$name$_\",\n");
@@ -346,7 +345,7 @@
void ImmutablePrimitiveOneofFieldLiteGenerator::GenerateMembers(
io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -396,7 +395,7 @@
void ImmutablePrimitiveOneofFieldLiteGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -511,9 +510,11 @@
printer->Print(
variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
- " if (!$is_mutable$) {\n"
+ // Use a temporary to avoid a redundant iget-object.
+ " $field_list_type$ tmp = $name$_;\n"
+ " if (!tmp.isModifiable()) {\n"
" $name$_ =\n"
- " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"
+ " com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);\n"
" }\n"
"}\n");
diff --git a/src/google/protobuf/compiler/java/java_string_field.cc b/src/google/protobuf/compiler/java/java_string_field.cc
index 4dec394..8e1595b 100644
--- a/src/google/protobuf/compiler/java/java_string_field.cc
+++ b/src/google/protobuf/compiler/java/java_string_field.cc
@@ -90,7 +90,7 @@
descriptor->options().deprecated() ? "@java.lang.Deprecated " : "";
(*variables)["on_changed"] = "onChanged();";
- if (SupportFieldPresence(descriptor->file())) {
+ if (SupportFieldPresence(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
(*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
@@ -147,7 +147,7 @@
ImmutableStringFieldGenerator::~ImmutableStringFieldGenerator() {}
int ImmutableStringFieldGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ return SupportFieldPresence(descriptor_) ? 1 : 0;
}
int ImmutableStringFieldGenerator::GetNumBitsForBuilder() const {
@@ -157,7 +157,7 @@
// A note about how strings are handled. This code used to just store a String
// in the Message. This had two issues:
//
-// 1. It wouldn't roundtrip byte arrays that were not vaid UTF-8 encoded
+// 1. It wouldn't roundtrip byte arrays that were not valid UTF-8 encoded
// strings, but rather fields that were raw bytes incorrectly marked
// as strings in the proto file. This is common because in the proto1
// syntax, string was the way to indicate bytes and C++ engineers can
@@ -188,7 +188,7 @@
// UnmodifiableLazyStringList.
void ImmutableStringFieldGenerator::GenerateInterfaceMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
@@ -207,10 +207,11 @@
printer->Print(variables_, "private volatile java.lang.Object $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
@@ -220,6 +221,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (ref instanceof java.lang.String) {\n"
@@ -243,6 +245,7 @@
"}\n");
WriteFieldStringBytesAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref = $name$_;\n"
@@ -263,7 +266,7 @@
io::Printer* printer) const {
printer->Print(variables_,
"private java.lang.Object $name$_ $default_init$;\n");
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -381,7 +384,7 @@
void ImmutableStringFieldGenerator::GenerateMergingCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
// Allow a slight breach of abstraction here in order to avoid forcing
// all string fields to Strings when copying fields from a Message.
printer->Print(variables_,
@@ -401,7 +404,7 @@
void ImmutableStringFieldGenerator::GenerateBuildingCode(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
printer->Print(variables_,
"if ($get_has_field_bit_from_local$) {\n"
" $set_has_field_bit_to_local$;\n"
@@ -482,7 +485,7 @@
io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -548,10 +551,11 @@
void ImmutableStringOneofFieldGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
@@ -561,6 +565,7 @@
WriteFieldAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(
variables_,
+ "@java.lang.Override\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
@@ -590,6 +595,7 @@
WriteFieldStringBytesAccessorDocComment(printer, descriptor_, GETTER);
printer->Print(variables_,
+ "@java.lang.Override\n"
"$deprecation$public com.google.protobuf.ByteString\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref $default_init$;\n"
diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.cc b/src/google/protobuf/compiler/java/java_string_field_lite.cc
index b2f22a5..432a789 100644
--- a/src/google/protobuf/compiler/java/java_string_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_string_field_lite.cc
@@ -85,7 +85,7 @@
descriptor->options().deprecated() ? "@java.lang.Deprecated " : "";
(*variables)["required"] = descriptor->is_required() ? "true" : "false";
- if (SupportFieldPresence(descriptor->file())) {
+ if (SupportFieldPresence(descriptor)) {
// For singular messages and builders, one bit is used for the hasField bit.
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
@@ -104,9 +104,6 @@
"!" + (*variables)["name"] + "_.isEmpty()";
}
- // For repeated builders, the underlying list tracks mutability state.
- (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()";
-
(*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex);
(*variables)["set_has_field_bit_to_local"] =
@@ -130,14 +127,14 @@
ImmutableStringFieldLiteGenerator::~ImmutableStringFieldLiteGenerator() {}
int ImmutableStringFieldLiteGenerator::GetNumBitsForMessage() const {
- return SupportFieldPresence(descriptor_->file()) ? 1 : 0;
+ return SupportFieldPresence(descriptor_) ? 1 : 0;
}
// A note about how strings are handled. In the SPEED and CODE_SIZE runtimes,
// strings are not stored as java.lang.String in the Message because of two
// issues:
//
-// 1. It wouldn't roundtrip byte arrays that were not vaid UTF-8 encoded
+// 1. It wouldn't roundtrip byte arrays that were not valid UTF-8 encoded
// strings, but rather fields that were raw bytes incorrectly marked
// as strings in the proto file. This is common because in the proto1
// syntax, string was the way to indicate bytes and C++ engineers can
@@ -160,7 +157,7 @@
// shouldn't be necessary or used on devices.
void ImmutableStringFieldLiteGenerator::GenerateInterfaceMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
@@ -179,7 +176,7 @@
printer->Print(variables_, "private java.lang.String $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -241,7 +238,7 @@
void ImmutableStringFieldLiteGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -309,7 +306,7 @@
WriteIntToUtf16CharSequence(descriptor_->number(), output);
WriteIntToUtf16CharSequence(GetExperimentalJavaFieldType(descriptor_),
output);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (HasHasbit(descriptor_)) {
WriteIntToUtf16CharSequence(messageBitIndex_, output);
}
printer->Print(variables_, "\"$name$_\",\n");
@@ -341,7 +338,7 @@
io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -421,7 +418,7 @@
void ImmutableStringOneofFieldLiteGenerator::GenerateBuilderMembers(
io::Printer* printer) const {
- if (SupportFieldPresence(descriptor_->file())) {
+ if (SupportFieldPresence(descriptor_)) {
WriteFieldAccessorDocComment(printer, descriptor_, HAZZER);
printer->Print(
variables_,
@@ -567,9 +564,12 @@
printer->Print(
variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
- " if (!$is_mutable$) {\n"
+ // Use a temporary to avoid a redundant iget-object.
+ " com.google.protobuf.Internal.ProtobufList<java.lang.String> tmp =\n"
+ " $name$_;"
+ " if (!tmp.isModifiable()) {\n"
" $name$_ =\n"
- " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"
+ " com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);\n"
" }\n"
"}\n");
diff --git a/src/google/protobuf/compiler/main.cc b/src/google/protobuf/compiler/main.cc
index b723b14..5239e09 100644
--- a/src/google/protobuf/compiler/main.cc
+++ b/src/google/protobuf/compiler/main.cc
@@ -69,17 +69,17 @@
// Proto2 Python
python::Generator py_generator;
- cli.RegisterGenerator("--python_out", &py_generator,
+ cli.RegisterGenerator("--python_out", "--python_opt", &py_generator,
"Generate Python source file.");
// PHP
php::Generator php_generator;
- cli.RegisterGenerator("--php_out", &php_generator,
+ cli.RegisterGenerator("--php_out", "--php_opt", &php_generator,
"Generate PHP source file.");
// Ruby
ruby::Generator rb_generator;
- cli.RegisterGenerator("--ruby_out", &rb_generator,
+ cli.RegisterGenerator("--ruby_out", "--ruby_opt", &rb_generator,
"Generate Ruby source file.");
// CSharp
@@ -94,7 +94,7 @@
// JavaScript
js::Generator js_generator;
- cli.RegisterGenerator("--js_out", &js_generator,
+ cli.RegisterGenerator("--js_out", "--js_opt", &js_generator,
"Generate JavaScript source.");
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 e88b18b..8b82901 100644
--- a/src/google/protobuf/compiler/mock_code_generator.cc
+++ b/src/google/protobuf/compiler/mock_code_generator.cc
@@ -87,6 +87,15 @@
MockCodeGenerator::~MockCodeGenerator() {}
+uint64 MockCodeGenerator::GetSupportedFeatures() const {
+ uint64 all_features = CodeGenerator::FEATURE_PROTO3_OPTIONAL;
+ return all_features & ~suppressed_features_;
+}
+
+void MockCodeGenerator::SuppressFeatures(uint64 features) {
+ suppressed_features_ = features;
+}
+
void MockCodeGenerator::ExpectGenerated(
const std::string& name, const std::string& parameter,
const std::string& insertions, const std::string& file,
@@ -320,7 +329,7 @@
const std::string& file, const std::string& parsed_file_list,
const std::string& first_message_name) {
return strings::Substitute("$0: $1, $2, $3, $4\n", generator_name, parameter,
- file, first_message_name, parsed_file_list);
+ file, first_message_name, parsed_file_list);
}
} // namespace compiler
diff --git a/src/google/protobuf/compiler/mock_code_generator.h b/src/google/protobuf/compiler/mock_code_generator.h
index 082ba18..70a840e 100644
--- a/src/google/protobuf/compiler/mock_code_generator.h
+++ b/src/google/protobuf/compiler/mock_code_generator.h
@@ -106,12 +106,15 @@
// implements CodeGenerator ----------------------------------------
- virtual bool Generate(const FileDescriptor* file,
- const std::string& parameter, GeneratorContext* context,
- std::string* error) const;
+ bool Generate(const FileDescriptor* file, const std::string& parameter,
+ GeneratorContext* context, std::string* error) const override;
+
+ uint64 GetSupportedFeatures() const override;
+ void SuppressFeatures(uint64 features);
private:
std::string name_;
+ uint64 suppressed_features_ = 0;
static std::string GetOutputFileContent(const std::string& generator_name,
const std::string& parameter,
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
index 9890d0a..3893801 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
@@ -104,13 +104,13 @@
"int32_t $owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message) {\n"
" GPBDescriptor *descriptor = [$owning_message_class$ descriptor];\n"
" GPBFieldDescriptor *field = [descriptor fieldWithNumber:$field_number_name$];\n"
- " return GPBGetMessageInt32Field(message, field);\n"
+ " return GPBGetMessageRawEnumField(message, field);\n"
"}\n"
"\n"
"void Set$owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message, int32_t value) {\n"
" GPBDescriptor *descriptor = [$owning_message_class$ descriptor];\n"
" GPBFieldDescriptor *field = [descriptor fieldWithNumber:$field_number_name$];\n"
- " GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);\n"
+ " GPBSetMessageRawEnumField(message, field, value);\n"
"}\n"
"\n");
}
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
index bf65de3..b514b8a 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
@@ -84,24 +84,24 @@
io::Printer* printer) {
std::map<string, string> vars;
vars["root_class_and_method_name"] = root_class_and_method_name_;
- vars["extended_type"] = ClassName(descriptor_->containing_type());
+ const string containing_type = ClassName(descriptor_->containing_type());
+ vars["extended_type"] = ObjCClass(containing_type);
vars["number"] = StrCat(descriptor_->number());
std::vector<string> options;
if (descriptor_->is_repeated()) options.push_back("GPBExtensionRepeated");
if (descriptor_->is_packed()) options.push_back("GPBExtensionPacked");
- if (descriptor_->containing_type()->options().message_set_wire_format())
+ if (descriptor_->containing_type()->options().message_set_wire_format()) {
options.push_back("GPBExtensionSetWireFormat");
-
+ }
vars["options"] = BuildFlagsString(FLAGTYPE_EXTENSION, options);
ObjectiveCType objc_type = GetObjectiveCType(descriptor_);
- string singular_type;
if (objc_type == OBJECTIVECTYPE_MESSAGE) {
- vars["type"] = string("GPBStringifySymbol(") +
- ClassName(descriptor_->message_type()) + ")";
+ std::string message_type = ClassName(descriptor_->message_type());
+ vars["type"] = ObjCClass(message_type);
} else {
- vars["type"] = "NULL";
+ vars["type"] = "Nil";
}
vars["default_name"] = GPBGenericValueFieldName(descriptor_);
@@ -124,8 +124,8 @@
"{\n"
" .defaultValue.$default_name$ = $default$,\n"
" .singletonName = GPBStringifySymbol($root_class_and_method_name$),\n"
- " .extendedClass = GPBStringifySymbol($extended_type$),\n"
- " .messageOrGroupClassName = $type$,\n"
+ " .extendedClass.clazz = $extended_type$,\n"
+ " .messageOrGroupClass.clazz = $type$,\n"
" .enumDescriptorFunc = $enum_desc_func_name$,\n"
" .fieldNumber = $number$,\n"
" .dataType = $extension_type$,\n"
@@ -133,11 +133,23 @@
"},\n");
}
+void ExtensionGenerator::DetermineObjectiveCClassDefinitions(
+ std::set<string>* fwd_decls) {
+ string extended_type = ClassName(descriptor_->containing_type());
+ fwd_decls->insert(ObjCClassDeclaration(extended_type));
+ ObjectiveCType objc_type = GetObjectiveCType(descriptor_);
+ if (objc_type == OBJECTIVECTYPE_MESSAGE) {
+ string message_type = ClassName(descriptor_->message_type());
+ fwd_decls->insert(ObjCClassDeclaration(message_type));
+ }
+}
+
void ExtensionGenerator::GenerateRegistrationSource(io::Printer* printer) {
printer->Print(
"[registry addExtension:$root_class_and_method_name$];\n",
"root_class_and_method_name", root_class_and_method_name_);
}
+
} // namespace objectivec
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_extension.h b/src/google/protobuf/compiler/objectivec/objectivec_extension.h
index d49a4f1..1bc19d8 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_extension.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_extension.h
@@ -51,6 +51,7 @@
void GenerateMembersHeader(io::Printer* printer);
void GenerateStaticVariablesInitialization(io::Printer* printer);
void GenerateRegistrationSource(io::Printer* printer);
+ void DetermineObjectiveCClassDefinitions(std::set<string>* fwd_decls);
private:
string method_name_;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
index f585941..e8360a5 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
@@ -91,14 +91,22 @@
if (descriptor->type() == FieldDescriptor::TYPE_ENUM) {
field_flags.push_back("GPBFieldHasEnumDescriptor");
}
+ // It will clear on a zero value if...
+ // - not repeated/map
+ // - doesn't have presence
+ bool clear_on_zero =
+ (!descriptor->is_repeated() && !descriptor->has_presence());
+ if (clear_on_zero) {
+ field_flags.push_back("GPBFieldClearHasIvarOnZero");
+ }
(*variables)["fieldflags"] = BuildFlagsString(FLAGTYPE_FIELD, field_flags);
(*variables)["default"] = DefaultValue(descriptor);
(*variables)["default_name"] = GPBGenericValueFieldName(descriptor);
- (*variables)["dataTypeSpecific_name"] = "className";
- (*variables)["dataTypeSpecific_value"] = "NULL";
+ (*variables)["dataTypeSpecific_name"] = "clazz";
+ (*variables)["dataTypeSpecific_value"] = "Nil";
(*variables)["storage_offset_value"] =
"(uint32_t)offsetof(" + classname + "__storage_, " + camel_case_name + ")";
@@ -181,6 +189,11 @@
// Nothing
}
+void FieldGenerator::DetermineObjectiveCClassDefinitions(
+ std::set<string>* fwd_decls) const {
+ // Nothing
+}
+
void FieldGenerator::GenerateFieldDescription(
io::Printer* printer, bool include_default) const {
// Printed in the same order as the structure decl.
@@ -233,13 +246,18 @@
}
void FieldGenerator::SetOneofIndexBase(int index_base) {
- if (descriptor_->containing_oneof() != NULL) {
- int index = descriptor_->containing_oneof()->index() + index_base;
+ const OneofDescriptor *oneof = descriptor_->real_containing_oneof();
+ if (oneof != NULL) {
+ int index = oneof->index() + index_base;
// Flip the sign to mark it as a oneof.
variables_["has_index"] = StrCat(-index);
}
}
+bool FieldGenerator::WantsHasProperty(void) const {
+ return descriptor_->has_presence() && !descriptor_->real_containing_oneof();
+}
+
void FieldGenerator::FinishInitialization(void) {
// If "property_type" wasn't set, make it "storage_type".
if ((variables_.find("property_type") == variables_.end()) &&
@@ -284,20 +302,8 @@
}
}
-bool SingleFieldGenerator::WantsHasProperty(void) const {
- if (descriptor_->containing_oneof() != NULL) {
- // If in a oneof, it uses the oneofcase instead of a has bit.
- return false;
- }
- if (HasFieldPresence(descriptor_->file())) {
- // In proto1/proto2, every field has a has_$name$() method.
- return true;
- }
- return false;
-}
-
bool SingleFieldGenerator::RuntimeUsesHasBit(void) const {
- if (descriptor_->containing_oneof() != NULL) {
+ if (descriptor_->real_containing_oneof()) {
// The oneof tracks what is set instead.
return false;
}
@@ -397,13 +403,8 @@
printer->Print("\n");
}
-bool RepeatedFieldGenerator::WantsHasProperty(void) const {
- // Consumer check the array size/existance rather than a has bit.
- return false;
-}
-
bool RepeatedFieldGenerator::RuntimeUsesHasBit(void) const {
- return false; // The array having anything is what is used.
+ return false; // The array (or map/dict) having anything is what is used.
}
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.h b/src/google/protobuf/compiler/objectivec/objectivec_field.h
index 24465d0..2ebe55b 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_field.h
@@ -66,6 +66,7 @@
// Exposed for subclasses, should always call it on the parent class also.
virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
+ virtual void DetermineObjectiveCClassDefinitions(std::set<string>* fwd_decls) const;
// Used during generation, not intended to be extended by subclasses.
void GenerateFieldDescription(
@@ -95,7 +96,7 @@
FieldGenerator(const FieldDescriptor* descriptor, const Options& options);
virtual void FinishInitialization(void);
- virtual bool WantsHasProperty(void) const = 0;
+ bool WantsHasProperty(void) const;
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
@@ -118,7 +119,6 @@
protected:
SingleFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
- virtual bool WantsHasProperty(void) const;
};
// Subclass with common support for when the field ends up as an ObjC Object.
@@ -155,7 +155,6 @@
RepeatedFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
virtual void FinishInitialization(void);
- virtual bool WantsHasProperty(void) const;
};
// Convenience class which constructs FieldGenerators for a Descriptor.
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
index 7bc585e..04733ca 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
@@ -52,7 +52,7 @@
namespace {
// This is also found in GPBBootstrap.h, and needs to be kept in sync.
-const int32 GOOGLE_PROTOBUF_OBJC_VERSION = 30002;
+const int32 GOOGLE_PROTOBUF_OBJC_VERSION = 30004;
const char* kHeaderExtension = ".pbobjc.h";
@@ -303,12 +303,12 @@
" * 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"
+ "GPB_FINAL @interface $root_class_name$ : GPBRootObject\n"
"@end\n"
"\n",
"root_class_name", root_class_name_);
- if (extension_generators_.size() > 0) {
+ if (!extension_generators_.empty()) {
// The dynamic methods block is only needed if there are extensions.
printer->Print(
"@interface $root_class_name$ (DynamicMethods)\n",
@@ -319,7 +319,7 @@
}
printer->Print("@end\n\n");
- } // extension_generators_.size() > 0
+ } // !extension_generators_.empty()
for (const auto& generator : message_generators_) {
generator->GenerateMessageHeader(printer);
@@ -398,10 +398,20 @@
}
}
+ std::set<string> fwd_decls;
+ for (const auto& generator : message_generators_) {
+ generator->DetermineObjectiveCClassDefinitions(&fwd_decls);
+ }
+ for (const auto& generator : extension_generators_) {
+ generator->DetermineObjectiveCClassDefinitions(&fwd_decls);
+ }
+
// Note:
// deprecated-declarations suppression is only needed if some place in this
// proto file is something deprecated or if it references something from
// another file that is deprecated.
+ // dollar-in-identifier-extension is needed because we use references to
+ // objc class names that have $ in identifiers.
printer->Print(
"// @@protoc_insertion_point(imports)\n"
"\n"
@@ -414,9 +424,26 @@
printer->Print(
"#pragma clang diagnostic ignored \"-Wdirect-ivar-access\"\n");
}
-
+ if (!fwd_decls.empty()) {
+ printer->Print(
+ "#pragma clang diagnostic ignored \"-Wdollar-in-identifier-extension\"\n");
+ }
printer->Print(
- "\n"
+ "\n");
+ if (!fwd_decls.empty()) {
+ printer->Print(
+ "#pragma mark - Objective C Class declarations\n"
+ "// Forward declarations of Objective C classes that we can use as\n"
+ "// static values in struct initializers.\n"
+ "// We don't use [Foo class] because it is not a static value.\n");
+ }
+ for (const auto& i : fwd_decls) {
+ printer->Print("$value$\n", "value", i);
+ }
+ if (!fwd_decls.empty()) {
+ printer->Print("\n");
+ }
+ printer->Print(
"#pragma mark - $root_class_name$\n"
"\n"
"@implementation $root_class_name$\n\n",
@@ -454,7 +481,8 @@
"};\n"
"for (size_t i = 0; i < sizeof(descriptions) / sizeof(descriptions[0]); ++i) {\n"
" GPBExtensionDescriptor *extension =\n"
- " [[GPBExtensionDescriptor alloc] initWithExtensionDescription:&descriptions[i]];\n"
+ " [[GPBExtensionDescriptor alloc] initWithExtensionDescription:&descriptions[i]\n"
+ " usesClassRefs:YES];\n"
" [registry addExtension:extension];\n"
" [self globallyRegisterExtension:extension];\n"
" [extension release];\n"
@@ -500,7 +528,7 @@
printer->Print("\n@end\n\n");
// File descriptor only needed if there are messages to use it.
- if (message_generators_.size() > 0) {
+ if (!message_generators_.empty()) {
std::map<string, string> vars;
vars["root_class_name"] = root_class_name_;
vars["package"] = file_->package();
@@ -525,7 +553,7 @@
" static GPBFileDescriptor *descriptor = NULL;\n"
" if (!descriptor) {\n"
" GPB_DEBUG_CHECK_RUNTIME_VERSIONS();\n");
- if (vars["objc_prefix"].size() > 0) {
+ if (!vars["objc_prefix"].empty()) {
printer->Print(
vars,
" descriptor = [[GPBFileDescriptor alloc] initWithPackage:@\"$package$\"\n"
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.h b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
index d10efc2..b09e2b2 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_generator.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
@@ -57,15 +57,19 @@
ObjectiveCGenerator& operator=(const ObjectiveCGenerator&) = delete;
// implements CodeGenerator ----------------------------------------
- bool HasGenerateAll() const;
+ bool HasGenerateAll() const override;
bool Generate(const FileDescriptor* file,
const string& parameter,
GeneratorContext* context,
- string* error) const;
+ string* error) const override;
bool GenerateAll(const std::vector<const FileDescriptor*>& files,
const string& parameter,
GeneratorContext* context,
- string* error) const;
+ string* error) const override;
+
+ uint64 GetSupportedFeatures() const override {
+ return FEATURE_PROTO3_OPTIONAL;
+ }
};
} // namespace objectivec
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
index 09a808b..df11689 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
@@ -585,6 +585,14 @@
return result;
}
+string ObjCClass(const string& class_name) {
+ return string("GPBObjCClass(") + class_name + ")";
+}
+
+string ObjCClassDeclaration(const string& class_name) {
+ return string("GPBObjCClassDeclaration(") + class_name + ");";
+}
+
string UnCamelCaseFieldName(const string& name, const FieldDescriptor* field) {
string worker(name);
if (HasSuffixString(worker, "_p")) {
@@ -910,7 +918,7 @@
string BuildFlagsString(const FlagType flag_type,
const std::vector<string>& strings) {
- if (strings.size() == 0) {
+ if (strings.empty()) {
return GetZeroEnumNameForFlagType(flag_type);
} else if (strings.size() == 1) {
return strings[0];
@@ -937,7 +945,7 @@
lines.pop_back();
}
// If there are no comments, just return an empty string.
- if (lines.size() == 0) {
+ if (lines.empty()) {
return "";
}
@@ -982,7 +990,7 @@
// want to put the library in a framework is an interesting question. The
// problem is it means changing sources shipped with the library to actually
// use a different value; so it isn't as simple as a option.
-const char* const ProtobufLibraryFrameworkName = "protobuf";
+const char* const ProtobufLibraryFrameworkName = "Protobuf";
string ProtobufFrameworkImportSymbol(const string& framework_name) {
// GPB_USE_[framework_name]_FRAMEWORK_IMPORTS
@@ -1293,14 +1301,14 @@
}
private:
- static const uint8 kAddUnderscore = 0x80;
+ static constexpr uint8 kAddUnderscore = 0x80;
- static const uint8 kOpAsIs = 0x00;
- static const uint8 kOpFirstUpper = 0x40;
- static const uint8 kOpFirstLower = 0x20;
- static const uint8 kOpAllUpper = 0x60;
+ static constexpr uint8 kOpAsIs = 0x00;
+ static constexpr uint8 kOpFirstUpper = 0x40;
+ static constexpr uint8 kOpFirstLower = 0x20;
+ static constexpr uint8 kOpAllUpper = 0x60;
- static const int kMaxSegmentLen = 0x1f;
+ static constexpr int kMaxSegmentLen = 0x1f;
void AddChar(const char desired) {
++segment_len_;
@@ -1397,7 +1405,7 @@
// static
string TextFormatDecodeData::DecodeDataForString(const string& input_for_decode,
const string& desired_output) {
- if ((input_for_decode.size() == 0) || (desired_output.size() == 0)) {
+ if (input_for_decode.empty() || desired_output.empty()) {
std::cerr << "error: got empty string for making TextFormat data, input: \""
<< input_for_decode << "\", desired: \"" << desired_output << "\"."
<< std::endl;
@@ -1507,7 +1515,7 @@
++line_;
RemoveComment(&line);
TrimWhitespace(&line);
- if (line.size() == 0) {
+ if (line.empty()) {
continue; // Blank line.
}
if (!line_consumer_->ConsumeLine(line, &error_str_)) {
@@ -1570,16 +1578,15 @@
void ImportWriter::AddFile(const FileDescriptor* file,
const string& header_extension) {
- const string file_path(FilePath(file));
-
if (IsProtobufLibraryBundledProtoFile(file)) {
// The imports of the WKTs are only needed within the library itself,
// in other cases, they get skipped because the generated code already
// import GPBProtocolBuffers.h and hence proves them.
if (include_wkt_imports_) {
- protobuf_framework_imports_.push_back(
- FilePathBasename(file) + header_extension);
- protobuf_non_framework_imports_.push_back(file_path + header_extension);
+ const string header_name =
+ "GPB" + FilePathBasename(file) + header_extension;
+ protobuf_framework_imports_.push_back(header_name);
+ protobuf_non_framework_imports_.push_back(header_name);
}
return;
}
@@ -1605,7 +1612,7 @@
return;
}
- other_imports_.push_back(file_path + header_extension);
+ other_imports_.push_back(FilePath(file) + header_extension);
}
void ImportWriter::Print(io::Printer* printer) const {
@@ -1614,7 +1621,7 @@
bool add_blank_line = false;
- if (protobuf_framework_imports_.size() > 0) {
+ if (!protobuf_framework_imports_.empty()) {
const string framework_name(ProtobufLibraryFrameworkName);
const string cpp_symbol(ProtobufFrameworkImportSymbol(framework_name));
@@ -1642,7 +1649,7 @@
add_blank_line = true;
}
- if (other_framework_imports_.size() > 0) {
+ if (!other_framework_imports_.empty()) {
if (add_blank_line) {
printer->Print("\n");
}
@@ -1657,7 +1664,7 @@
add_blank_line = true;
}
- if (other_imports_.size() > 0) {
+ if (!other_imports_.empty()) {
if (add_blank_line) {
printer->Print("\n");
}
@@ -1709,7 +1716,7 @@
StringPiece proto_file = proto_file_list.substr(start, offset - start);
TrimWhitespace(&proto_file);
- if (proto_file.size() != 0) {
+ if (!proto_file.empty()) {
std::map<string, string>::iterator existing_entry =
map_->find(string(proto_file));
if (existing_entry != map_->end()) {
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
index 98ec7db..5f91f4e 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
@@ -118,9 +118,13 @@
string PROTOC_EXPORT OneofName(const OneofDescriptor* descriptor);
string PROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor);
-inline bool HasFieldPresence(const FileDescriptor* file) {
- return file->syntax() != FileDescriptor::SYNTAX_PROTO3;
-}
+// Returns a symbol that can be used in C code to refer to an Objective C
+// class without initializing the class.
+string PROTOC_EXPORT ObjCClass(const string& class_name);
+
+// Declares an Objective C class without initializing the class so that it can
+// be refrerred to by ObjCClass.
+string PROTOC_EXPORT ObjCClassDeclaration(const string& class_name);
inline bool HasPreservingUnknownEnumSemantics(const FileDescriptor* file) {
return file->syntax() == FileDescriptor::SYNTAX_PROTO3;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
index 6abad8b..545660d 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
@@ -85,9 +85,9 @@
const Options& options)
: RepeatedFieldGenerator(descriptor, options) {
const FieldDescriptor* key_descriptor =
- descriptor->message_type()->FindFieldByName("key");
+ descriptor->message_type()->map_key();
const FieldDescriptor* value_descriptor =
- descriptor->message_type()->FindFieldByName("value");
+ descriptor->message_type()->map_value();
value_field_generator_.reset(FieldGenerator::Make(value_descriptor, options));
// Pull over some variables_ from the value.
@@ -112,6 +112,7 @@
if (value_field_flags.find("GPBFieldHasEnumDescriptor") != string::npos) {
field_flags.push_back("GPBFieldHasEnumDescriptor");
}
+
variables_["fieldflags"] = BuildFlagsString(FLAGTYPE_FIELD, field_flags);
ObjectiveCType value_objc_type = GetObjectiveCType(value_descriptor);
@@ -170,6 +171,17 @@
}
}
+void MapFieldGenerator::DetermineObjectiveCClassDefinitions(
+ std::set<string>* fwd_decls) const {
+ // Class name is already in "storage_type".
+ const FieldDescriptor* value_descriptor =
+ descriptor_->message_type()->FindFieldByName("value");
+ if (GetObjectiveCType(value_descriptor) == OBJECTIVECTYPE_MESSAGE) {
+ fwd_decls->insert(ObjCClassDeclaration(
+ value_field_generator_->variable("storage_type")));
+ }
+}
+
} // namespace objectivec
} // namespace compiler
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
index c308501..da18d57 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h
@@ -54,6 +54,7 @@
MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options);
virtual ~MapFieldGenerator();
+ virtual void DetermineObjectiveCClassDefinitions(std::set<string>* fwd_decls) const;
virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
private:
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.cc b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
index 6731e37..0684021 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
@@ -50,9 +50,6 @@
namespace compiler {
namespace objectivec {
-using internal::WireFormat;
-using internal::WireFormatLite;
-
namespace {
struct FieldOrderingByNumber {
inline bool operator()(const FieldDescriptor* a,
@@ -188,7 +185,7 @@
new ExtensionGenerator(class_name_, descriptor_->extension(i)));
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
+ for (int i = 0; i < descriptor_->real_oneof_decl_count(); i++) {
OneofGenerator* generator = new OneofGenerator(descriptor_->oneof_decl(i));
oneof_generators_.emplace_back(generator);
}
@@ -234,6 +231,30 @@
}
}
+void MessageGenerator::DetermineObjectiveCClassDefinitions(std::set<string>* fwd_decls) {
+ if (!IsMapEntryMessage(descriptor_)) {
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ const FieldDescriptor* fieldDescriptor = descriptor_->field(i);
+ field_generators_.get(fieldDescriptor)
+ .DetermineObjectiveCClassDefinitions(fwd_decls);
+ }
+ }
+
+ for (const auto& generator : extension_generators_) {
+ generator->DetermineObjectiveCClassDefinitions(fwd_decls);
+ }
+
+ for (const auto& generator : nested_message_generators_) {
+ generator->DetermineObjectiveCClassDefinitions(fwd_decls);
+ }
+
+ const Descriptor* containing_descriptor = descriptor_->containing_type();
+ if (containing_descriptor != NULL) {
+ string containing_class = ClassName(containing_descriptor);
+ fwd_decls->insert(ObjCClassDeclaration(containing_class));
+ }
+}
+
bool MessageGenerator::IncludesOneOfDefinition() const {
if (!oneof_generators_.empty()) {
return true;
@@ -313,16 +334,17 @@
}
printer->Print(
- "$comments$$deprecated_attribute$@interface $classname$ : GPBMessage\n\n",
+ "$comments$$deprecated_attribute$GPB_FINAL @interface $classname$ : GPBMessage\n\n",
"classname", class_name_,
"deprecated_attribute", deprecated_attribute_,
"comments", message_comments);
- std::vector<char> seen_oneofs(descriptor_->oneof_decl_count(), 0);
+ std::vector<char> seen_oneofs(oneof_generators_.size(), 0);
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
- if (field->containing_oneof() != NULL) {
- const int oneof_index = field->containing_oneof()->index();
+ const OneofDescriptor *oneof = field->real_containing_oneof();
+ if (oneof) {
+ const int oneof_index = oneof->index();
if (!seen_oneofs[oneof_index]) {
seen_oneofs[oneof_index] = 1;
oneof_generators_[oneof_index]->GeneratePublicCasePropertyDeclaration(
@@ -393,6 +415,7 @@
SortFieldsByStorageSize(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
+ sorted_extensions.reserve(descriptor_->extension_range_count());
for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
sorted_extensions.push_back(descriptor_->extension_range(i));
}
@@ -421,7 +444,7 @@
field_generators_.SetOneofIndexBase(sizeof_has_storage);
// sizeof_has_storage needs enough bits for the single fields that aren't in
// any oneof, and then one int32 for each oneof (to store the field number).
- sizeof_has_storage += descriptor_->oneof_decl_count();
+ sizeof_has_storage += oneof_generators_.size();
printer->Print(
"\n"
@@ -457,12 +480,12 @@
field_description_type = "GPBMessageFieldDescription";
}
if (has_fields) {
+ printer->Indent();
+ printer->Indent();
printer->Print(
- " static $field_description_type$ fields[] = {\n",
+ "static $field_description_type$ fields[] = {\n",
"field_description_type", field_description_type);
printer->Indent();
- printer->Indent();
- printer->Indent();
for (int i = 0; i < descriptor_->field_count(); ++i) {
const FieldGenerator& field_generator =
field_generators_.get(sorted_fields[i]);
@@ -474,10 +497,10 @@
}
}
printer->Outdent();
- printer->Outdent();
- printer->Outdent();
printer->Print(
- " };\n");
+ "};\n");
+ printer->Outdent();
+ printer->Outdent();
}
std::map<string, string> vars;
@@ -492,6 +515,8 @@
}
std::vector<string> init_flags;
+ init_flags.push_back("GPBDescriptorInitializationFlag_UsesClassRefs");
+ init_flags.push_back("GPBDescriptorInitializationFlag_Proto3OptionalKnown");
if (need_defaults) {
init_flags.push_back("GPBDescriptorInitializationFlag_FieldsWithDefault");
}
@@ -511,7 +536,7 @@
" fieldCount:$fields_count$\n"
" storageSize:sizeof($classname$__storage_)\n"
" flags:$init_flags$];\n");
- if (oneof_generators_.size() != 0) {
+ if (!oneof_generators_.empty()) {
printer->Print(
" static const char *oneofs[] = {\n");
for (const auto& generator : oneof_generators_) {
@@ -542,7 +567,7 @@
" [localDescriptor setupExtraTextInfo:extraTextFormatInfo];\n"
"#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS\n");
}
- if (sorted_extensions.size() != 0) {
+ if (!sorted_extensions.empty()) {
printer->Print(
" static const GPBExtensionRange ranges[] = {\n");
for (int i = 0; i < sorted_extensions.size(); i++) {
@@ -556,14 +581,15 @@
" count:(uint32_t)(sizeof(ranges) / sizeof(GPBExtensionRange))];\n");
}
if (descriptor_->containing_type() != NULL) {
- string parent_class_name = ClassName(descriptor_->containing_type());
+ string containing_class = ClassName(descriptor_->containing_type());
+ string parent_class_ref = ObjCClass(containing_class);
printer->Print(
- " [localDescriptor setupContainingMessageClassName:GPBStringifySymbol($parent_name$)];\n",
- "parent_name", parent_class_name);
+ " [localDescriptor setupContainingMessageClass:$parent_class_ref$];\n",
+ "parent_class_ref", parent_class_ref);
}
string suffix_added;
ClassName(descriptor_, &suffix_added);
- if (suffix_added.size() > 0) {
+ if (!suffix_added.empty()) {
printer->Print(
" [localDescriptor setupMessageClassNameSuffix:@\"$suffix$\"];\n",
"suffix", suffix_added);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.h b/src/google/protobuf/compiler/objectivec/objectivec_message.h
index 55eda0b..138e620 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.h
@@ -63,6 +63,7 @@
void GenerateMessageHeader(io::Printer* printer);
void GenerateSource(io::Printer* printer);
void GenerateExtensionRegistrationSource(io::Printer* printer);
+ void DetermineObjectiveCClassDefinitions(std::set<string>* fwd_decls);
void DetermineForwardDeclarations(std::set<string>* fwd_decls);
// Checks if the message or a nested message includes a oneof definition.
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc
index 8a0299e..7bf33f4 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc
@@ -46,13 +46,13 @@
void SetMessageVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
const string& message_type = ClassName(descriptor->message_type());
+ const string& containing_class = ClassName(descriptor->containing_type());
(*variables)["type"] = message_type;
- (*variables)["containing_class"] = ClassName(descriptor->containing_type());
+ (*variables)["containing_class"] = containing_class;
(*variables)["storage_type"] = message_type;
(*variables)["group_or_message"] =
(descriptor->type() == FieldDescriptor::TYPE_GROUP) ? "Group" : "Message";
-
- (*variables)["dataTypeSpecific_value"] = "GPBStringifySymbol(" + message_type + ")";
+ (*variables)["dataTypeSpecific_value"] = ObjCClass(message_type);
}
} // namespace
@@ -72,14 +72,9 @@
fwd_decls->insert("@class " + variable("storage_type"));
}
-bool MessageFieldGenerator::WantsHasProperty(void) const {
- if (descriptor_->containing_oneof() != NULL) {
- // If in a oneof, it uses the oneofcase instead of a has bit.
- return false;
- }
- // In both proto2 & proto3, message fields have a has* property to tell
- // when it is a non default value.
- return true;
+void MessageFieldGenerator::DetermineObjectiveCClassDefinitions(
+ std::set<string>* fwd_decls) const {
+ fwd_decls->insert(ObjCClassDeclaration(variable("storage_type")));
}
RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(
@@ -100,6 +95,10 @@
fwd_decls->insert("@class " + variable("storage_type"));
}
+void RepeatedMessageFieldGenerator::DetermineObjectiveCClassDefinitions(
+ std::set<string>* fwd_decls) const {
+ fwd_decls->insert(ObjCClassDeclaration(variable("storage_type")));
+}
} // namespace objectivec
} // namespace compiler
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message_field.h b/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
index 98d4579..a53c4a5 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message_field.h
@@ -52,10 +52,10 @@
MessageFieldGenerator& operator=(const MessageFieldGenerator&) = delete;
virtual ~MessageFieldGenerator();
- virtual bool WantsHasProperty(void) const;
public:
virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
+ virtual void DetermineObjectiveCClassDefinitions(std::set<string>* fwd_decls) const;
};
class RepeatedMessageFieldGenerator : public RepeatedFieldGenerator {
@@ -72,6 +72,7 @@
public:
virtual void DetermineForwardDeclarations(std::set<string>* fwd_decls) const;
+ virtual void DetermineObjectiveCClassDefinitions(std::set<string>* fwd_decls) const;
};
} // namespace objectivec
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc b/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc
index 5b37c4e..badebf5 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc
@@ -120,9 +120,9 @@
printer->Print(
variables_,
"void $owning_message_class$_Clear$capitalized_name$OneOfCase($owning_message_class$ *message) {\n"
- " GPBDescriptor *descriptor = [message descriptor];\n"
+ " GPBDescriptor *descriptor = [$owning_message_class$ descriptor];\n"
" GPBOneofDescriptor *oneof = [descriptor.oneofs objectAtIndex:$raw_index$];\n"
- " GPBMaybeClearOneof(message, oneof, $index$, 0);\n"
+ " GPBClearOneof(message, oneof);\n"
"}\n");
}
diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc
index c5bd0a4..d92cd55 100644
--- a/src/google/protobuf/compiler/parser.cc
+++ b/src/google/protobuf/compiler/parser.cc
@@ -34,22 +34,24 @@
//
// Recursive descent FTW.
+#include <google/protobuf/compiler/parser.h>
+
#include <float.h>
+
#include <limits>
#include <unordered_map>
-
-#include <google/protobuf/stubs/hash.h>
+#include <unordered_set>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/compiler/parser.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/map_util.h>
+#include <google/protobuf/stubs/hash.h>
namespace google {
namespace protobuf {
@@ -765,6 +767,43 @@
}
}
DO(ParseMessageBlock(message, message_location, containing_file));
+
+ if (syntax_identifier_ == "proto3") {
+ // Add synthetic one-field oneofs for optional fields, except messages which
+ // already have presence in proto3.
+ //
+ // We have to make sure the oneof names don't conflict with any other
+ // field or oneof.
+ std::unordered_set<std::string> names;
+ for (const auto& field : message->field()) {
+ names.insert(field.name());
+ }
+ for (const auto& oneof : message->oneof_decl()) {
+ names.insert(oneof.name());
+ }
+
+ for (auto& field : *message->mutable_field()) {
+ if (field.proto3_optional()) {
+ std::string oneof_name = field.name();
+
+ // Prepend 'XXXXX_' until we are no longer conflicting.
+ // Avoid prepending a double-underscore because such names are
+ // reserved in C++.
+ if (oneof_name.empty() || oneof_name[0] != '_') {
+ oneof_name = '_' + oneof_name;
+ }
+ while (names.count(oneof_name) > 0) {
+ oneof_name = 'X' + oneof_name;
+ }
+
+ names.insert(oneof_name);
+ field.set_oneof_index(message->oneof_decl_size());
+ OneofDescriptorProto* oneof = message->add_oneof_decl();
+ oneof->set_name(oneof_name);
+ }
+ }
+ }
+
return true;
}
@@ -907,10 +946,7 @@
field->set_label(label);
if (label == FieldDescriptorProto::LABEL_OPTIONAL &&
syntax_identifier_ == "proto3") {
- AddError(
- "Explicit 'optional' labels are disallowed in the Proto3 syntax. "
- "To define 'optional' fields in Proto3, simply remove the "
- "'optional' label, as fields are 'optional' by default.");
+ field->set_proto3_optional(true);
}
}
}
@@ -1295,7 +1331,7 @@
break;
case FieldDescriptorProto::TYPE_STRING:
- // Note: When file opton java_string_check_utf8 is true, if a
+ // Note: When file option java_string_check_utf8 is true, if a
// non-string representation (eg byte[]) is later supported, it must
// be checked for UTF-8-ness.
DO(ConsumeString(default_value,
diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc
index 8994cc5..4a3a228 100644
--- a/src/google/protobuf/compiler/parser_unittest.cc
+++ b/src/google/protobuf/compiler/parser_unittest.cc
@@ -68,8 +68,7 @@
// implements ErrorCollector ---------------------------------------
void AddWarning(int line, int column, const std::string& message) override {
- strings::SubstituteAndAppend(&warning_, "$0:$1: $2\n", line, column,
- message);
+ strings::SubstituteAndAppend(&warning_, "$0:$1: $2\n", line, column, message);
}
void AddError(int line, int column, const std::string& message) override {
@@ -1009,6 +1008,43 @@
"}");
}
+TEST_F(ParseMessageTest, ExplicitOptionalLabelProto3) {
+ ExpectParsesTo(
+ "syntax = 'proto3';\n"
+ "message TestMessage {\n"
+ " optional int32 foo = 1;\n"
+ "}\n",
+
+ "syntax: \"proto3\" "
+ "message_type {"
+ " name: \"TestMessage\""
+ " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 "
+ " proto3_optional: true oneof_index: 0 } "
+ " oneof_decl { name:\"_foo\" } "
+ "}");
+
+ // Handle collisions in the synthetic oneof name.
+ ExpectParsesTo(
+ "syntax = 'proto3';\n"
+ "message TestMessage {\n"
+ " optional int32 foo = 1;\n"
+ " oneof _foo {\n"
+ " int32 __foo = 2;\n"
+ " }\n"
+ "}\n",
+
+ "syntax: \"proto3\" "
+ "message_type {"
+ " name: \"TestMessage\""
+ " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 "
+ " proto3_optional: true oneof_index: 1 } "
+ " field { name:\"__foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:2 "
+ " oneof_index: 0 } "
+ " oneof_decl { name:\"_foo\" } "
+ " oneof_decl { name:\"X_foo\" } "
+ "}");
+}
+
// ===================================================================
typedef ParserTest ParseEnumTest;
@@ -1575,17 +1611,6 @@
"1:0: Unexpected end of stream while parsing aggregate value.\n");
}
-TEST_F(ParseErrorTest, ExplicitOptionalLabelProto3) {
- ExpectHasErrors(
- "syntax = 'proto3';\n"
- "message TestMessage {\n"
- " optional int32 foo = 1;\n"
- "}\n",
- "2:11: Explicit 'optional' labels are disallowed in the Proto3 syntax. "
- "To define 'optional' fields in Proto3, simply remove the 'optional' "
- "label, as fields are 'optional' by default.\n");
-}
-
// -------------------------------------------------------------------
// Enum errors
diff --git a/src/google/protobuf/compiler/php/php_generator.cc b/src/google/protobuf/compiler/php/php_generator.cc
index 55b3de2..16ec9aa 100644
--- a/src/google/protobuf/compiler/php/php_generator.cc
+++ b/src/google/protobuf/compiler/php/php_generator.cc
@@ -91,6 +91,9 @@
std::string BinaryToHex(const string& binary);
void Indent(io::Printer* printer);
void Outdent(io::Printer* printer);
+void GenerateAddFilesToPool(const FileDescriptor* file,
+ const std::set<string>& aggregate_metadata_prefixes,
+ io::Printer* printer);
void GenerateMessageDocComment(io::Printer* printer, const Descriptor* message,
int is_descriptor);
void GenerateMessageConstructorDocComment(io::Printer* printer,
@@ -111,7 +114,6 @@
void GenerateServiceMethodDocComment(io::Printer* printer,
const MethodDescriptor* method);
-
std::string ReservedNamePrefix(const string& classname,
const FileDescriptor* file) {
bool is_reserved = false;
@@ -924,13 +926,20 @@
}
}
-void GenerateAddFileToPool(const FileDescriptor* file, bool is_descriptor,
- io::Printer* printer) {
- printer->Print(
- "public static $is_initialized = false;\n\n"
- "public static function initOnce() {\n");
- Indent(printer);
+void GenerateAddFileToPool(
+ const FileDescriptor* file,
+ bool is_descriptor,
+ bool aggregate_metadata,
+ const std::set<string>& aggregate_metadata_prefixes,
+ io::Printer* printer) {
+ printer->Print(
+ "public static $is_initialized = false;\n\n"
+ "public static function initOnce() {\n");
+ Indent(printer);
+ if (aggregate_metadata) {
+ GenerateAddFilesToPool(file, aggregate_metadata_prefixes, printer);
+ } else {
printer->Print(
"$pool = \\Google\\Protobuf\\Internal\\"
"DescriptorPool::getGeneratedPool();\n\n"
@@ -938,79 +947,210 @@
" return;\n"
"}\n");
- if (is_descriptor) {
- for (int i = 0; i < file->message_type_count(); i++) {
- GenerateMessageToPool("", file->message_type(i), printer);
- }
- for (int i = 0; i < file->enum_type_count(); i++) {
- GenerateEnumToPool(file->enum_type(i), printer);
- }
+ if (is_descriptor) {
+ for (int i = 0; i < file->message_type_count(); i++) {
+ GenerateMessageToPool("", file->message_type(i), printer);
+ }
+ for (int i = 0; i < file->enum_type_count(); i++) {
+ GenerateEnumToPool(file->enum_type(i), printer);
+ }
+ printer->Print(
+ "$pool->finish();\n");
+ } else {
+ for (int i = 0; i < file->dependency_count(); i++) {
+ const std::string& name = file->dependency(i)->name();
+ // Currently, descriptor.proto is not ready for external usage. Skip to
+ // import it for now, so that its dependencies can still work as long as
+ // they don't use protos defined in descriptor.proto.
+ if (name == kDescriptorFile) {
+ continue;
+ }
+ std::string dependency_filename =
+ GeneratedMetadataFileName(file->dependency(i), is_descriptor);
+ printer->Print(
+ "\\^name^::initOnce();\n",
+ "name", FilenameToClassname(dependency_filename));
+ }
+
+ // Add messages and enums to descriptor pool.
+ FileDescriptorSet files;
+ FileDescriptorProto* file_proto = files.add_file();
+ file->CopyTo(file_proto);
+
+ // Filter out descriptor.proto as it cannot be depended on for now.
+ RepeatedPtrField<string>* dependency = file_proto->mutable_dependency();
+ for (RepeatedPtrField<string>::iterator it = dependency->begin();
+ it != dependency->end(); ++it) {
+ if (*it != kDescriptorFile) {
+ dependency->erase(it);
+ break;
+ }
+ }
+
+ // Filter out all extensions, since we do not support extension yet.
+ file_proto->clear_extension();
+ RepeatedPtrField<DescriptorProto>* message_type =
+ file_proto->mutable_message_type();
+ for (RepeatedPtrField<DescriptorProto>::iterator it = message_type->begin();
+ it != message_type->end(); ++it) {
+ it->clear_extension();
+ }
+
+ string files_data;
+ files.SerializeToString(&files_data);
+
+ printer->Print("$pool->internalAddGeneratedFile(hex2bin(\n");
+ Indent(printer);
+
+ printer->Print(
+ "\"^data^\"\n",
+ "data", BinaryToHex(files_data));
+
+ Outdent(printer);
+ printer->Print(
+ "), true);\n\n");
+ }
printer->Print(
- "$pool->finish();\n");
+ "static::$is_initialized = true;\n");
+ }
+
+ Outdent(printer);
+ printer->Print("}\n");
+}
+
+static void AnalyzeDependencyForFile(
+ const FileDescriptor* file,
+ std::set<const FileDescriptor*>* nodes_without_dependency,
+ std::map<const FileDescriptor*, std::set<const FileDescriptor*>>* deps,
+ std::map<const FileDescriptor*, int>* dependency_count) {
+ int count = file->dependency_count();
+ for (int i = 0; i < file->dependency_count(); i++) {
+ const FileDescriptor* dependency = file->dependency(i);
+ if (dependency->name() == kDescriptorFile) {
+ count--;
+ break;
+ }
+ }
+
+ if (count == 0) {
+ nodes_without_dependency->insert(file);
} else {
+ (*dependency_count)[file] = count;
for (int i = 0; i < file->dependency_count(); i++) {
- const std::string& name = file->dependency(i)->name();
- // Currently, descriptor.proto is not ready for external usage. Skip to
- // import it for now, so that its dependencies can still work as long as
- // they don't use protos defined in descriptor.proto.
- if (name == kDescriptorFile) {
+ const FileDescriptor* dependency = file->dependency(i);
+ if (dependency->name() == kDescriptorFile) {
continue;
}
+ if (deps->find(dependency) == deps->end()) {
+ (*deps)[dependency] = std::set<const FileDescriptor*>();
+ }
+ (*deps)[dependency].insert(file);
+ AnalyzeDependencyForFile(
+ dependency, nodes_without_dependency, deps, dependency_count);
+ }
+ }
+}
+
+static bool NeedsUnwrapping(
+ const FileDescriptor* file,
+ const std::set<string>& aggregate_metadata_prefixes) {
+ bool has_aggregate_metadata_prefix = false;
+ if (aggregate_metadata_prefixes.empty()) {
+ has_aggregate_metadata_prefix = true;
+ } else {
+ for (const auto& prefix : aggregate_metadata_prefixes) {
+ if (HasPrefixString(file->package(), prefix)) {
+ has_aggregate_metadata_prefix = true;
+ break;
+ }
+ }
+ }
+
+ return has_aggregate_metadata_prefix;
+}
+
+void GenerateAddFilesToPool(
+ const FileDescriptor* file,
+ const std::set<string>& aggregate_metadata_prefixes,
+ io::Printer* printer) {
+ printer->Print(
+ "$pool = \\Google\\Protobuf\\Internal\\"
+ "DescriptorPool::getGeneratedPool();\n"
+ "if (static::$is_initialized == true) {\n"
+ " return;\n"
+ "}\n");
+
+ // Sort files according to dependency
+ std::map<const FileDescriptor*, std::set<const FileDescriptor*>> deps;
+ std::map<const FileDescriptor*, int> dependency_count;
+ std::set<const FileDescriptor*> nodes_without_dependency;
+ FileDescriptorSet sorted_file_set;
+
+ AnalyzeDependencyForFile(
+ file, &nodes_without_dependency, &deps, &dependency_count);
+
+ while (!nodes_without_dependency.empty()) {
+ auto file = *nodes_without_dependency.begin();
+ nodes_without_dependency.erase(file);
+ for (auto dependent : deps[file]) {
+ if (dependency_count[dependent] == 1) {
+ dependency_count.erase(dependent);
+ nodes_without_dependency.insert(dependent);
+ } else {
+ dependency_count[dependent] -= 1;
+ }
+ }
+
+ bool needs_aggregate = NeedsUnwrapping(file, aggregate_metadata_prefixes);
+
+ if (needs_aggregate) {
+ auto file_proto = sorted_file_set.add_file();
+ file->CopyTo(file_proto);
+
+ // Filter out descriptor.proto as it cannot be depended on for now.
+ RepeatedPtrField<string>* dependency = file_proto->mutable_dependency();
+ for (RepeatedPtrField<string>::iterator it = dependency->begin();
+ it != dependency->end(); ++it) {
+ if (*it != kDescriptorFile) {
+ dependency->erase(it);
+ break;
+ }
+ }
+
+ // Filter out all extensions, since we do not support extension yet.
+ file_proto->clear_extension();
+ RepeatedPtrField<DescriptorProto>* message_type =
+ file_proto->mutable_message_type();
+ for (RepeatedPtrField<DescriptorProto>::iterator it = message_type->begin();
+ it != message_type->end(); ++it) {
+ it->clear_extension();
+ }
+ } else {
std::string dependency_filename =
- GeneratedMetadataFileName(file->dependency(i), is_descriptor);
+ GeneratedMetadataFileName(file, false);
printer->Print(
"\\^name^::initOnce();\n",
"name", FilenameToClassname(dependency_filename));
}
-
- // Add messages and enums to descriptor pool.
- FileDescriptorSet files;
- FileDescriptorProto* file_proto = files.add_file();
- file->CopyTo(file_proto);
-
- // Filter out descriptor.proto as it cannot be depended on for now.
- RepeatedPtrField<string>* dependency = file_proto->mutable_dependency();
- for (RepeatedPtrField<string>::iterator it = dependency->begin();
- it != dependency->end(); ++it) {
- if (*it != kDescriptorFile) {
- dependency->erase(it);
- break;
- }
- }
-
- // Filter out all extensions, since we do not support extension yet.
- file_proto->clear_extension();
- RepeatedPtrField<DescriptorProto>* message_type =
- file_proto->mutable_message_type();
- for (RepeatedPtrField<DescriptorProto>::iterator it = message_type->begin();
- it != message_type->end(); ++it) {
- it->clear_extension();
- }
-
- string files_data;
- files.SerializeToString(&files_data);
-
- 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(
- "), true);\n\n");
}
+
+ string files_data;
+ sorted_file_set.SerializeToString(&files_data);
+
+ printer->Print("$pool->internalAddGeneratedFile(hex2bin(\n");
+ Indent(printer);
+
+ printer->Print(
+ "\"^data^\"\n",
+ "data", BinaryToHex(files_data));
+
+ Outdent(printer);
+ printer->Print(
+ "), true);\n");
+
printer->Print(
"static::$is_initialized = true;\n");
- Outdent(printer);
- printer->Print("}\n");
}
void GenerateUseDeclaration(bool is_descriptor, io::Printer* printer) {
@@ -1051,6 +1191,8 @@
void GenerateMetadataFile(const FileDescriptor* file,
bool is_descriptor,
+ bool aggregate_metadata,
+ const std::set<string>& aggregate_metadata_prefixes,
GeneratorContext* generator_context) {
std::string filename = GeneratedMetadataFileName(file, is_descriptor);
std::unique_ptr<io::ZeroCopyOutputStream> output(
@@ -1079,7 +1221,8 @@
}
Indent(&printer);
- GenerateAddFileToPool(file, is_descriptor, &printer);
+ GenerateAddFileToPool(file, is_descriptor, aggregate_metadata,
+ aggregate_metadata_prefixes, &printer);
Outdent(&printer);
printer.Print("}\n\n");
@@ -1215,7 +1358,7 @@
Outdent(&printer);
printer.Print("}\n\n");
- // write legacy file for backwards compatiblity with nested messages and enums
+ // write legacy file for backwards compatibility with nested messages and enums
if (en->containing_type() != NULL) {
printer.Print(
"// Adding a class alias for backwards compatibility with the previous class name.\n");
@@ -1229,6 +1372,7 @@
void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message,
bool is_descriptor,
+ bool aggregate_metadata,
GeneratorContext* generator_context) {
// Don't generate MapEntry messages -- we use the PHP extension's native
// support for map fields instead.
@@ -1285,10 +1429,12 @@
GeneratedMetadataFileName(file, is_descriptor);
std::string metadata_fullname = FilenameToClassname(metadata_filename);
printer.Print(
- "\\^fullname^::initOnce();\n"
- "parent::__construct($data);\n",
+ "\\^fullname^::initOnce();\n",
"fullname", metadata_fullname);
+ printer.Print(
+ "parent::__construct($data);\n");
+
Outdent(&printer);
printer.Print("}\n\n");
@@ -1314,7 +1460,7 @@
Outdent(&printer);
printer.Print("}\n\n");
- // write legacy file for backwards compatiblity with nested messages and enums
+ // write legacy file for backwards compatibility with nested messages and enums
if (message->containing_type() != NULL) {
printer.Print(
"// Adding a class alias for backwards compatibility with the previous class name.\n");
@@ -1328,6 +1474,7 @@
// Nested messages and enums.
for (int i = 0; i < message->nested_type_count(); i++) {
GenerateMessageFile(file, message->nested_type(i), is_descriptor,
+ aggregate_metadata,
generator_context);
}
for (int i = 0; i < message->enum_type_count(); i++) {
@@ -1384,10 +1531,15 @@
}
void GenerateFile(const FileDescriptor* file, bool is_descriptor,
+ bool aggregate_metadata,
+ const std::set<string>& aggregate_metadata_prefixes,
GeneratorContext* generator_context) {
- GenerateMetadataFile(file, is_descriptor, generator_context);
+ GenerateMetadataFile(file, is_descriptor, aggregate_metadata,
+ aggregate_metadata_prefixes, generator_context);
+
for (int i = 0; i < file->message_type_count(); i++) {
GenerateMessageFile(file, file->message_type(i), is_descriptor,
+ aggregate_metadata,
generator_context);
}
for (int i = 0; i < file->enum_type_count(); i++) {
@@ -1397,7 +1549,7 @@
if (file->options().php_generic_services()) {
for (int i = 0; i < file->service_count(); i++) {
GenerateServiceFile(file, file->service(i), is_descriptor,
- generator_context);
+ generator_context);
}
}
}
@@ -1653,8 +1805,17 @@
bool Generator::Generate(const FileDescriptor* file, const string& parameter,
GeneratorContext* generator_context,
string* error) const {
- bool is_descriptor = parameter == "internal";
+ return Generate(file, false, false, std::set<string>(),
+ generator_context, error);
+}
+bool Generator::Generate(
+ const FileDescriptor* file,
+ bool is_descriptor,
+ bool aggregate_metadata,
+ const std::set<string>& aggregate_metadata_prefixes,
+ GeneratorContext* generator_context,
+ string* error) const {
if (is_descriptor && file->name() != kDescriptorFile) {
*error =
"Can only generate PHP code for google/protobuf/descriptor.proto.\n";
@@ -1668,11 +1829,48 @@
return false;
}
- GenerateFile(file, is_descriptor, generator_context);
+ GenerateFile(file, is_descriptor, aggregate_metadata,
+ aggregate_metadata_prefixes, generator_context);
return true;
}
+bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
+ const std::string& parameter,
+ GeneratorContext* generator_context,
+ std::string* error) const {
+ bool is_descriptor = false;
+ bool aggregate_metadata = false;
+ std::set<string> aggregate_metadata_prefixes;
+
+ for (const auto& option : Split(parameter, ",", true)) {
+ const std::vector<std::string> option_pair = Split(option, "=", true);
+ if (HasPrefixString(option_pair[0], "aggregate_metadata")) {
+ string options_string = option_pair[1];
+ const std::vector<std::string> options =
+ Split(options_string, "#", false);
+ aggregate_metadata = true;
+ for (int i = 0; i < options.size(); i++) {
+ aggregate_metadata_prefixes.insert(options[i]);
+ GOOGLE_LOG(INFO) << options[i];
+ }
+ }
+ if (option_pair[0] == "internal") {
+ is_descriptor = true;
+ }
+ }
+
+ for (auto file : files) {
+ if (!Generate(
+ file, is_descriptor, aggregate_metadata,
+ aggregate_metadata_prefixes,
+ generator_context, error)) {
+ return false;
+ }
+ }
+ return true;
+}
+
} // namespace php
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h
index ef708ab..ca9d23a 100644
--- a/src/google/protobuf/compiler/php/php_generator.h
+++ b/src/google/protobuf/compiler/php/php_generator.h
@@ -44,10 +44,24 @@
namespace php {
class PROTOC_EXPORT Generator : public CodeGenerator {
+ public:
virtual bool Generate(
const FileDescriptor* file,
const string& parameter,
GeneratorContext* generator_context,
+ string* error) const override;
+
+ bool GenerateAll(const std::vector<const FileDescriptor*>& files,
+ const std::string& parameter,
+ GeneratorContext* generator_context,
+ std::string* error) const override;
+ private:
+ bool Generate(
+ const FileDescriptor* file,
+ bool is_descriptor,
+ bool aggregate_metadata,
+ const std::set<string>& aggregate_metadata_prefixes,
+ GeneratorContext* generator_context,
string* error) const;
};
diff --git a/src/google/protobuf/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc
index 7de3985..7306cf4 100644
--- a/src/google/protobuf/compiler/plugin.cc
+++ b/src/google/protobuf/compiler/plugin.cc
@@ -132,6 +132,8 @@
bool succeeded = generator.GenerateAll(parsed_files, request.parameter(),
&context, &error);
+ response->set_supported_features(generator.GetSupportedFeatures());
+
if (!succeeded && error.empty()) {
error =
"Code generator returned false but provided no error "
diff --git a/src/google/protobuf/compiler/plugin.h b/src/google/protobuf/compiler/plugin.h
index 69c5d3f..de581c1 100644
--- a/src/google/protobuf/compiler/plugin.h
+++ b/src/google/protobuf/compiler/plugin.h
@@ -79,7 +79,7 @@
const CodeGenerator* generator);
// Generates code using the given code generator. Returns true if the code
-// generation is successful. If the code geneartion fails, error_msg may be
+// generation is successful. If the code generation fails, error_msg may be
// populated to describe the failure cause.
bool GenerateCode(const CodeGeneratorRequest& request,
const CodeGenerator& generator,
diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc
index 354b4c8..6739215 100644
--- a/src/google/protobuf/compiler/plugin.pb.cc
+++ b/src/google/protobuf/compiler/plugin.pb.cc
@@ -97,7 +97,7 @@
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto[4];
-static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr;
+static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto[1];
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
@@ -144,15 +144,17 @@
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, error_),
+ PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, supported_features_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, file_),
0,
+ 1,
~0u,
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 9, sizeof(PROTOBUF_NAMESPACE_ID::compiler::Version)},
{ 13, 22, sizeof(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest)},
{ 26, 34, sizeof(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File)},
- { 37, 44, sizeof(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse)},
+ { 37, 45, sizeof(PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
@@ -172,13 +174,16 @@
"\t\0228\n\nproto_file\030\017 \003(\0132$.google.protobuf."
"FileDescriptorProto\022;\n\020compiler_version\030"
"\003 \001(\0132!.google.protobuf.compiler.Version"
- "\"\252\001\n\025CodeGeneratorResponse\022\r\n\005error\030\001 \001("
- "\t\022B\n\004file\030\017 \003(\01324.google.protobuf.compil"
- "er.CodeGeneratorResponse.File\032>\n\004File\022\014\n"
- "\004name\030\001 \001(\t\022\027\n\017insertion_point\030\002 \001(\t\022\017\n\007"
- "content\030\017 \001(\tBg\n\034com.google.protobuf.com"
- "pilerB\014PluginProtosZ9github.com/golang/p"
- "rotobuf/protoc-gen-go/plugin;plugin_go"
+ "\"\200\002\n\025CodeGeneratorResponse\022\r\n\005error\030\001 \001("
+ "\t\022\032\n\022supported_features\030\002 \001(\004\022B\n\004file\030\017 "
+ "\003(\01324.google.protobuf.compiler.CodeGener"
+ "atorResponse.File\032>\n\004File\022\014\n\004name\030\001 \001(\t\022"
+ "\027\n\017insertion_point\030\002 \001(\t\022\017\n\007content\030\017 \001("
+ "\t\"8\n\007Feature\022\020\n\014FEATURE_NONE\020\000\022\033\n\027FEATUR"
+ "E_PROTO3_OPTIONAL\020\001Bg\n\034com.google.protob"
+ "uf.compilerB\014PluginProtosZ9github.com/go"
+ "lang/protobuf/protoc-gen-go/plugin;plugi"
+ "n_go"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_deps[1] = {
&::descriptor_table_google_2fprotobuf_2fdescriptor_2eproto,
@@ -190,18 +195,38 @@
&scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto = {
- &descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fcompiler_2fplugin_2eproto, "google/protobuf/compiler/plugin.proto", 638,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fcompiler_2fplugin_2eproto, "google/protobuf/compiler/plugin.proto", 724,
&descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once, descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_sccs, descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto_deps, 4, 1,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto, 4, file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto, file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fcompiler_2fplugin_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fcompiler_2fplugin_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
namespace compiler {
+const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CodeGeneratorResponse_Feature_descriptor() {
+ ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto[0];
+}
+bool CodeGeneratorResponse_Feature_IsValid(int value) {
+ switch (value) {
+ case 0:
+ case 1:
+ return true;
+ default:
+ return false;
+ }
+}
+
+#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
+constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse::FEATURE_NONE;
+constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse::FEATURE_PROTO3_OPTIONAL;
+constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse::Feature_MIN;
+constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse::Feature_MAX;
+constexpr int CodeGeneratorResponse::Feature_ARRAYSIZE;
+#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
// ===================================================================
@@ -224,19 +249,20 @@
}
};
-Version::Version()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+Version::Version(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.compiler.Version)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.Version)
}
Version::Version(const Version& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
suffix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_suffix()) {
- suffix_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.suffix_);
+ suffix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_suffix(),
+ GetArena());
}
::memcpy(&major_, &from.major_,
static_cast<size_t>(reinterpret_cast<char*>(&patch_) -
@@ -255,12 +281,20 @@
Version::~Version() {
// @@protoc_insertion_point(destructor:google.protobuf.compiler.Version)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Version::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
suffix_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
+void Version::ArenaDtor(void* object) {
+ Version* _this = reinterpret_cast< Version* >(object);
+ (void)_this;
+}
+void Version::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void Version::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -278,7 +312,7 @@
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
- suffix_.ClearNonDefaultToEmptyNoArena();
+ suffix_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x0000000eu) {
::memset(&major_, 0, static_cast<size_t>(
@@ -286,12 +320,13 @@
reinterpret_cast<char*>(&major_)) + sizeof(patch_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Version::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -301,7 +336,7 @@
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_major(&has_bits);
- major_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ major_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -309,7 +344,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_minor(&has_bits);
- minor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ minor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -317,7 +352,7 @@
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_patch(&has_bits);
- patch_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ patch_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -338,7 +373,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -390,7 +427,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.Version)
return target;
@@ -462,15 +499,14 @@
void Version::MergeFrom(const Version& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.Version)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x0000000fu) {
if (cached_has_bits & 0x00000001u) {
- _has_bits_[0] |= 0x00000001u;
- suffix_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.suffix_);
+ _internal_set_suffix(from._internal_suffix());
}
if (cached_has_bits & 0x00000002u) {
major_ = from.major_;
@@ -505,13 +541,15 @@
void Version::InternalSwap(Version* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- suffix_.Swap(&other->suffix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(major_, other->major_);
- swap(minor_, other->minor_);
- swap(patch_, other->patch_);
+ suffix_.Swap(&other->suffix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Version, patch_)
+ + sizeof(Version::patch_)
+ - PROTOBUF_FIELD_OFFSET(Version, major_)>(
+ reinterpret_cast<char*>(&major_),
+ reinterpret_cast<char*>(&other->major_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Version::GetMetadata() const {
@@ -544,21 +582,24 @@
void CodeGeneratorRequest::clear_proto_file() {
proto_file_.Clear();
}
-CodeGeneratorRequest::CodeGeneratorRequest()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+CodeGeneratorRequest::CodeGeneratorRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
+ file_to_generate_(arena),
+ proto_file_(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.CodeGeneratorRequest)
}
CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
file_to_generate_(from.file_to_generate_),
proto_file_(from.proto_file_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
parameter_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_parameter()) {
- parameter_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.parameter_);
+ parameter_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_parameter(),
+ GetArena());
}
if (from._internal_has_compiler_version()) {
compiler_version_ = new PROTOBUF_NAMESPACE_ID::compiler::Version(*from.compiler_version_);
@@ -577,13 +618,21 @@
CodeGeneratorRequest::~CodeGeneratorRequest() {
// @@protoc_insertion_point(destructor:google.protobuf.compiler.CodeGeneratorRequest)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void CodeGeneratorRequest::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
parameter_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete compiler_version_;
}
+void CodeGeneratorRequest::ArenaDtor(void* object) {
+ CodeGeneratorRequest* _this = reinterpret_cast< CodeGeneratorRequest* >(object);
+ (void)_this;
+}
+void CodeGeneratorRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void CodeGeneratorRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -604,7 +653,7 @@
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
- parameter_.ClearNonDefaultToEmptyNoArena();
+ parameter_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(compiler_version_ != nullptr);
@@ -612,12 +661,13 @@
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* CodeGeneratorRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -675,7 +725,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -735,7 +787,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorRequest)
return target;
@@ -808,7 +860,7 @@
void CodeGeneratorRequest::MergeFrom(const CodeGeneratorRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -817,8 +869,7 @@
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
- _has_bits_[0] |= 0x00000001u;
- parameter_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.parameter_);
+ _internal_set_parameter(from._internal_parameter());
}
if (cached_has_bits & 0x00000002u) {
_internal_mutable_compiler_version()->PROTOBUF_NAMESPACE_ID::compiler::Version::MergeFrom(from._internal_compiler_version());
@@ -847,12 +898,11 @@
void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
file_to_generate_.InternalSwap(&other->file_to_generate_);
proto_file_.InternalSwap(&other->proto_file_);
- parameter_.Swap(&other->parameter_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ parameter_.Swap(&other->parameter_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(compiler_version_, other->compiler_version_);
}
@@ -879,27 +929,30 @@
}
};
-CodeGeneratorResponse_File::CodeGeneratorResponse_File()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+CodeGeneratorResponse_File::CodeGeneratorResponse_File(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.CodeGeneratorResponse.File)
}
CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
+ GetArena());
}
insertion_point_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_insertion_point()) {
- insertion_point_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.insertion_point_);
+ insertion_point_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_insertion_point(),
+ GetArena());
}
content_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_content()) {
- content_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.content_);
+ content_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_content(),
+ GetArena());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse.File)
}
@@ -914,14 +967,22 @@
CodeGeneratorResponse_File::~CodeGeneratorResponse_File() {
// @@protoc_insertion_point(destructor:google.protobuf.compiler.CodeGeneratorResponse.File)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void CodeGeneratorResponse_File::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
insertion_point_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
content_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
+void CodeGeneratorResponse_File::ArenaDtor(void* object) {
+ CodeGeneratorResponse_File* _this = reinterpret_cast< CodeGeneratorResponse_File* >(object);
+ (void)_this;
+}
+void CodeGeneratorResponse_File::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void CodeGeneratorResponse_File::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -940,22 +1001,23 @@
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
- name_.ClearNonDefaultToEmptyNoArena();
+ name_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000002u) {
- insertion_point_.ClearNonDefaultToEmptyNoArena();
+ insertion_point_.ClearNonDefaultToEmpty();
}
if (cached_has_bits & 0x00000004u) {
- content_.ClearNonDefaultToEmptyNoArena();
+ content_.ClearNonDefaultToEmpty();
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* CodeGeneratorResponse_File::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1000,7 +1062,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1054,7 +1118,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse.File)
return target;
@@ -1119,23 +1183,20 @@
void CodeGeneratorResponse_File::MergeFrom(const CodeGeneratorResponse_File& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
- _has_bits_[0] |= 0x00000001u;
- name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.name_);
+ _internal_set_name(from._internal_name());
}
if (cached_has_bits & 0x00000002u) {
- _has_bits_[0] |= 0x00000002u;
- insertion_point_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.insertion_point_);
+ _internal_set_insertion_point(from._internal_insertion_point());
}
if (cached_has_bits & 0x00000004u) {
- _has_bits_[0] |= 0x00000004u;
- content_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.content_);
+ _internal_set_content(from._internal_content());
}
}
}
@@ -1160,14 +1221,11 @@
void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- insertion_point_.Swap(&other->insertion_point_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- content_.Swap(&other->content_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ insertion_point_.Swap(&other->insertion_point_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ content_.Swap(&other->content_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorResponse_File::GetMetadata() const {
@@ -1185,40 +1243,55 @@
static void set_has_error(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
+ static void set_has_supported_features(HasBits* has_bits) {
+ (*has_bits)[0] |= 2u;
+ }
};
-CodeGeneratorResponse::CodeGeneratorResponse()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+CodeGeneratorResponse::CodeGeneratorResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
+ file_(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.CodeGeneratorResponse)
}
CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
file_(from.file_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
error_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_error()) {
- error_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.error_);
+ error_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_error(),
+ GetArena());
}
+ supported_features_ = from.supported_features_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse)
}
void CodeGeneratorResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
error_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ supported_features_ = PROTOBUF_ULONGLONG(0);
}
CodeGeneratorResponse::~CodeGeneratorResponse() {
// @@protoc_insertion_point(destructor:google.protobuf.compiler.CodeGeneratorResponse)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void CodeGeneratorResponse::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
error_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
+void CodeGeneratorResponse::ArenaDtor(void* object) {
+ CodeGeneratorResponse* _this = reinterpret_cast< CodeGeneratorResponse* >(object);
+ (void)_this;
+}
+void CodeGeneratorResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void CodeGeneratorResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -1237,15 +1310,17 @@
file_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
- error_.ClearNonDefaultToEmptyNoArena();
+ error_.ClearNonDefaultToEmpty();
}
+ supported_features_ = PROTOBUF_ULONGLONG(0);
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* CodeGeneratorResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1262,6 +1337,14 @@
CHK_(ptr);
} else goto handle_unusual;
continue;
+ // optional uint64 supported_features = 2;
+ case 2:
+ if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
+ _Internal::set_has_supported_features(&has_bits);
+ supported_features_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
+ CHK_(ptr);
+ } else goto handle_unusual;
+ continue;
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
case 15:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) {
@@ -1280,7 +1363,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1312,6 +1397,12 @@
1, this->_internal_error(), target);
}
+ // optional uint64 supported_features = 2;
+ if (cached_has_bits & 0x00000002u) {
+ target = stream->EnsureSpace(target);
+ target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(2, this->_internal_supported_features(), target);
+ }
+
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->_internal_file_size()); i < n; i++) {
@@ -1322,7 +1413,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse)
return target;
@@ -1343,14 +1434,23 @@
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg);
}
- // optional string error = 1;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 0x00000001u) {
- total_size += 1 +
- ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
- this->_internal_error());
- }
+ if (cached_has_bits & 0x00000003u) {
+ // optional string error = 1;
+ if (cached_has_bits & 0x00000001u) {
+ total_size += 1 +
+ ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
+ this->_internal_error());
+ }
+ // optional uint64 supported_features = 2;
+ if (cached_has_bits & 0x00000002u) {
+ total_size += 1 +
+ ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size(
+ this->_internal_supported_features());
+ }
+
+ }
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
@@ -1378,14 +1478,20 @@
void CodeGeneratorResponse::MergeFrom(const CodeGeneratorResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
file_.MergeFrom(from.file_);
- if (from._internal_has_error()) {
- _has_bits_[0] |= 0x00000001u;
- error_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.error_);
+ cached_has_bits = from._has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
+ if (cached_has_bits & 0x00000001u) {
+ _internal_set_error(from._internal_error());
+ }
+ if (cached_has_bits & 0x00000002u) {
+ supported_features_ = from.supported_features_;
+ }
+ _has_bits_[0] |= cached_has_bits;
}
}
@@ -1409,11 +1515,11 @@
void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
file_.InternalSwap(&other->file_);
- error_.Swap(&other->error_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ error_.Swap(&other->error_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ swap(supported_features_, other->supported_features_);
}
::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorResponse::GetMetadata() const {
@@ -1426,16 +1532,16 @@
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::Version* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::Version >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::Version >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::compiler::Version >(arena);
}
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest >(arena);
}
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >(arena);
}
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h
index 2dee810..0e0cc72 100644
--- a/src/google/protobuf/compiler/plugin.pb.h
+++ b/src/google/protobuf/compiler/plugin.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,11 +26,12 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
+#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/descriptor.pb.h>
// @@protoc_insertion_point(includes)
@@ -86,12 +87,35 @@
PROTOBUF_NAMESPACE_OPEN
namespace compiler {
+enum CodeGeneratorResponse_Feature : int {
+ CodeGeneratorResponse_Feature_FEATURE_NONE = 0,
+ CodeGeneratorResponse_Feature_FEATURE_PROTO3_OPTIONAL = 1
+};
+PROTOC_EXPORT bool CodeGeneratorResponse_Feature_IsValid(int value);
+constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse_Feature_Feature_MIN = CodeGeneratorResponse_Feature_FEATURE_NONE;
+constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse_Feature_Feature_MAX = CodeGeneratorResponse_Feature_FEATURE_PROTO3_OPTIONAL;
+constexpr int CodeGeneratorResponse_Feature_Feature_ARRAYSIZE = CodeGeneratorResponse_Feature_Feature_MAX + 1;
+
+PROTOC_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CodeGeneratorResponse_Feature_descriptor();
+template<typename T>
+inline const std::string& CodeGeneratorResponse_Feature_Name(T enum_t_value) {
+ static_assert(::std::is_same<T, CodeGeneratorResponse_Feature>::value ||
+ ::std::is_integral<T>::value,
+ "Incorrect type passed to function CodeGeneratorResponse_Feature_Name.");
+ return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
+ CodeGeneratorResponse_Feature_descriptor(), enum_t_value);
+}
+inline bool CodeGeneratorResponse_Feature_Parse(
+ const std::string& name, CodeGeneratorResponse_Feature* value) {
+ return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<CodeGeneratorResponse_Feature>(
+ CodeGeneratorResponse_Feature_descriptor(), name, value);
+}
// ===================================================================
-class PROTOC_EXPORT Version :
+class PROTOC_EXPORT Version PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ {
public:
- Version();
+ inline Version() : Version(nullptr) {};
virtual ~Version();
Version(const Version& from);
@@ -105,7 +129,7 @@
return *this;
}
inline Version& operator=(Version&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -114,10 +138,10 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
@@ -144,6 +168,15 @@
}
inline void Swap(Version* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(Version* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -178,13 +211,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.compiler.Version";
}
+ protected:
+ explicit Version(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -220,6 +251,15 @@
std::string* mutable_suffix();
std::string* release_suffix();
void set_allocated_suffix(std::string* suffix);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_suffix();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_suffix(
+ std::string* suffix);
private:
const std::string& _internal_suffix() const;
void _internal_set_suffix(const std::string& value);
@@ -269,7 +309,9 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr suffix_;
@@ -280,10 +322,10 @@
};
// -------------------------------------------------------------------
-class PROTOC_EXPORT CodeGeneratorRequest :
+class PROTOC_EXPORT CodeGeneratorRequest PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ {
public:
- CodeGeneratorRequest();
+ inline CodeGeneratorRequest() : CodeGeneratorRequest(nullptr) {};
virtual ~CodeGeneratorRequest();
CodeGeneratorRequest(const CodeGeneratorRequest& from);
@@ -297,7 +339,7 @@
return *this;
}
inline CodeGeneratorRequest& operator=(CodeGeneratorRequest&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -306,10 +348,10 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
@@ -336,6 +378,15 @@
}
inline void Swap(CodeGeneratorRequest* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(CodeGeneratorRequest* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -370,13 +421,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.compiler.CodeGeneratorRequest";
}
+ protected:
+ explicit CodeGeneratorRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -454,6 +503,15 @@
std::string* mutable_parameter();
std::string* release_parameter();
void set_allocated_parameter(std::string* parameter);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_parameter();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_parameter(
+ std::string* parameter);
private:
const std::string& _internal_parameter() const;
void _internal_set_parameter(const std::string& value);
@@ -474,12 +532,17 @@
const PROTOBUF_NAMESPACE_ID::compiler::Version& _internal_compiler_version() const;
PROTOBUF_NAMESPACE_ID::compiler::Version* _internal_mutable_compiler_version();
public:
+ void unsafe_arena_set_allocated_compiler_version(
+ PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version);
+ PROTOBUF_NAMESPACE_ID::compiler::Version* unsafe_arena_release_compiler_version();
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorRequest)
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> file_to_generate_;
@@ -490,10 +553,10 @@
};
// -------------------------------------------------------------------
-class PROTOC_EXPORT CodeGeneratorResponse_File :
+class PROTOC_EXPORT CodeGeneratorResponse_File PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ {
public:
- CodeGeneratorResponse_File();
+ inline CodeGeneratorResponse_File() : CodeGeneratorResponse_File(nullptr) {};
virtual ~CodeGeneratorResponse_File();
CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from);
@@ -507,7 +570,7 @@
return *this;
}
inline CodeGeneratorResponse_File& operator=(CodeGeneratorResponse_File&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -516,10 +579,10 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
@@ -546,6 +609,15 @@
}
inline void Swap(CodeGeneratorResponse_File* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(CodeGeneratorResponse_File* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -580,13 +652,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.compiler.CodeGeneratorResponse.File";
}
+ protected:
+ explicit CodeGeneratorResponse_File(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -621,6 +691,15 @@
std::string* mutable_name();
std::string* release_name();
void set_allocated_name(std::string* name);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_name();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_name(
+ std::string* name);
private:
const std::string& _internal_name() const;
void _internal_set_name(const std::string& value);
@@ -641,6 +720,15 @@
std::string* mutable_insertion_point();
std::string* release_insertion_point();
void set_allocated_insertion_point(std::string* insertion_point);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_insertion_point();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_insertion_point(
+ std::string* insertion_point);
private:
const std::string& _internal_insertion_point() const;
void _internal_set_insertion_point(const std::string& value);
@@ -661,6 +749,15 @@
std::string* mutable_content();
std::string* release_content();
void set_allocated_content(std::string* content);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_content();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_content(
+ std::string* content);
private:
const std::string& _internal_content() const;
void _internal_set_content(const std::string& value);
@@ -671,7 +768,9 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_;
@@ -681,10 +780,10 @@
};
// -------------------------------------------------------------------
-class PROTOC_EXPORT CodeGeneratorResponse :
+class PROTOC_EXPORT CodeGeneratorResponse PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ {
public:
- CodeGeneratorResponse();
+ inline CodeGeneratorResponse() : CodeGeneratorResponse(nullptr) {};
virtual ~CodeGeneratorResponse();
CodeGeneratorResponse(const CodeGeneratorResponse& from);
@@ -698,7 +797,7 @@
return *this;
}
inline CodeGeneratorResponse& operator=(CodeGeneratorResponse&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -707,10 +806,10 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
@@ -737,6 +836,15 @@
}
inline void Swap(CodeGeneratorResponse* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(CodeGeneratorResponse* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -771,13 +879,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.compiler.CodeGeneratorResponse";
}
+ protected:
+ explicit CodeGeneratorResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -793,11 +899,42 @@
typedef CodeGeneratorResponse_File File;
+ typedef CodeGeneratorResponse_Feature Feature;
+ static constexpr Feature FEATURE_NONE =
+ CodeGeneratorResponse_Feature_FEATURE_NONE;
+ static constexpr Feature FEATURE_PROTO3_OPTIONAL =
+ CodeGeneratorResponse_Feature_FEATURE_PROTO3_OPTIONAL;
+ static inline bool Feature_IsValid(int value) {
+ return CodeGeneratorResponse_Feature_IsValid(value);
+ }
+ static constexpr Feature Feature_MIN =
+ CodeGeneratorResponse_Feature_Feature_MIN;
+ static constexpr Feature Feature_MAX =
+ CodeGeneratorResponse_Feature_Feature_MAX;
+ static constexpr int Feature_ARRAYSIZE =
+ CodeGeneratorResponse_Feature_Feature_ARRAYSIZE;
+ static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor*
+ Feature_descriptor() {
+ return CodeGeneratorResponse_Feature_descriptor();
+ }
+ template<typename T>
+ static inline const std::string& Feature_Name(T enum_t_value) {
+ static_assert(::std::is_same<T, Feature>::value ||
+ ::std::is_integral<T>::value,
+ "Incorrect type passed to function Feature_Name.");
+ return CodeGeneratorResponse_Feature_Name(enum_t_value);
+ }
+ static inline bool Feature_Parse(const std::string& name,
+ Feature* value) {
+ return CodeGeneratorResponse_Feature_Parse(name, value);
+ }
+
// accessors -------------------------------------------------------
enum : int {
kFileFieldNumber = 15,
kErrorFieldNumber = 1,
+ kSupportedFeaturesFieldNumber = 2,
};
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
int file_size() const;
@@ -831,21 +968,46 @@
std::string* mutable_error();
std::string* release_error();
void set_allocated_error(std::string* error);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_error();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_error(
+ std::string* error);
private:
const std::string& _internal_error() const;
void _internal_set_error(const std::string& value);
std::string* _internal_mutable_error();
public:
+ // optional uint64 supported_features = 2;
+ bool has_supported_features() const;
+ private:
+ bool _internal_has_supported_features() const;
+ public:
+ void clear_supported_features();
+ ::PROTOBUF_NAMESPACE_ID::uint64 supported_features() const;
+ void set_supported_features(::PROTOBUF_NAMESPACE_ID::uint64 value);
+ private:
+ ::PROTOBUF_NAMESPACE_ID::uint64 _internal_supported_features() const;
+ void _internal_set_supported_features(::PROTOBUF_NAMESPACE_ID::uint64 value);
+ public:
+
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse)
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File > file_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr error_;
+ ::PROTOBUF_NAMESPACE_ID::uint64 supported_features_;
friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto;
};
// ===================================================================
@@ -952,7 +1114,7 @@
return _internal_has_suffix();
}
inline void Version::clear_suffix() {
- suffix_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ suffix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Version::suffix() const {
@@ -968,33 +1130,35 @@
return _internal_mutable_suffix();
}
inline const std::string& Version::_internal_suffix() const {
- return suffix_.GetNoArena();
+ return suffix_.Get();
}
inline void Version::_internal_set_suffix(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- suffix_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ suffix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Version::set_suffix(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
- suffix_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ suffix_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.Version.suffix)
}
inline void Version::set_suffix(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
- suffix_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ suffix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.Version.suffix)
}
-inline void Version::set_suffix(const char* value, size_t size) {
+inline void Version::set_suffix(const char* value,
+ size_t size) {
_has_bits_[0] |= 0x00000001u;
- suffix_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ suffix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.Version.suffix)
}
inline std::string* Version::_internal_mutable_suffix() {
_has_bits_[0] |= 0x00000001u;
- return suffix_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return suffix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Version::release_suffix() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix)
@@ -1002,7 +1166,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return suffix_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return suffix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Version::set_allocated_suffix(std::string* suffix) {
if (suffix != nullptr) {
@@ -1010,9 +1174,29 @@
} else {
_has_bits_[0] &= ~0x00000001u;
}
- suffix_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), suffix);
+ suffix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), suffix,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.Version.suffix)
}
+inline std::string* Version::unsafe_arena_release_suffix() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.compiler.Version.suffix)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ _has_bits_[0] &= ~0x00000001u;
+ return suffix_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void Version::unsafe_arena_set_allocated_suffix(
+ std::string* suffix) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (suffix != nullptr) {
+ _has_bits_[0] |= 0x00000001u;
+ } else {
+ _has_bits_[0] &= ~0x00000001u;
+ }
+ suffix_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ suffix, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.Version.suffix)
+}
// -------------------------------------------------------------------
@@ -1101,7 +1285,7 @@
return _internal_has_parameter();
}
inline void CodeGeneratorRequest::clear_parameter() {
- parameter_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ parameter_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& CodeGeneratorRequest::parameter() const {
@@ -1117,33 +1301,35 @@
return _internal_mutable_parameter();
}
inline const std::string& CodeGeneratorRequest::_internal_parameter() const {
- return parameter_.GetNoArena();
+ return parameter_.Get();
}
inline void CodeGeneratorRequest::_internal_set_parameter(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- parameter_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ parameter_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void CodeGeneratorRequest::set_parameter(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
- parameter_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ parameter_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
inline void CodeGeneratorRequest::set_parameter(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
- parameter_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ parameter_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
-inline void CodeGeneratorRequest::set_parameter(const char* value, size_t size) {
+inline void CodeGeneratorRequest::set_parameter(const char* value,
+ size_t size) {
_has_bits_[0] |= 0x00000001u;
- parameter_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ parameter_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
inline std::string* CodeGeneratorRequest::_internal_mutable_parameter() {
_has_bits_[0] |= 0x00000001u;
- return parameter_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return parameter_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* CodeGeneratorRequest::release_parameter() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter)
@@ -1151,7 +1337,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return parameter_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return parameter_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void CodeGeneratorRequest::set_allocated_parameter(std::string* parameter) {
if (parameter != nullptr) {
@@ -1159,9 +1345,29 @@
} else {
_has_bits_[0] &= ~0x00000001u;
}
- parameter_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), parameter);
+ parameter_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), parameter,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
+inline std::string* CodeGeneratorRequest::unsafe_arena_release_parameter() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.compiler.CodeGeneratorRequest.parameter)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ _has_bits_[0] &= ~0x00000001u;
+ return parameter_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void CodeGeneratorRequest::unsafe_arena_set_allocated_parameter(
+ std::string* parameter) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (parameter != nullptr) {
+ _has_bits_[0] |= 0x00000001u;
+ } else {
+ _has_bits_[0] &= ~0x00000001u;
+ }
+ parameter_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ parameter, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.parameter)
+}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
inline int CodeGeneratorRequest::_internal_proto_file_size() const {
@@ -1221,7 +1427,29 @@
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
return _internal_compiler_version();
}
+inline void CodeGeneratorRequest::unsafe_arena_set_allocated_compiler_version(
+ PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(compiler_version_);
+ }
+ compiler_version_ = compiler_version;
+ if (compiler_version) {
+ _has_bits_[0] |= 0x00000002u;
+ } else {
+ _has_bits_[0] &= ~0x00000002u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
+}
inline PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::release_compiler_version() {
+ _has_bits_[0] &= ~0x00000002u;
+ PROTOBUF_NAMESPACE_ID::compiler::Version* temp = compiler_version_;
+ compiler_version_ = nullptr;
+ if (GetArena() != nullptr) {
+ temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
+ }
+ return temp;
+}
+inline PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::unsafe_arena_release_compiler_version() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
_has_bits_[0] &= ~0x00000002u;
PROTOBUF_NAMESPACE_ID::compiler::Version* temp = compiler_version_;
@@ -1231,7 +1459,7 @@
inline PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::_internal_mutable_compiler_version() {
_has_bits_[0] |= 0x00000002u;
if (compiler_version_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::compiler::Version>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::compiler::Version>(GetArena());
compiler_version_ = p;
}
return compiler_version_;
@@ -1241,12 +1469,13 @@
return _internal_mutable_compiler_version();
}
inline void CodeGeneratorRequest::set_allocated_compiler_version(PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete compiler_version_;
}
if (compiler_version) {
- ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
+ ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
+ ::PROTOBUF_NAMESPACE_ID::Arena::GetArena(compiler_version);
if (message_arena != submessage_arena) {
compiler_version = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, compiler_version, submessage_arena);
@@ -1272,7 +1501,7 @@
return _internal_has_name();
}
inline void CodeGeneratorResponse_File::clear_name() {
- name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& CodeGeneratorResponse_File::name() const {
@@ -1288,33 +1517,35 @@
return _internal_mutable_name();
}
inline const std::string& CodeGeneratorResponse_File::_internal_name() const {
- return name_.GetNoArena();
+ return name_.Get();
}
inline void CodeGeneratorResponse_File::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void CodeGeneratorResponse_File::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
- name_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ name_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
inline void CodeGeneratorResponse_File::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
-inline void CodeGeneratorResponse_File::set_name(const char* value, size_t size) {
+inline void CodeGeneratorResponse_File::set_name(const char* value,
+ size_t size) {
_has_bits_[0] |= 0x00000001u;
- name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
inline std::string* CodeGeneratorResponse_File::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* CodeGeneratorResponse_File::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name)
@@ -1322,7 +1553,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void CodeGeneratorResponse_File::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -1330,9 +1561,29 @@
} else {
_has_bits_[0] &= ~0x00000001u;
}
- name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
+inline std::string* CodeGeneratorResponse_File::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.compiler.CodeGeneratorResponse.File.name)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ _has_bits_[0] &= ~0x00000001u;
+ return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void CodeGeneratorResponse_File::unsafe_arena_set_allocated_name(
+ std::string* name) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (name != nullptr) {
+ _has_bits_[0] |= 0x00000001u;
+ } else {
+ _has_bits_[0] &= ~0x00000001u;
+ }
+ name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ name, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.name)
+}
// optional string insertion_point = 2;
inline bool CodeGeneratorResponse_File::_internal_has_insertion_point() const {
@@ -1343,7 +1594,7 @@
return _internal_has_insertion_point();
}
inline void CodeGeneratorResponse_File::clear_insertion_point() {
- insertion_point_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ insertion_point_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& CodeGeneratorResponse_File::insertion_point() const {
@@ -1359,33 +1610,35 @@
return _internal_mutable_insertion_point();
}
inline const std::string& CodeGeneratorResponse_File::_internal_insertion_point() const {
- return insertion_point_.GetNoArena();
+ return insertion_point_.Get();
}
inline void CodeGeneratorResponse_File::_internal_set_insertion_point(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
- insertion_point_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ insertion_point_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void CodeGeneratorResponse_File::set_insertion_point(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
- insertion_point_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ insertion_point_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
inline void CodeGeneratorResponse_File::set_insertion_point(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
- insertion_point_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ insertion_point_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
-inline void CodeGeneratorResponse_File::set_insertion_point(const char* value, size_t size) {
+inline void CodeGeneratorResponse_File::set_insertion_point(const char* value,
+ size_t size) {
_has_bits_[0] |= 0x00000002u;
- insertion_point_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ insertion_point_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
inline std::string* CodeGeneratorResponse_File::_internal_mutable_insertion_point() {
_has_bits_[0] |= 0x00000002u;
- return insertion_point_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return insertion_point_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* CodeGeneratorResponse_File::release_insertion_point() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
@@ -1393,7 +1646,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
- return insertion_point_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return insertion_point_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void CodeGeneratorResponse_File::set_allocated_insertion_point(std::string* insertion_point) {
if (insertion_point != nullptr) {
@@ -1401,9 +1654,29 @@
} else {
_has_bits_[0] &= ~0x00000002u;
}
- insertion_point_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), insertion_point);
+ insertion_point_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), insertion_point,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
+inline std::string* CodeGeneratorResponse_File::unsafe_arena_release_insertion_point() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ _has_bits_[0] &= ~0x00000002u;
+ return insertion_point_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void CodeGeneratorResponse_File::unsafe_arena_set_allocated_insertion_point(
+ std::string* insertion_point) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (insertion_point != nullptr) {
+ _has_bits_[0] |= 0x00000002u;
+ } else {
+ _has_bits_[0] &= ~0x00000002u;
+ }
+ insertion_point_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ insertion_point, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
+}
// optional string content = 15;
inline bool CodeGeneratorResponse_File::_internal_has_content() const {
@@ -1414,7 +1687,7 @@
return _internal_has_content();
}
inline void CodeGeneratorResponse_File::clear_content() {
- content_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ content_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& CodeGeneratorResponse_File::content() const {
@@ -1430,33 +1703,35 @@
return _internal_mutable_content();
}
inline const std::string& CodeGeneratorResponse_File::_internal_content() const {
- return content_.GetNoArena();
+ return content_.Get();
}
inline void CodeGeneratorResponse_File::_internal_set_content(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
- content_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ content_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void CodeGeneratorResponse_File::set_content(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
- content_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ content_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
inline void CodeGeneratorResponse_File::set_content(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
- content_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ content_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
-inline void CodeGeneratorResponse_File::set_content(const char* value, size_t size) {
+inline void CodeGeneratorResponse_File::set_content(const char* value,
+ size_t size) {
_has_bits_[0] |= 0x00000004u;
- content_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ content_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
inline std::string* CodeGeneratorResponse_File::_internal_mutable_content() {
_has_bits_[0] |= 0x00000004u;
- return content_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return content_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* CodeGeneratorResponse_File::release_content() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content)
@@ -1464,7 +1739,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
- return content_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return content_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void CodeGeneratorResponse_File::set_allocated_content(std::string* content) {
if (content != nullptr) {
@@ -1472,9 +1747,29 @@
} else {
_has_bits_[0] &= ~0x00000004u;
}
- content_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), content);
+ content_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), content,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
+inline std::string* CodeGeneratorResponse_File::unsafe_arena_release_content() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.compiler.CodeGeneratorResponse.File.content)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ _has_bits_[0] &= ~0x00000004u;
+ return content_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void CodeGeneratorResponse_File::unsafe_arena_set_allocated_content(
+ std::string* content) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (content != nullptr) {
+ _has_bits_[0] |= 0x00000004u;
+ } else {
+ _has_bits_[0] &= ~0x00000004u;
+ }
+ content_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ content, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content)
+}
// -------------------------------------------------------------------
@@ -1489,7 +1784,7 @@
return _internal_has_error();
}
inline void CodeGeneratorResponse::clear_error() {
- error_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ error_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& CodeGeneratorResponse::error() const {
@@ -1505,33 +1800,35 @@
return _internal_mutable_error();
}
inline const std::string& CodeGeneratorResponse::_internal_error() const {
- return error_.GetNoArena();
+ return error_.Get();
}
inline void CodeGeneratorResponse::_internal_set_error(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- error_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ error_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void CodeGeneratorResponse::set_error(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
- error_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ error_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.error)
}
inline void CodeGeneratorResponse::set_error(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
- error_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ error_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.error)
}
-inline void CodeGeneratorResponse::set_error(const char* value, size_t size) {
+inline void CodeGeneratorResponse::set_error(const char* value,
+ size_t size) {
_has_bits_[0] |= 0x00000001u;
- error_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ error_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.error)
}
inline std::string* CodeGeneratorResponse::_internal_mutable_error() {
_has_bits_[0] |= 0x00000001u;
- return error_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return error_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* CodeGeneratorResponse::release_error() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error)
@@ -1539,7 +1836,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return error_.ReleaseNonDefaultNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return error_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void CodeGeneratorResponse::set_allocated_error(std::string* error) {
if (error != nullptr) {
@@ -1547,9 +1844,57 @@
} else {
_has_bits_[0] &= ~0x00000001u;
}
- error_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), error);
+ error_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), error,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.error)
}
+inline std::string* CodeGeneratorResponse::unsafe_arena_release_error() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.compiler.CodeGeneratorResponse.error)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ _has_bits_[0] &= ~0x00000001u;
+ return error_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void CodeGeneratorResponse::unsafe_arena_set_allocated_error(
+ std::string* error) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (error != nullptr) {
+ _has_bits_[0] |= 0x00000001u;
+ } else {
+ _has_bits_[0] &= ~0x00000001u;
+ }
+ error_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ error, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.error)
+}
+
+// optional uint64 supported_features = 2;
+inline bool CodeGeneratorResponse::_internal_has_supported_features() const {
+ bool value = (_has_bits_[0] & 0x00000002u) != 0;
+ return value;
+}
+inline bool CodeGeneratorResponse::has_supported_features() const {
+ return _internal_has_supported_features();
+}
+inline void CodeGeneratorResponse::clear_supported_features() {
+ supported_features_ = PROTOBUF_ULONGLONG(0);
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline ::PROTOBUF_NAMESPACE_ID::uint64 CodeGeneratorResponse::_internal_supported_features() const {
+ return supported_features_;
+}
+inline ::PROTOBUF_NAMESPACE_ID::uint64 CodeGeneratorResponse::supported_features() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.supported_features)
+ return _internal_supported_features();
+}
+inline void CodeGeneratorResponse::_internal_set_supported_features(::PROTOBUF_NAMESPACE_ID::uint64 value) {
+ _has_bits_[0] |= 0x00000002u;
+ supported_features_ = value;
+}
+inline void CodeGeneratorResponse::set_supported_features(::PROTOBUF_NAMESPACE_ID::uint64 value) {
+ _internal_set_supported_features(value);
+ // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.supported_features)
+}
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
inline int CodeGeneratorResponse::_internal_file_size() const {
@@ -1605,6 +1950,16 @@
} // namespace compiler
PROTOBUF_NAMESPACE_CLOSE
+PROTOBUF_NAMESPACE_OPEN
+
+template <> struct is_proto_enum< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_Feature> : ::std::true_type {};
+template <>
+inline const EnumDescriptor* GetEnumDescriptor< PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_Feature>() {
+ return PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_Feature_descriptor();
+}
+
+PROTOBUF_NAMESPACE_CLOSE
+
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/plugin.proto b/src/google/protobuf/compiler/plugin.proto
index 665e5a7..492b896 100644
--- a/src/google/protobuf/compiler/plugin.proto
+++ b/src/google/protobuf/compiler/plugin.proto
@@ -107,6 +107,16 @@
// exiting with a non-zero status code.
optional string error = 1;
+ // A bitmask of supported features that the code generator supports.
+ // This is a bitwise "or" of values from the Feature enum.
+ optional uint64 supported_features = 2;
+
+ // Sync with code_generator.h.
+ enum Feature {
+ FEATURE_NONE = 0;
+ FEATURE_PROTO3_OPTIONAL = 1;
+ }
+
// Represents a single generated file.
message File {
// The file name, relative to the output directory. The name must not
diff --git a/src/google/protobuf/compiler/python/python_generator.cc b/src/google/protobuf/compiler/python/python_generator.cc
index b20f3fb..050fe9e 100644
--- a/src/google/protobuf/compiler/python/python_generator.cc
+++ b/src/google/protobuf/compiler/python/python_generator.cc
@@ -301,6 +301,10 @@
Generator::~Generator() {}
+uint64 Generator::GetSupportedFeatures() const {
+ return CodeGenerator::Feature::FEATURE_PROTO3_OPTIONAL;
+}
+
bool Generator::Generate(const FileDescriptor* file,
const std::string& parameter,
GeneratorContext* context, std::string* error) const {
@@ -441,7 +445,8 @@
" name='$name$',\n"
" package='$package$',\n"
" syntax='$syntax$',\n"
- " serialized_options=$options$,\n";
+ " serialized_options=$options$,\n"
+ " create_key=_descriptor._internal_create_key,\n";
printer_->Print(m, file_descriptor_template);
printer_->Indent();
if (pure_python_workable_) {
@@ -531,6 +536,7 @@
" full_name='$full_name$',\n"
" filename=None,\n"
" file=$file$,\n"
+ " create_key=_descriptor._internal_create_key,\n"
" values=[\n";
std::string options_string;
enum_descriptor.options().SerializeToString(&options_string);
@@ -578,7 +584,7 @@
for (int i = 0; i < file_->extension_count(); ++i) {
const FieldDescriptor& extension_field = *file_->extension(i);
std::string constant_name = extension_field.name() + "_FIELD_NUMBER";
- UpperString(&constant_name);
+ ToUpper(&constant_name);
printer_->Print("$constant_name$ = $number$\n", "constant_name",
constant_name, "number",
StrCat(extension_field.number()));
@@ -635,7 +641,8 @@
"full_name='$full_name$',\n"
"file=$file$,\n"
"index=$index$,\n"
- "serialized_options=$options_value$,\n";
+ "serialized_options=$options_value$,\n"
+ "create_key=_descriptor._internal_create_key,\n";
printer_->Print(m, required_function_arguments);
ServiceDescriptorProto sdp;
@@ -663,7 +670,8 @@
"containing_service=None,\n"
"input_type=$input_type$,\n"
"output_type=$output_type$,\n"
- "serialized_options=$options_value$,\n");
+ "serialized_options=$options_value$,\n"
+ "create_key=_descriptor._internal_create_key,\n");
printer_->Outdent();
printer_->Print("),\n");
}
@@ -733,7 +741,8 @@
"full_name='$full_name$',\n"
"filename=None,\n"
"file=$file$,\n"
- "containing_type=None,\n";
+ "containing_type=None,\n"
+ "create_key=_descriptor._internal_create_key,\n";
printer_->Print(m, required_function_arguments);
PrintFieldsInDescriptor(message_descriptor);
PrintExtensionsInDescriptor(message_descriptor);
@@ -796,7 +805,8 @@
printer_->Print(m,
"_descriptor.OneofDescriptor(\n"
" name='$name$', full_name='$full_name$',\n"
- " index=$index$, containing_type=None, "
+ " index=$index$, containing_type=None,\n"
+ " create_key=_descriptor._internal_create_key,\n"
"fields=[]$serialized_options$),\n");
}
printer_->Outdent();
@@ -1037,8 +1047,8 @@
return ResolveKeyword(field.name());
}
return strings::Substitute("$0.$1['$2']",
- ModuleLevelDescriptorName(*containing_type),
- python_dict_name, field.name());
+ ModuleLevelDescriptorName(*containing_type),
+ python_dict_name, field.name());
}
// Prints containing_type for nested descriptors or enum descriptors.
@@ -1144,7 +1154,8 @@
"_descriptor.EnumValueDescriptor(\n"
" name='$name$', index=$index$, number=$number$,\n"
" serialized_options=$options$,\n"
- " type=None)");
+ " type=None,\n"
+ " create_key=_descriptor._internal_create_key)");
}
// Returns a CEscaped string of serialized_options.
@@ -1187,7 +1198,8 @@
"default_value=$default_value$,\n"
" message_type=None, enum_type=None, containing_type=None,\n"
" is_extension=$is_extension$, extension_scope=None,\n"
- " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR)";
+ " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR,"
+ " create_key=_descriptor._internal_create_key)";
printer_->Print(m, field_descriptor_decl);
}
@@ -1250,7 +1262,7 @@
// The C++ implementation doesn't guard against this either. Leaving
// it for now...
std::string name = NamePrefixedWithNestedTypes(descriptor, "_");
- UpperString(&name);
+ ToUpper(&name);
// Module-private for now. Easy to make public later; almost impossible
// to make private later.
name = "_" + name;
@@ -1280,7 +1292,7 @@
std::string Generator::ModuleLevelServiceDescriptorName(
const ServiceDescriptor& descriptor) const {
std::string name = descriptor.name();
- UpperString(&name);
+ ToUpper(&name);
name = "_" + name;
if (descriptor.file() != file_) {
name = ModuleAlias(descriptor.file()->name()) + "." + name;
diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/python_generator.h
index 6f299e8..fb1aee1 100644
--- a/src/google/protobuf/compiler/python/python_generator.h
+++ b/src/google/protobuf/compiler/python/python_generator.h
@@ -69,10 +69,11 @@
virtual ~Generator();
// CodeGenerator methods.
- virtual bool Generate(const FileDescriptor* file,
- const std::string& parameter,
- GeneratorContext* generator_context,
- std::string* error) const;
+ bool Generate(const FileDescriptor* file, const std::string& parameter,
+ GeneratorContext* generator_context,
+ std::string* error) const override;
+
+ uint64 GetSupportedFeatures() const override;
private:
void PrintImports() const;
diff --git a/src/google/protobuf/compiler/ruby/ruby_generator.cc b/src/google/protobuf/compiler/ruby/ruby_generator.cc
index 092cbc3..cf61d99 100644
--- a/src/google/protobuf/compiler/ruby/ruby_generator.cc
+++ b/src/google/protobuf/compiler/ruby/ruby_generator.cc
@@ -77,6 +77,10 @@
}
std::string LabelForField(const FieldDescriptor* field) {
+ if (field->has_optional_keyword() &&
+ field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
+ return "proto3_optional";
+ }
switch (field->label()) {
case FieldDescriptor::LABEL_OPTIONAL: return "optional";
case FieldDescriptor::LABEL_REQUIRED: return "required";
@@ -255,12 +259,12 @@
for (int i = 0; i < message->field_count(); i++) {
const FieldDescriptor* field = message->field(i);
- if (!field->containing_oneof()) {
+ if (!field->real_containing_oneof()) {
GenerateField(field, printer);
}
}
- for (int i = 0; i < message->oneof_decl_count(); i++) {
+ for (int i = 0; i < message->real_oneof_decl_count(); i++) {
const OneofDescriptor* oneof = message->oneof_decl(i);
GenerateOneof(oneof, printer);
}
@@ -407,7 +411,7 @@
if (file->options().has_ruby_package()) {
package_name = file->options().ruby_package();
- // If :: is in the package use the Ruby formated name as-is
+ // If :: is in the package use the Ruby formatted name as-is
// -> A::B::C
// otherwise, use the dot seperator
// -> A.B.C
@@ -421,7 +425,7 @@
package_name = file->package();
}
- // Use the appropriate delimter
+ // Use the appropriate delimiter
string delimiter = need_change_to_module ? "." : "::";
int delimiter_size = need_change_to_module ? 1 : 2;
diff --git a/src/google/protobuf/compiler/ruby/ruby_generator.h b/src/google/protobuf/compiler/ruby/ruby_generator.h
index 731a81a..ea4f30a 100644
--- a/src/google/protobuf/compiler/ruby/ruby_generator.h
+++ b/src/google/protobuf/compiler/ruby/ruby_generator.h
@@ -49,11 +49,12 @@
// Ruby output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
class PROTOC_EXPORT Generator : public CodeGenerator {
- virtual bool Generate(
- const FileDescriptor* file,
- const string& parameter,
- GeneratorContext* generator_context,
- string* error) const;
+ bool Generate(const FileDescriptor* file, const string& parameter,
+ GeneratorContext* generator_context,
+ string* error) const override;
+ uint64 GetSupportedFeatures() const override {
+ return FEATURE_PROTO3_OPTIONAL;
+ }
};
} // namespace ruby
diff --git a/src/google/protobuf/compiler/subprocess.cc b/src/google/protobuf/compiler/subprocess.cc
index bd6be2b..7e59cd7 100644
--- a/src/google/protobuf/compiler/subprocess.cc
+++ b/src/google/protobuf/compiler/subprocess.cc
@@ -255,8 +255,7 @@
child_handle_ = NULL;
if (exit_code != 0) {
- *error =
- strings::Substitute("Plugin failed with status code $0.", exit_code);
+ *error = strings::Substitute("Plugin failed with status code $0.", exit_code);
return false;
}
@@ -274,7 +273,7 @@
// WTF?
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL, error_code, 0,
+ NULL, error_code, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
(LPSTR)&message, // NOT A BUG!
0, NULL);
diff --git a/src/google/protobuf/compiler/zip_writer.cc b/src/google/protobuf/compiler/zip_writer.cc
index 872dd9e..5ae0261 100644
--- a/src/google/protobuf/compiler/zip_writer.cc
+++ b/src/google/protobuf/compiler/zip_writer.cc
@@ -28,36 +28,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
// Author: ambrose@google.com (Ambrose Feinstein),
// kenton@google.com (Kenton Varda)
//
diff --git a/src/google/protobuf/compiler/zip_writer.h b/src/google/protobuf/compiler/zip_writer.h
index a99bb78..3a8903a 100644
--- a/src/google/protobuf/compiler/zip_writer.h
+++ b/src/google/protobuf/compiler/zip_writer.h
@@ -28,36 +28,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
// Author: kenton@google.com (Kenton Varda)
#include <vector>
diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc
index 6835a3c..aaaec6a 100644
--- a/src/google/protobuf/descriptor.cc
+++ b/src/google/protobuf/descriptor.cc
@@ -492,7 +492,7 @@
allowed_proto3_extendees->insert(std::string("google.protobuf.") +
kOptionNames[i]);
// Split the word to trick the opensource processing scripts so they
- // will keep the origial package name.
+ // will keep the original package name.
allowed_proto3_extendees->insert(std::string("proto") + "2." +
kOptionNames[i]);
}
@@ -579,6 +579,12 @@
// set of extensions numbers from fallback_database_.
HASH_SET<const Descriptor*> extensions_loaded_from_db_;
+ // Maps type name to Descriptor::WellKnownType. This is logically global
+ // and const, but we make it a member here to simplify its construction and
+ // destruction. This only has 20-ish entries and is one per DescriptorPool,
+ // so the overhead is small.
+ HASH_MAP<std::string, Descriptor::WellKnownType> well_known_types_;
+
// -----------------------------------------------------------------
// Finding items.
@@ -649,7 +655,7 @@
private:
// All other memory allocated in the pool. Must be first as other objects can
// point into these.
- std::vector<std::unique_ptr<char[]>> allocations_;
+ std::vector<std::vector<char>> allocations_;
std::vector<std::unique_ptr<std::string>> strings_;
std::vector<std::unique_ptr<Message>> messages_;
std::vector<std::unique_ptr<internal::once_flag>> once_dynamics_;
@@ -800,7 +806,26 @@
known_bad_symbols_(3),
extensions_loaded_from_db_(3),
symbols_by_name_(3),
- files_by_name_(3) {}
+ files_by_name_(3) {
+ well_known_types_.insert({
+ {"google.protobuf.DoubleValue", Descriptor::WELLKNOWNTYPE_DOUBLEVALUE},
+ {"google.protobuf.FloatValue", Descriptor::WELLKNOWNTYPE_FLOATVALUE},
+ {"google.protobuf.Int64Value", Descriptor::WELLKNOWNTYPE_INT64VALUE},
+ {"google.protobuf.UInt64Value", Descriptor::WELLKNOWNTYPE_UINT64VALUE},
+ {"google.protobuf.Int32Value", Descriptor::WELLKNOWNTYPE_INT32VALUE},
+ {"google.protobuf.UInt32Value", Descriptor::WELLKNOWNTYPE_UINT32VALUE},
+ {"google.protobuf.StringValue", Descriptor::WELLKNOWNTYPE_STRINGVALUE},
+ {"google.protobuf.BytesValue", Descriptor::WELLKNOWNTYPE_BYTESVALUE},
+ {"google.protobuf.BoolValue", Descriptor::WELLKNOWNTYPE_BOOLVALUE},
+ {"google.protobuf.Any", Descriptor::WELLKNOWNTYPE_ANY},
+ {"google.protobuf.FieldMask", Descriptor::WELLKNOWNTYPE_FIELDMASK},
+ {"google.protobuf.Duration", Descriptor::WELLKNOWNTYPE_DURATION},
+ {"google.protobuf.Timestamp", Descriptor::WELLKNOWNTYPE_TIMESTAMP},
+ {"google.protobuf.Value", Descriptor::WELLKNOWNTYPE_VALUE},
+ {"google.protobuf.ListValue", Descriptor::WELLKNOWNTYPE_LISTVALUE},
+ {"google.protobuf.Struct", Descriptor::WELLKNOWNTYPE_STRUCT},
+ });
+}
DescriptorPool::Tables::~Tables() { GOOGLE_DCHECK(checkpoints_.empty()); }
@@ -1209,8 +1234,8 @@
// allocators...
if (size == 0) return nullptr;
- allocations_.emplace_back(new char[size]);
- return allocations_.back().get();
+ allocations_.emplace_back(size);
+ return allocations_.back().data();
}
void FileDescriptorTables::BuildLocationsByPath(
@@ -1283,8 +1308,9 @@
enforce_dependencies_ = false;
}
-void DescriptorPool::AddUnusedImportTrackFile(const std::string& file_name) {
- unused_import_track_files_.insert(file_name);
+void DescriptorPool::AddUnusedImportTrackFile(const std::string& file_name,
+ bool is_error) {
+ unused_import_track_files_[file_name] = is_error;
}
void DescriptorPool::ClearUnusedImportTrackFiles() {
@@ -1315,6 +1341,10 @@
} // anonymous namespace
+DescriptorDatabase* DescriptorPool::internal_generated_database() {
+ return GeneratedDatabase();
+}
+
DescriptorPool* DescriptorPool::internal_generated_pool() {
static DescriptorPool* generated_pool =
internal::OnShutdownDelete(NewGeneratedPool());
@@ -1694,6 +1724,18 @@
}
}
+const FieldDescriptor* Descriptor::map_key() const {
+ if (!options().map_entry()) return nullptr;
+ GOOGLE_DCHECK_EQ(field_count(), 2);
+ return field(0);
+}
+
+const FieldDescriptor* Descriptor::map_value() const {
+ if (!options().map_entry()) return nullptr;
+ GOOGLE_DCHECK_EQ(field_count(), 2);
+ return field(1);
+}
+
const EnumValueDescriptor* EnumDescriptor::FindValueByName(
const std::string& key) const {
Symbol result =
@@ -2117,7 +2159,9 @@
if (has_json_name_) {
proto->set_json_name(json_name());
}
-
+ if (proto3_optional_) {
+ proto->set_proto3_optional(true);
+ }
// Some compilers do not allow static_cast directly between two enum types,
// so we must cast to int first.
proto->set_label(static_cast<FieldDescriptorProto::Label>(
@@ -2337,7 +2381,7 @@
if (RetrieveOptions(depth, options, pool, &all_options)) {
for (int i = 0; i < all_options.size(); i++) {
strings::SubstituteAndAppend(output, "$0option $1;\n", prefix,
- all_options[i]);
+ all_options[i]);
}
}
return !all_options.empty();
@@ -2422,7 +2466,7 @@
debug_string_options);
syntax_comment.AddPreComment(&contents);
strings::SubstituteAndAppend(&contents, "syntax = \"$0\";\n\n",
- SyntaxName(syntax()));
+ SyntaxName(syntax()));
syntax_comment.AddPostComment(&contents);
}
@@ -2439,13 +2483,13 @@
for (int i = 0; i < dependency_count(); i++) {
if (public_dependencies.count(i) > 0) {
strings::SubstituteAndAppend(&contents, "import public \"$0\";\n",
- dependency(i)->name());
+ dependency(i)->name());
} else if (weak_dependencies.count(i) > 0) {
strings::SubstituteAndAppend(&contents, "import weak \"$0\";\n",
- dependency(i)->name());
+ dependency(i)->name());
} else {
strings::SubstituteAndAppend(&contents, "import \"$0\";\n",
- dependency(i)->name());
+ dependency(i)->name());
}
}
@@ -2496,10 +2540,9 @@
if (i > 0) contents.append("}\n\n");
containing_type = extension(i)->containing_type();
strings::SubstituteAndAppend(&contents, "extend .$0 {\n",
- containing_type->full_name());
+ containing_type->full_name());
}
- extension(i)->DebugString(1, FieldDescriptor::PRINT_LABEL, &contents,
- debug_string_options);
+ extension(i)->DebugString(1, &contents, debug_string_options);
}
if (extension_count() > 0) contents.append("}\n\n");
@@ -2567,8 +2610,7 @@
}
for (int i = 0; i < field_count(); i++) {
if (field(i)->containing_oneof() == nullptr) {
- field(i)->DebugString(depth, FieldDescriptor::PRINT_LABEL, contents,
- debug_string_options);
+ field(i)->DebugString(depth, contents, debug_string_options);
} else if (field(i)->containing_oneof()->field(0) == field(i)) {
// This is the first field in this oneof, so print the whole oneof.
field(i)->containing_oneof()->DebugString(depth, contents,
@@ -2578,8 +2620,8 @@
for (int i = 0; i < extension_range_count(); i++) {
strings::SubstituteAndAppend(contents, "$0 extensions $1 to $2;\n", prefix,
- extension_range(i)->start,
- extension_range(i)->end - 1);
+ extension_range(i)->start,
+ extension_range(i)->end - 1);
}
// Group extensions by what they extend, so they can be printed out together.
@@ -2589,10 +2631,9 @@
if (i > 0) strings::SubstituteAndAppend(contents, "$0 }\n", prefix);
containing_type = extension(i)->containing_type();
strings::SubstituteAndAppend(contents, "$0 extend .$1 {\n", prefix,
- containing_type->full_name());
+ containing_type->full_name());
}
- extension(i)->DebugString(depth + 1, FieldDescriptor::PRINT_LABEL, contents,
- debug_string_options);
+ extension(i)->DebugString(depth + 1, contents, debug_string_options);
}
if (extension_count() > 0)
strings::SubstituteAndAppend(contents, "$0 }\n", prefix);
@@ -2605,7 +2646,7 @@
strings::SubstituteAndAppend(contents, "$0, ", range->start);
} else {
strings::SubstituteAndAppend(contents, "$0 to $1, ", range->start,
- range->end - 1);
+ range->end - 1);
}
}
contents->replace(contents->size() - 2, 2, ";\n");
@@ -2615,7 +2656,7 @@
strings::SubstituteAndAppend(contents, "$0 reserved ", prefix);
for (int i = 0; i < reserved_name_count(); i++) {
strings::SubstituteAndAppend(contents, "\"$0\", ",
- CEscape(reserved_name(i)));
+ CEscape(reserved_name(i)));
}
contents->replace(contents->size() - 2, 2, ";\n");
}
@@ -2635,10 +2676,10 @@
int depth = 0;
if (is_extension()) {
strings::SubstituteAndAppend(&contents, "extend .$0 {\n",
- containing_type()->full_name());
+ containing_type()->full_name());
depth = 1;
}
- DebugString(depth, PRINT_LABEL, &contents, debug_string_options);
+ DebugString(depth, &contents, debug_string_options);
if (is_extension()) {
contents.append("}\n");
}
@@ -2658,7 +2699,7 @@
}
void FieldDescriptor::DebugString(
- int depth, PrintLabelFlag print_label_flag, std::string* contents,
+ int depth, std::string* contents,
const DebugStringOptions& debug_string_options) const {
std::string prefix(depth * 2, ' ');
std::string field_type;
@@ -2673,20 +2714,12 @@
field_type = FieldTypeNameDebugString();
}
- bool print_label = true;
- // Determine whether to omit label:
- // 1. For an optional field, omit label if it's in oneof or in proto3.
- // 2. For a repeated field, omit label if it's a map.
- if (is_optional() && (print_label_flag == OMIT_LABEL ||
- file()->syntax() == FileDescriptor::SYNTAX_PROTO3)) {
- print_label = false;
- } else if (is_map()) {
- print_label = false;
- }
- std::string label;
- if (print_label) {
- label = kLabelToName[this->label()];
- label.push_back(' ');
+ std::string label = StrCat(kLabelToName[this->label()], " ");
+
+ // Label is omitted for maps, oneof, and plain proto3 fields.
+ if (is_map() || containing_oneof() ||
+ (is_optional() && !has_optional_keyword())) {
+ label.clear();
}
SourceLocationCommentPrinter comment_printer(this, prefix,
@@ -2701,7 +2734,7 @@
if (has_default_value()) {
bracketed = true;
strings::SubstituteAndAppend(contents, " [default = $0",
- DefaultValueAsString(true));
+ DefaultValueAsString(true));
}
if (has_json_name_) {
if (!bracketed) {
@@ -2771,8 +2804,7 @@
} else {
contents->append("\n");
for (int i = 0; i < field_count(); i++) {
- field(i)->DebugString(depth, FieldDescriptor::OMIT_LABEL, contents,
- debug_string_options);
+ field(i)->DebugString(depth, contents, debug_string_options);
}
strings::SubstituteAndAppend(contents, "$0}\n", prefix);
}
@@ -2817,7 +2849,7 @@
strings::SubstituteAndAppend(contents, "$0, ", range->start);
} else {
strings::SubstituteAndAppend(contents, "$0 to $1, ", range->start,
- range->end);
+ range->end);
}
}
contents->replace(contents->size() - 2, 2, ";\n");
@@ -2827,7 +2859,7 @@
strings::SubstituteAndAppend(contents, "$0 reserved ", prefix);
for (int i = 0; i < reserved_name_count(); i++) {
strings::SubstituteAndAppend(contents, "\"$0\", ",
- CEscape(reserved_name(i)));
+ CEscape(reserved_name(i)));
}
contents->replace(contents->size() - 2, 2, ";\n");
}
@@ -2933,7 +2965,7 @@
if (FormatLineOptions(depth, options(), service()->file()->pool(),
&formatted_options)) {
strings::SubstituteAndAppend(contents, " {\n$0$1}\n", formatted_options,
- prefix);
+ prefix);
} else {
contents->append(";\n");
}
@@ -3246,7 +3278,7 @@
// Like AddSymbol(), but succeeds if the symbol is already defined as long
// as the existing definition is also a package (because it's OK to define
// the same package in two different files). Also adds all parents of the
- // packgae to the symbol table (e.g. AddPackage("foo.bar", ...) will add
+ // package to the symbol table (e.g. AddPackage("foo.bar", ...) will add
// "foo.bar" and "foo" to the table).
void AddPackage(const std::string& name, const Message& proto,
const FileDescriptor* file);
@@ -3294,14 +3326,14 @@
void BuildMessage(const DescriptorProto& proto, const Descriptor* parent,
Descriptor* result);
void BuildFieldOrExtension(const FieldDescriptorProto& proto,
- const Descriptor* parent, FieldDescriptor* result,
+ Descriptor* parent, FieldDescriptor* result,
bool is_extension);
- void BuildField(const FieldDescriptorProto& proto, const Descriptor* parent,
+ void BuildField(const FieldDescriptorProto& proto, Descriptor* parent,
FieldDescriptor* result) {
BuildFieldOrExtension(proto, parent, result, false);
}
- void BuildExtension(const FieldDescriptorProto& proto,
- const Descriptor* parent, FieldDescriptor* result) {
+ void BuildExtension(const FieldDescriptorProto& proto, Descriptor* parent,
+ FieldDescriptor* result) {
BuildFieldOrExtension(proto, parent, result, true);
}
void BuildExtensionRange(const DescriptorProto::ExtensionRange& proto,
@@ -3424,6 +3456,7 @@
void SetUInt64(int number, uint64 value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields);
+
// A helper function that adds an error at the specified location of the
// option we're currently interpreting, and returns false.
bool AddOptionError(DescriptorPool::ErrorCollector::ErrorLocation location,
@@ -3493,7 +3526,7 @@
return pool->enforce_weak_;
}
static inline bool get_is_placeholder(const Descriptor* descriptor) {
- return descriptor->is_placeholder_;
+ return descriptor != nullptr && descriptor->is_placeholder_;
}
static inline void assert_mutex_held(const DescriptorPool* pool) {
if (pool->mutex_ != nullptr) {
@@ -3517,6 +3550,9 @@
const EnumDescriptorProto& proto);
void ValidateEnumValueOptions(EnumValueDescriptor* enum_value,
const EnumValueDescriptorProto& proto);
+ void ValidateExtensionRangeOptions(
+ const std::string& full_name, Descriptor::ExtensionRange* extension_range,
+ const DescriptorProto_ExtensionRange& proto);
void ValidateServiceOptions(ServiceDescriptor* service,
const ServiceDescriptorProto& proto);
void ValidateMethodOptions(MethodDescriptor* method,
@@ -3988,7 +4024,7 @@
placeholder->tables_ = &FileDescriptorTables::GetEmptyInstance();
placeholder->source_code_info_ = &SourceCodeInfo::default_instance();
placeholder->is_placeholder_ = true;
- placeholder->syntax_ = FileDescriptor::SYNTAX_PROTO2;
+ placeholder->syntax_ = FileDescriptor::SYNTAX_UNKNOWN;
placeholder->finished_building_ = true;
// All other fields are zero or nullptr.
@@ -4489,9 +4525,8 @@
BUILD_ARRAY(proto, result, extension, BuildExtension, nullptr);
// Copy options.
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
AllocateOptions(proto.options(), result);
}
@@ -4532,8 +4567,10 @@
// Again, see comments at InternalSetLazilyBuildDependencies about error
- // checking.
- if (!unused_dependency_.empty() && !pool_->lazily_build_dependencies_) {
+ // checking. Also, don't log unused dependencies if there were previous
+ // errors, since the results might be inaccurate.
+ if (!had_errors_ && !unused_dependency_.empty() &&
+ !pool_->lazily_build_dependencies_) {
LogUnusedDependency(proto, result);
}
@@ -4571,6 +4608,12 @@
result->containing_type_ = parent;
result->is_placeholder_ = false;
result->is_unqualified_placeholder_ = false;
+ result->well_known_type_ = Descriptor::WELLKNOWNTYPE_UNSPECIFIED;
+
+ auto it = pool_->tables_->well_known_types_.find(*full_name);
+ if (it != pool_->tables_->well_known_types_.end()) {
+ result->well_known_type_ = it->second;
+ }
// Build oneofs first so that fields and extension ranges can refer to them.
BUILD_ARRAY(proto, result, oneof_decl, BuildOneof, result);
@@ -4592,9 +4635,8 @@
}
// Copy options.
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
AllocateOptions(proto.options(), result,
DescriptorProto::kOptionsFieldNumber,
"google.protobuf.MessageOptions");
@@ -4610,9 +4652,9 @@
AddError(result->full_name(), proto.reserved_range(i),
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Reserved range $0 to $1 overlaps with "
- "already-defined range $2 to $3.",
- range2.start(), range2.end() - 1,
- range1.start(), range1.end() - 1));
+ "already-defined range $2 to $3.",
+ range2.start(), range2.end() - 1,
+ range1.start(), range1.end() - 1));
}
}
}
@@ -4624,11 +4666,12 @@
reserved_name_set.insert(name);
} else {
AddError(name, proto, DescriptorPool::ErrorCollector::NAME,
- strings::Substitute(
- "Field name \"$0\" is reserved multiple times.", name));
+ strings::Substitute("Field name \"$0\" is reserved multiple times.",
+ name));
}
}
+
for (int i = 0; i < result->field_count(); i++) {
const FieldDescriptor* field = result->field(i);
for (int j = 0; j < result->extension_range_count(); j++) {
@@ -4648,7 +4691,7 @@
AddError(field->full_name(), proto.reserved_range(j),
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Field \"$0\" uses reserved number $1.",
- field->name(), field->number()));
+ field->name(), field->number()));
}
}
if (reserved_name_set.find(field->name()) != reserved_name_set.end()) {
@@ -4657,10 +4700,11 @@
DescriptorPool::ErrorCollector::NAME,
strings::Substitute("Field name \"$0\" is reserved.", field->name()));
}
+
}
// Check that extension ranges don't overlap and don't include
- // reserved field numbers.
+ // reserved field numbers or names.
for (int i = 0; i < result->extension_range_count(); i++) {
const Descriptor::ExtensionRange* range1 = result->extension_range(i);
for (int j = 0; j < result->reserved_range_count(); j++) {
@@ -4669,9 +4713,9 @@
AddError(result->full_name(), proto.extension_range(i),
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Extension range $0 to $1 overlaps with "
- "reserved range $2 to $3.",
- range1->start, range1->end - 1,
- range2->start, range2->end - 1));
+ "reserved range $2 to $3.",
+ range1->start, range1->end - 1, range2->start,
+ range2->end - 1));
}
}
for (int j = i + 1; j < result->extension_range_count(); j++) {
@@ -4680,16 +4724,16 @@
AddError(result->full_name(), proto.extension_range(i),
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Extension range $0 to $1 overlaps with "
- "already-defined range $2 to $3.",
- range2->start, range2->end - 1,
- range1->start, range1->end - 1));
+ "already-defined range $2 to $3.",
+ range2->start, range2->end - 1, range1->start,
+ range1->end - 1));
}
}
}
}
void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
- const Descriptor* parent,
+ Descriptor* parent,
FieldDescriptor* result,
bool is_extension) {
const std::string& scope =
@@ -4702,6 +4746,15 @@
result->file_ = file_;
result->number_ = proto.number();
result->is_extension_ = is_extension;
+ result->proto3_optional_ = proto.proto3_optional();
+
+ if (proto.proto3_optional() &&
+ file_->syntax() != FileDescriptor::SYNTAX_PROTO3) {
+ AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
+ "The [proto3_optional=true] option may only be set on proto3"
+ "fields, not " +
+ result->full_name());
+ }
// If .proto files follow the style guide then the name should already be
// lower-cased. If that's the case we can just reuse the string we
@@ -4736,17 +4789,18 @@
result->label_ = static_cast<FieldDescriptor::Label>(
implicit_cast<int>(proto.label()));
- // An extension cannot have a required field (b/13365836).
- if (result->is_extension_ &&
- result->label_ == FieldDescriptor::LABEL_REQUIRED) {
- AddError(result->full_name(), proto,
- // Error location `TYPE`: we would really like to indicate
- // `LABEL`, but the `ErrorLocation` enum has no entry for this, and
- // we don't necessarily know about all implementations of the
- // `ErrorCollector` interface to extend them to handle the new
- // error location type properly.
- DescriptorPool::ErrorCollector::TYPE,
- "The extension " + result->full_name() + " cannot be required.");
+ if (result->label_ == FieldDescriptor::LABEL_REQUIRED) {
+ // An extension cannot have a required field (b/13365836).
+ if (result->is_extension_) {
+ AddError(result->full_name(), proto,
+ // Error location `TYPE`: we would really like to indicate
+ // `LABEL`, but the `ErrorLocation` enum has no entry for this,
+ // and we don't necessarily know about all implementations of the
+ // `ErrorCollector` interface to extend them to handle the new
+ // error location type properly.
+ DescriptorPool::ErrorCollector::TYPE,
+ "The extension " + result->full_name() + " cannot be required.");
+ }
}
// Some of these may be filled in when cross-linking.
@@ -4910,7 +4964,7 @@
// on extension numbers.
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Field numbers cannot be greater than $0.",
- FieldDescriptor::kMaxNumber));
+ FieldDescriptor::kMaxNumber));
} else if (result->number() >= FieldDescriptor::kFirstReservedNumber &&
result->number() <= FieldDescriptor::kLastReservedNumber) {
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
@@ -4953,8 +5007,8 @@
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::TYPE,
strings::Substitute("FieldDescriptorProto.oneof_index $0 is "
- "out of range for type \"$1\".",
- proto.oneof_index(), parent->name()));
+ "out of range for type \"$1\".",
+ proto.oneof_index(), parent->name()));
result->containing_oneof_ = nullptr;
} else {
result->containing_oneof_ = parent->oneof_decl(proto.oneof_index());
@@ -4965,9 +5019,8 @@
}
// Copy options.
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
AllocateOptions(proto.options(), result,
FieldDescriptorProto::kOptionsFieldNumber,
"google.protobuf.FieldOptions");
@@ -4997,9 +5050,8 @@
"Extension range end number must be greater than start number.");
}
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
std::vector<int> options_path;
parent->GetLocationPath(&options_path);
options_path.push_back(DescriptorProto::kExtensionRangeFieldNumber);
@@ -5169,9 +5221,8 @@
CheckEnumValueUniqueness(proto, result);
// Copy options.
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
AllocateOptions(proto.options(), result,
EnumDescriptorProto::kOptionsFieldNumber,
"google.protobuf.EnumOptions");
@@ -5189,9 +5240,9 @@
AddError(result->full_name(), proto.reserved_range(i),
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Reserved range $0 to $1 overlaps with "
- "already-defined range $2 to $3.",
- range2.start(), range2.end(),
- range1.start(), range1.end()));
+ "already-defined range $2 to $3.",
+ range2.start(), range2.end(), range1.start(),
+ range1.end()));
}
}
}
@@ -5203,8 +5254,8 @@
reserved_name_set.insert(name);
} else {
AddError(name, proto, DescriptorPool::ErrorCollector::NAME,
- strings::Substitute(
- "Enum value \"$0\" is reserved multiple times.", name));
+ strings::Substitute("Enum value \"$0\" is reserved multiple times.",
+ name));
}
}
@@ -5213,11 +5264,10 @@
for (int j = 0; j < result->reserved_range_count(); j++) {
const EnumDescriptor::ReservedRange* range = result->reserved_range(j);
if (range->start <= value->number() && value->number() <= range->end) {
- AddError(
- value->full_name(), proto.reserved_range(j),
- DescriptorPool::ErrorCollector::NUMBER,
- strings::Substitute("Enum value \"$0\" uses reserved number $1.",
- value->name(), value->number()));
+ AddError(value->full_name(), proto.reserved_range(j),
+ DescriptorPool::ErrorCollector::NUMBER,
+ strings::Substitute("Enum value \"$0\" uses reserved number $1.",
+ value->name(), value->number()));
}
}
if (reserved_name_set.find(value->name()) != reserved_name_set.end()) {
@@ -5248,9 +5298,8 @@
ValidateSymbolName(proto.name(), *full_name, proto);
// Copy options.
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
AllocateOptions(proto.options(), result,
EnumValueDescriptorProto::kOptionsFieldNumber,
"google.protobuf.EnumValueOptions");
@@ -5314,9 +5363,8 @@
BUILD_ARRAY(proto, result, method, BuildMethod, result);
// Copy options.
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
AllocateOptions(proto.options(), result,
ServiceDescriptorProto::kOptionsFieldNumber,
"google.protobuf.ServiceOptions");
@@ -5343,9 +5391,8 @@
result->output_type_.Init();
// Copy options.
- if (!proto.has_options()) {
- result->options_ = nullptr; // Will set to default_instance later.
- } else {
+ result->options_ = nullptr; // Set to default_instance later if necessary.
+ if (proto.has_options()) {
AllocateOptions(proto.options(), result,
MethodDescriptorProto::kOptionsFieldNumber,
"google.protobuf.MethodOptions");
@@ -5469,6 +5516,42 @@
message->field(i);
}
}
+
+ for (int i = 0; i < message->field_count(); i++) {
+ const FieldDescriptor* field = message->field(i);
+ if (field->proto3_optional_) {
+ if (!field->containing_oneof() ||
+ !field->containing_oneof()->is_synthetic()) {
+ AddError(message->full_name(), proto.field(i),
+ DescriptorPool::ErrorCollector::OTHER,
+ "Fields with proto3_optional set must be "
+ "a member of a one-field oneof");
+ }
+ }
+ }
+
+ // Synthetic oneofs must be last.
+ int first_synthetic = -1;
+ for (int i = 0; i < message->oneof_decl_count(); i++) {
+ const OneofDescriptor* oneof = message->oneof_decl(i);
+ if (oneof->is_synthetic()) {
+ if (first_synthetic == -1) {
+ first_synthetic = i;
+ }
+ } else {
+ if (first_synthetic != -1) {
+ AddError(message->full_name(), proto.oneof_decl(i),
+ DescriptorPool::ErrorCollector::OTHER,
+ "Synthetic oneofs must be after all other oneofs");
+ }
+ }
+ }
+
+ if (first_synthetic == -1) {
+ message->real_oneof_decl_count_ = message->oneof_decl_count_;
+ } else {
+ message->real_oneof_decl_count_ = first_synthetic;
+ }
}
void DescriptorBuilder::CrossLinkExtensionRange(
@@ -5519,9 +5602,9 @@
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("\"$0\" does not declare $1 as an "
- "extension number.",
- field->containing_type()->full_name(),
- field->number()));
+ "extension number.",
+ field->containing_type()->full_name(),
+ field->number()));
}
}
}
@@ -5544,7 +5627,7 @@
proto.has_default_value();
// In case of weak fields we force building the dependency. We need to know
- // if the type exist or not. If it doesnt exist we substitute Empty which
+ // if the type exist or not. If it doesn't exist we substitute Empty which
// should only be done if the type can't be found in the generated pool.
// TODO(gerbens) Ideally we should query the database directly to check
// if weak fields exist or not so that we don't need to force building
@@ -5702,16 +5785,16 @@
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Extension number $0 has already been used "
- "in \"$1\" by extension \"$2\".",
- field->number(), containing_type_name,
- conflicting_field->full_name()));
+ "in \"$1\" by extension \"$2\".",
+ field->number(), containing_type_name,
+ conflicting_field->full_name()));
} else {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER,
strings::Substitute("Field number $0 has already been used in "
- "\"$1\" by field \"$2\".",
- field->number(), containing_type_name,
- conflicting_field->name()));
+ "\"$1\" by field \"$2\".",
+ field->number(), containing_type_name,
+ conflicting_field->name()));
}
} else {
if (field->is_extension()) {
@@ -5951,7 +6034,8 @@
}
if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
field->enum_type() &&
- field->enum_type()->file()->syntax() != FileDescriptor::SYNTAX_PROTO3) {
+ field->enum_type()->file()->syntax() != FileDescriptor::SYNTAX_PROTO3 &&
+ field->enum_type()->file()->syntax() != FileDescriptor::SYNTAX_UNKNOWN) {
// Proto3 messages can only use Proto3 enum types; otherwise we can't
// guarantee that the default value is zero.
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
@@ -5988,12 +6072,15 @@
: FieldDescriptor::kMaxNumber);
for (int i = 0; i < message->extension_range_count(); ++i) {
if (message->extension_range(i)->end > max_extension_range + 1) {
- AddError(
- message->full_name(), proto.extension_range(i),
- DescriptorPool::ErrorCollector::NUMBER,
- strings::Substitute("Extension numbers cannot be greater than $0.",
- max_extension_range));
+ AddError(message->full_name(), proto.extension_range(i),
+ DescriptorPool::ErrorCollector::NUMBER,
+ strings::Substitute("Extension numbers cannot be greater than $0.",
+ max_extension_range));
}
+
+ ValidateExtensionRangeOptions(message->full_name(),
+ message->extension_ranges_ + i,
+ proto.extension_range(i));
}
}
@@ -6108,6 +6195,12 @@
const EnumValueDescriptorProto& /* proto */) {
// Nothing to do so far.
}
+
+void DescriptorBuilder::ValidateExtensionRangeOptions(
+ const std::string& full_name, Descriptor::ExtensionRange* extension_range,
+ const DescriptorProto_ExtensionRange& proto) {
+}
+
void DescriptorBuilder::ValidateServiceOptions(
ServiceDescriptor* service, const ServiceDescriptorProto& proto) {
if (IsLite(service->file()) &&
@@ -6145,8 +6238,8 @@
return false;
}
- const FieldDescriptor* key = message->field(0);
- const FieldDescriptor* value = message->field(1);
+ const FieldDescriptor* key = message->map_key();
+ const FieldDescriptor* value = message->map_value();
if (key->label() != FieldDescriptor::LABEL_OPTIONAL || key->number() != 1 ||
key->name() != "key") {
return false;
@@ -6303,6 +6396,7 @@
DescriptorBuilder::OptionInterpreter::~OptionInterpreter() {}
+
bool DescriptorBuilder::OptionInterpreter::InterpretOptions(
OptionsToInterpret* options_to_interpret) {
// Note that these may be in different pools, so we can't use the same
@@ -6382,6 +6476,8 @@
options->GetReflection()->Swap(unparsed_options.get(), options);
}
}
+
+
return !failed;
}
@@ -7170,13 +7266,20 @@
const FileDescriptor* result) {
if (!unused_dependency_.empty()) {
+ auto itr = pool_->unused_import_track_files_.find(proto.name());
+ bool is_error =
+ itr != pool_->unused_import_track_files_.end() && itr->second;
for (std::set<const FileDescriptor*>::const_iterator it =
unused_dependency_.begin();
it != unused_dependency_.end(); ++it) {
- // Log warnings for unused imported files.
std::string error_message = "Import " + (*it)->name() + " is unused.";
- AddWarning((*it)->name(), proto, DescriptorPool::ErrorCollector::IMPORT,
+ if (is_error) {
+ AddError((*it)->name(), proto, DescriptorPool::ErrorCollector::IMPORT,
error_message);
+ } else {
+ AddWarning((*it)->name(), proto, DescriptorPool::ErrorCollector::IMPORT,
+ error_message);
+ }
}
}
}
diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h
index 422e444..b55841f 100644
--- a/src/google/protobuf/descriptor.h
+++ b/src/google/protobuf/descriptor.h
@@ -54,14 +54,15 @@
#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_H__
#define GOOGLE_PROTOBUF_DESCRIPTOR_H__
+#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
+
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/stubs/once.h>
-
#include <google/protobuf/port_def.inc>
// TYPE_BOOL is defined in the MacOS's ConditionalMacros.h.
@@ -264,7 +265,7 @@
// isn't, the result may be garbage.
void CopyTo(DescriptorProto* proto) const;
- // Write the contents of this decriptor in a human-readable form. Output
+ // Write the contents of this descriptor in a human-readable form. Output
// will be suitable for re-parsing.
std::string DebugString() const;
@@ -277,6 +278,36 @@
// with AllowUnknownDependencies() set.
bool is_placeholder() const;
+ enum WellKnownType {
+ WELLKNOWNTYPE_UNSPECIFIED, // Not a well-known type.
+
+ // Wrapper types.
+ WELLKNOWNTYPE_DOUBLEVALUE, // google.protobuf.DoubleValue
+ WELLKNOWNTYPE_FLOATVALUE, // google.protobuf.FloatValue
+ WELLKNOWNTYPE_INT64VALUE, // google.protobuf.Int64Value
+ WELLKNOWNTYPE_UINT64VALUE, // google.protobuf.UInt64Value
+ WELLKNOWNTYPE_INT32VALUE, // google.protobuf.Int32Value
+ WELLKNOWNTYPE_UINT32VALUE, // google.protobuf.UInt32Value
+ WELLKNOWNTYPE_STRINGVALUE, // google.protobuf.StringValue
+ WELLKNOWNTYPE_BYTESVALUE, // google.protobuf.BytesValue
+ WELLKNOWNTYPE_BOOLVALUE, // google.protobuf.BoolValue
+
+ // Other well known types.
+ WELLKNOWNTYPE_ANY, // google.protobuf.Any
+ WELLKNOWNTYPE_FIELDMASK, // google.protobuf.FieldMask
+ WELLKNOWNTYPE_DURATION, // google.protobuf.Duration
+ WELLKNOWNTYPE_TIMESTAMP, // google.protobuf.Timestamp
+ WELLKNOWNTYPE_VALUE, // google.protobuf.Value
+ WELLKNOWNTYPE_LISTVALUE, // google.protobuf.ListValue
+ WELLKNOWNTYPE_STRUCT, // google.protobuf.Struct
+
+ // New well-known types may be added in the future.
+ // Please make sure any switch() statements have a 'default' case.
+ __WELLKNOWNTYPE__DO_NOT_USE__ADD_DEFAULT_INSTEAD__,
+ };
+
+ WellKnownType well_known_type() const;
+
// Field stuff -----------------------------------------------------
// The number of fields in this message type.
@@ -306,6 +337,10 @@
// The number of oneofs in this message type.
int oneof_decl_count() const;
+ // The number of oneofs in this message type, excluding synthetic oneofs.
+ // Real oneofs always come first, so iterating up to real_oneof_decl_cout()
+ // will yield all real oneofs.
+ int real_oneof_decl_count() const;
// Get a oneof by index, where 0 <= index < oneof_decl_count().
// These are returned in the order they were defined in the .proto file.
const OneofDescriptor* oneof_decl(int index) const;
@@ -372,8 +407,30 @@
// Returns nullptr if no extension range contains the given number.
const ExtensionRange* FindExtensionRangeContainingNumber(int number) const;
- // The number of extensions -- extending *other* messages -- that were
- // defined nested within this message type's scope.
+ // The number of extensions defined nested within this message type's scope.
+ // See doc:
+ // https://developers.google.com/protocol-buffers/docs/proto#nested-extensions
+ //
+ // Note that the extensions may be extending *other* messages.
+ //
+ // For example:
+ // message M1 {
+ // extensions 1 to max;
+ // }
+ //
+ // message M2 {
+ // extend M1 {
+ // optional int32 foo = 1;
+ // }
+ // }
+ //
+ // In this case,
+ // DescriptorPool::generated_pool()
+ // ->FindMessageTypeByName("M2")
+ // ->extension(0)
+ // will return "foo", even though "foo" is an extension of M1.
+ // To find all known extensions of a given message, instead use
+ // DescriptorPool::FindAllExtensions.
int extension_count() const;
// Get an extension by index, where 0 <= index < extension_count().
// These are returned in the order they were defined in the .proto file.
@@ -430,6 +487,16 @@
// |*out_location| unchanged iff location information was not available.
bool GetSourceLocation(SourceLocation* out_location) const;
+ // Maps --------------------------------------------------------------
+
+ // Returns the FieldDescriptor for the "key" field. If this isn't a map entry
+ // field, returns nullptr.
+ const FieldDescriptor* map_key() const;
+
+ // Returns the FieldDescriptor for the "value" field. If this isn't a map
+ // entry field, returns nullptr.
+ const FieldDescriptor* map_value() const;
+
private:
typedef MessageOptions OptionsType;
@@ -473,6 +540,7 @@
int field_count_;
int oneof_decl_count_;
+ int real_oneof_decl_count_;
int nested_type_count_;
int enum_type_count_;
int extension_range_count_;
@@ -484,6 +552,8 @@
bool is_placeholder_;
// True if this is a placeholder and the type name wasn't fully-qualified.
bool is_unqualified_placeholder_;
+ // Well known type. Stored as char to conserve space.
+ char well_known_type_;
// IMPORTANT: If you add a new field, make sure to search for all instances
// of Allocate<Descriptor>() and AllocateArray<Descriptor>() in descriptor.cc
@@ -629,6 +699,19 @@
bool is_map() const; // shorthand for type() == TYPE_MESSAGE &&
// message_type()->options().map_entry()
+ // Returns true if this field was syntactically written with "optional" in the
+ // .proto file. Excludes singular proto3 fields that do not have a label.
+ bool has_optional_keyword() const;
+
+ // Returns true if this field tracks presence, ie. does the field
+ // distinguish between "unset" and "present with default value."
+ // This includes required, optional, and oneof fields. It excludes maps,
+ // repeated fields, and singular proto3 fields without "optional".
+ //
+ // For fields where has_presence() == true, the return value of
+ // Reflection::HasField() is semantically meaningful.
+ bool has_presence() const;
+
// Index of this field within the message's field array, or the file or
// extension scope's extensions array.
int index() const;
@@ -678,6 +761,10 @@
// nullptr.
const OneofDescriptor* containing_oneof() const;
+ // If the field is a member of a non-synthetic oneof, returns the descriptor
+ // for the oneof, otherwise returns nullptr.
+ const OneofDescriptor* real_containing_oneof() const;
+
// If the field is a member of a oneof, returns the index in that oneof.
int index_in_oneof() const;
@@ -756,9 +843,7 @@
void CopyJsonNameTo(FieldDescriptorProto* proto) const;
// See Descriptor::DebugString().
- enum PrintLabelFlag { PRINT_LABEL, OMIT_LABEL };
- void DebugString(int depth, PrintLabelFlag print_label_flag,
- std::string* contents,
+ void DebugString(int depth, std::string* contents,
const DebugStringOptions& options) const;
// formats the default value appropriately and returns it as a string.
@@ -790,6 +875,7 @@
mutable Type type_;
Label label_;
bool has_default_value_;
+ bool proto3_optional_;
// Whether the user has specified the json_name field option in the .proto
// file.
bool has_json_name_;
@@ -850,6 +936,10 @@
// Index of this oneof within the message's oneof array.
int index() const;
+ // Returns whether this oneof was inserted by the compiler to wrap a proto3
+ // optional field. If this returns true, code generators should *not* emit it.
+ bool is_synthetic() const;
+
// The .proto file in which this oneof was defined. Never nullptr.
const FileDescriptor* file() const;
// The Descriptor for the message containing this oneof.
@@ -1462,7 +1552,7 @@
static void DependenciesOnceInit(const FileDescriptor* to_init);
void InternalDependenciesOnceInit() const;
- // These are arranged to minimze padding on 64-bit.
+ // These are arranged to minimize padding on 64-bit.
int dependency_count_;
int public_dependency_count_;
int weak_dependency_count_;
@@ -1752,6 +1842,11 @@
// the underlay takes precedence.
static DescriptorPool* internal_generated_pool();
+ // For internal use only: Gets a non-const pointer to the generated
+ // descriptor database.
+ // Only used for testing.
+ static DescriptorDatabase* internal_generated_database();
+
// For internal use only: Changes the behavior of BuildFile() such that it
// allows the file to make reference to message types declared in other files
// which it did not officially declare as dependencies.
@@ -1783,8 +1878,9 @@
bool InternalIsFileLoaded(const std::string& filename) const;
// Add a file to unused_import_track_files_. DescriptorBuilder will log
- // warnings for those files if there is any unused import.
- void AddUnusedImportTrackFile(const std::string& file_name);
+ // warnings or errors for those files if there is any unused import.
+ void AddUnusedImportTrackFile(const std::string& file_name,
+ bool is_error = false);
void ClearUnusedImportTrackFiles();
private:
@@ -1868,7 +1964,10 @@
bool allow_unknown_;
bool enforce_weak_;
bool disallow_enforce_utf8_;
- std::set<std::string> unused_import_track_files_;
+
+ // Set of files to track for unused imports. The bool value when true means
+ // unused imports are treated as errors (and as warnings when false).
+ std::map<std::string, bool> unused_import_track_files_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool);
};
@@ -1898,6 +1997,7 @@
PROTOBUF_DEFINE_ACCESSOR(Descriptor, field_count, int)
PROTOBUF_DEFINE_ACCESSOR(Descriptor, oneof_decl_count, int)
+PROTOBUF_DEFINE_ACCESSOR(Descriptor, real_oneof_decl_count, int)
PROTOBUF_DEFINE_ACCESSOR(Descriptor, nested_type_count, int)
PROTOBUF_DEFINE_ACCESSOR(Descriptor, enum_type_count, int)
@@ -2013,6 +2113,10 @@
// A few accessors differ from the macros...
+inline Descriptor::WellKnownType Descriptor::well_known_type() const {
+ return static_cast<Descriptor::WellKnownType>(well_known_type_);
+}
+
inline bool Descriptor::IsExtensionNumber(int number) const {
return FindExtensionRangeContainingNumber(number) != nullptr;
}
@@ -2082,6 +2186,24 @@
return type() == TYPE_MESSAGE && is_map_message_type();
}
+inline bool FieldDescriptor::has_optional_keyword() const {
+ return proto3_optional_ ||
+ (file()->syntax() == FileDescriptor::SYNTAX_PROTO2 && is_optional() &&
+ !containing_oneof());
+}
+
+inline const OneofDescriptor* FieldDescriptor::real_containing_oneof() const {
+ return containing_oneof_ && !containing_oneof_->is_synthetic()
+ ? containing_oneof_
+ : nullptr;
+}
+
+inline bool FieldDescriptor::has_presence() const {
+ if (is_repeated()) return false;
+ return cpp_type() == CPPTYPE_MESSAGE || containing_oneof() ||
+ file()->syntax() == FileDescriptor::SYNTAX_PROTO2;
+}
+
// To save space, index() is computed by looking at the descriptor's position
// in the parent's array of children.
inline int FieldDescriptor::index() const {
@@ -2110,6 +2232,10 @@
return static_cast<int>(this - containing_type_->oneof_decls_);
}
+inline bool OneofDescriptor::is_synthetic() const {
+ return field_count() == 1 && field(0)->proto3_optional_;
+}
+
inline int EnumDescriptor::index() const {
if (containing_type_ == nullptr) {
return static_cast<int>(this - file_->enum_types_);
diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc
index 470b292..471351c 100644
--- a/src/google/protobuf/descriptor.pb.cc
+++ b/src/google/protobuf/descriptor.pb.cc
@@ -567,13 +567,12 @@
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fdescriptor_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
- PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorSet, _has_bits_),
+ ~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorSet, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorSet, file_),
- ~0u,
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _has_bits_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _internal_metadata_),
~0u, // no _extensions_
@@ -648,13 +647,12 @@
1,
~0u,
~0u,
- PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _has_bits_),
+ ~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _internal_metadata_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _extensions_),
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, uninterpreted_option_),
- ~0u,
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _has_bits_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _internal_metadata_),
~0u, // no _extensions_
@@ -670,16 +668,18 @@
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, oneof_index_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, json_name_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, options_),
+ PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, proto3_optional_),
0,
6,
- 8,
9,
+ 10,
2,
1,
3,
7,
4,
5,
+ 8,
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _has_bits_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _internal_metadata_),
~0u, // no _extensions_
@@ -783,14 +783,14 @@
10,
11,
12,
- 19,
+ 18,
2,
13,
14,
15,
16,
17,
- 18,
+ 19,
3,
4,
5,
@@ -833,13 +833,12 @@
3,
4,
~0u,
- PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, _has_bits_),
+ ~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, _internal_metadata_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, _extensions_),
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::OneofOptions, uninterpreted_option_),
- ~0u,
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, _has_bits_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, _internal_metadata_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::EnumOptions, _extensions_),
@@ -923,13 +922,12 @@
0,
1,
~0u,
- PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo, _has_bits_),
+ ~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::SourceCodeInfo, location_),
- ~0u,
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _has_bits_),
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _internal_metadata_),
~0u, // no _extensions_
@@ -943,22 +941,21 @@
0,
1,
2,
- PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, _has_bits_),
+ ~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, annotation_),
- ~0u,
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
- { 0, 6, sizeof(PROTOBUF_NAMESPACE_ID::FileDescriptorSet)},
- { 7, 24, sizeof(PROTOBUF_NAMESPACE_ID::FileDescriptorProto)},
- { 36, 44, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange)},
- { 47, 54, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange)},
- { 56, 71, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto)},
- { 81, 87, sizeof(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions)},
- { 88, 103, sizeof(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto)},
+ { 0, -1, sizeof(PROTOBUF_NAMESPACE_ID::FileDescriptorSet)},
+ { 6, 23, sizeof(PROTOBUF_NAMESPACE_ID::FileDescriptorProto)},
+ { 35, 43, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange)},
+ { 46, 53, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange)},
+ { 55, 70, sizeof(PROTOBUF_NAMESPACE_ID::DescriptorProto)},
+ { 80, -1, sizeof(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions)},
+ { 86, 102, sizeof(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto)},
{ 113, 120, sizeof(PROTOBUF_NAMESPACE_ID::OneofDescriptorProto)},
{ 122, 129, sizeof(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange)},
{ 131, 141, sizeof(PROTOBUF_NAMESPACE_ID::EnumDescriptorProto)},
@@ -968,17 +965,17 @@
{ 185, 211, sizeof(PROTOBUF_NAMESPACE_ID::FileOptions)},
{ 232, 242, sizeof(PROTOBUF_NAMESPACE_ID::MessageOptions)},
{ 247, 259, sizeof(PROTOBUF_NAMESPACE_ID::FieldOptions)},
- { 266, 272, sizeof(PROTOBUF_NAMESPACE_ID::OneofOptions)},
- { 273, 281, sizeof(PROTOBUF_NAMESPACE_ID::EnumOptions)},
- { 284, 291, sizeof(PROTOBUF_NAMESPACE_ID::EnumValueOptions)},
- { 293, 300, sizeof(PROTOBUF_NAMESPACE_ID::ServiceOptions)},
- { 302, 310, sizeof(PROTOBUF_NAMESPACE_ID::MethodOptions)},
- { 313, 320, sizeof(PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart)},
- { 322, 334, sizeof(PROTOBUF_NAMESPACE_ID::UninterpretedOption)},
- { 341, 351, sizeof(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location)},
- { 356, 362, sizeof(PROTOBUF_NAMESPACE_ID::SourceCodeInfo)},
- { 363, 372, sizeof(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation)},
- { 376, 382, sizeof(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo)},
+ { 266, -1, sizeof(PROTOBUF_NAMESPACE_ID::OneofOptions)},
+ { 272, 280, sizeof(PROTOBUF_NAMESPACE_ID::EnumOptions)},
+ { 283, 290, sizeof(PROTOBUF_NAMESPACE_ID::EnumValueOptions)},
+ { 292, 299, sizeof(PROTOBUF_NAMESPACE_ID::ServiceOptions)},
+ { 301, 309, sizeof(PROTOBUF_NAMESPACE_ID::MethodOptions)},
+ { 312, 319, sizeof(PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart)},
+ { 321, 333, sizeof(PROTOBUF_NAMESPACE_ID::UninterpretedOption)},
+ { 340, 350, sizeof(PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location)},
+ { 355, -1, sizeof(PROTOBUF_NAMESPACE_ID::SourceCodeInfo)},
+ { 361, 370, sizeof(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation)},
+ { 374, -1, sizeof(PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
@@ -1046,7 +1043,7 @@
"s\032+\n\rReservedRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end"
"\030\002 \001(\005\"g\n\025ExtensionRangeOptions\022C\n\024unint"
"erpreted_option\030\347\007 \003(\0132$.google.protobuf"
- ".UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"\274\005\n\024Fiel"
+ ".UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"\325\005\n\024Fiel"
"dDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n\006number"
"\030\003 \001(\005\022:\n\005label\030\004 \001(\0162+.google.protobuf."
"FieldDescriptorProto.Label\0228\n\004type\030\005 \001(\016"
@@ -1054,115 +1051,116 @@
"Type\022\021\n\ttype_name\030\006 \001(\t\022\020\n\010extendee\030\002 \001("
"\t\022\025\n\rdefault_value\030\007 \001(\t\022\023\n\013oneof_index\030"
"\t \001(\005\022\021\n\tjson_name\030\n \001(\t\022.\n\007options\030\010 \001("
- "\0132\035.google.protobuf.FieldOptions\"\266\002\n\004Typ"
- "e\022\017\n\013TYPE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTY"
- "PE_INT64\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT3"
- "2\020\005\022\020\n\014TYPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022"
- "\r\n\tTYPE_BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_"
- "GROUP\020\n\022\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020"
- "\014\022\017\n\013TYPE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYP"
- "E_SFIXED32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_"
- "SINT32\020\021\022\017\n\013TYPE_SINT64\020\022\"C\n\005Label\022\022\n\016LA"
- "BEL_OPTIONAL\020\001\022\022\n\016LABEL_REQUIRED\020\002\022\022\n\016LA"
- "BEL_REPEATED\020\003\"T\n\024OneofDescriptorProto\022\014"
- "\n\004name\030\001 \001(\t\022.\n\007options\030\002 \001(\0132\035.google.p"
- "rotobuf.OneofOptions\"\244\002\n\023EnumDescriptorP"
- "roto\022\014\n\004name\030\001 \001(\t\0228\n\005value\030\002 \003(\0132).goog"
- "le.protobuf.EnumValueDescriptorProto\022-\n\007"
- "options\030\003 \001(\0132\034.google.protobuf.EnumOpti"
- "ons\022N\n\016reserved_range\030\004 \003(\01326.google.pro"
- "tobuf.EnumDescriptorProto.EnumReservedRa"
- "nge\022\025\n\rreserved_name\030\005 \003(\t\032/\n\021EnumReserv"
- "edRange\022\r\n\005start\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\"l\n\030E"
- "numValueDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n"
- "\006number\030\002 \001(\005\0222\n\007options\030\003 \001(\0132!.google."
- "protobuf.EnumValueOptions\"\220\001\n\026ServiceDes"
- "criptorProto\022\014\n\004name\030\001 \001(\t\0226\n\006method\030\002 \003"
- "(\0132&.google.protobuf.MethodDescriptorPro"
- "to\0220\n\007options\030\003 \001(\0132\037.google.protobuf.Se"
- "rviceOptions\"\301\001\n\025MethodDescriptorProto\022\014"
- "\n\004name\030\001 \001(\t\022\022\n\ninput_type\030\002 \001(\t\022\023\n\013outp"
- "ut_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.google."
- "protobuf.MethodOptions\022\037\n\020client_streami"
- "ng\030\005 \001(\010:\005false\022\037\n\020server_streaming\030\006 \001("
- "\010:\005false\"\246\006\n\013FileOptions\022\024\n\014java_package"
- "\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 \001(\t\022\"\n\023"
- "java_multiple_files\030\n \001(\010:\005false\022)\n\035java"
- "_generate_equals_and_hash\030\024 \001(\010B\002\030\001\022%\n\026j"
- "ava_string_check_utf8\030\033 \001(\010:\005false\022F\n\014op"
- "timize_for\030\t \001(\0162).google.protobuf.FileO"
- "ptions.OptimizeMode:\005SPEED\022\022\n\ngo_package"
- "\030\013 \001(\t\022\"\n\023cc_generic_services\030\020 \001(\010:\005fal"
- "se\022$\n\025java_generic_services\030\021 \001(\010:\005false"
- "\022\"\n\023py_generic_services\030\022 \001(\010:\005false\022#\n\024"
- "php_generic_services\030* \001(\010:\005false\022\031\n\ndep"
- "recated\030\027 \001(\010:\005false\022\037\n\020cc_enable_arenas"
- "\030\037 \001(\010:\005false\022\031\n\021objc_class_prefix\030$ \001(\t"
- "\022\030\n\020csharp_namespace\030% \001(\t\022\024\n\014swift_pref"
- "ix\030\' \001(\t\022\030\n\020php_class_prefix\030( \001(\t\022\025\n\rph"
- "p_namespace\030) \001(\t\022\036\n\026php_metadata_namesp"
- "ace\030, \001(\t\022\024\n\014ruby_package\030- \001(\t\022C\n\024unint"
- "erpreted_option\030\347\007 \003(\0132$.google.protobuf"
- ".UninterpretedOption\":\n\014OptimizeMode\022\t\n\005"
- "SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003"
- "*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\362\001\n\016MessageOptions\022&\n\027"
- "message_set_wire_format\030\001 \001(\010:\005false\022.\n\037"
- "no_standard_descriptor_accessor\030\002 \001(\010:\005f"
- "alse\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021\n\tmap_e"
- "ntry\030\007 \001(\010\022C\n\024uninterpreted_option\030\347\007 \003("
- "\0132$.google.protobuf.UninterpretedOption*"
- "\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022"
- ":\n\005ctype\030\001 \001(\0162#.google.protobuf.FieldOp"
- "tions.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006j"
- "stype\030\006 \001(\0162$.google.protobuf.FieldOptio"
- "ns.JSType:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005fals"
- "e\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001"
- "(\010:\005false\022C\n\024uninterpreted_option\030\347\007 \003(\013"
- "2$.google.protobuf.UninterpretedOption\"/"
- "\n\005CType\022\n\n\006STRING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_"
- "PIECE\020\002\"5\n\006JSType\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_S"
- "TRING\020\001\022\r\n\tJS_NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\""
- "^\n\014OneofOptions\022C\n\024uninterpreted_option\030"
+ "\0132\035.google.protobuf.FieldOptions\022\027\n\017prot"
+ "o3_optional\030\021 \001(\010\"\266\002\n\004Type\022\017\n\013TYPE_DOUBL"
+ "E\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTYPE_INT64\020\003\022\017\n\013T"
+ "YPE_UINT64\020\004\022\016\n\nTYPE_INT32\020\005\022\020\n\014TYPE_FIX"
+ "ED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022\r\n\tTYPE_BOOL\020\010\022"
+ "\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_GROUP\020\n\022\020\n\014TYPE"
+ "_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020\014\022\017\n\013TYPE_UINT3"
+ "2\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYPE_SFIXED32\020\017\022\021\n"
+ "\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_SINT32\020\021\022\017\n\013TYP"
+ "E_SINT64\020\022\"C\n\005Label\022\022\n\016LABEL_OPTIONAL\020\001\022"
+ "\022\n\016LABEL_REQUIRED\020\002\022\022\n\016LABEL_REPEATED\020\003\""
+ "T\n\024OneofDescriptorProto\022\014\n\004name\030\001 \001(\t\022.\n"
+ "\007options\030\002 \001(\0132\035.google.protobuf.OneofOp"
+ "tions\"\244\002\n\023EnumDescriptorProto\022\014\n\004name\030\001 "
+ "\001(\t\0228\n\005value\030\002 \003(\0132).google.protobuf.Enu"
+ "mValueDescriptorProto\022-\n\007options\030\003 \001(\0132\034"
+ ".google.protobuf.EnumOptions\022N\n\016reserved"
+ "_range\030\004 \003(\01326.google.protobuf.EnumDescr"
+ "iptorProto.EnumReservedRange\022\025\n\rreserved"
+ "_name\030\005 \003(\t\032/\n\021EnumReservedRange\022\r\n\005star"
+ "t\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\"l\n\030EnumValueDescrip"
+ "torProto\022\014\n\004name\030\001 \001(\t\022\016\n\006number\030\002 \001(\005\0222"
+ "\n\007options\030\003 \001(\0132!.google.protobuf.EnumVa"
+ "lueOptions\"\220\001\n\026ServiceDescriptorProto\022\014\n"
+ "\004name\030\001 \001(\t\0226\n\006method\030\002 \003(\0132&.google.pro"
+ "tobuf.MethodDescriptorProto\0220\n\007options\030\003"
+ " \001(\0132\037.google.protobuf.ServiceOptions\"\301\001"
+ "\n\025MethodDescriptorProto\022\014\n\004name\030\001 \001(\t\022\022\n"
+ "\ninput_type\030\002 \001(\t\022\023\n\013output_type\030\003 \001(\t\022/"
+ "\n\007options\030\004 \001(\0132\036.google.protobuf.Method"
+ "Options\022\037\n\020client_streaming\030\005 \001(\010:\005false"
+ "\022\037\n\020server_streaming\030\006 \001(\010:\005false\"\245\006\n\013Fi"
+ "leOptions\022\024\n\014java_package\030\001 \001(\t\022\034\n\024java_"
+ "outer_classname\030\010 \001(\t\022\"\n\023java_multiple_f"
+ "iles\030\n \001(\010:\005false\022)\n\035java_generate_equal"
+ "s_and_hash\030\024 \001(\010B\002\030\001\022%\n\026java_string_chec"
+ "k_utf8\030\033 \001(\010:\005false\022F\n\014optimize_for\030\t \001("
+ "\0162).google.protobuf.FileOptions.Optimize"
+ "Mode:\005SPEED\022\022\n\ngo_package\030\013 \001(\t\022\"\n\023cc_ge"
+ "neric_services\030\020 \001(\010:\005false\022$\n\025java_gene"
+ "ric_services\030\021 \001(\010:\005false\022\"\n\023py_generic_"
+ "services\030\022 \001(\010:\005false\022#\n\024php_generic_ser"
+ "vices\030* \001(\010:\005false\022\031\n\ndeprecated\030\027 \001(\010:\005"
+ "false\022\036\n\020cc_enable_arenas\030\037 \001(\010:\004true\022\031\n"
+ "\021objc_class_prefix\030$ \001(\t\022\030\n\020csharp_names"
+ "pace\030% \001(\t\022\024\n\014swift_prefix\030\' \001(\t\022\030\n\020php_"
+ "class_prefix\030( \001(\t\022\025\n\rphp_namespace\030) \001("
+ "\t\022\036\n\026php_metadata_namespace\030, \001(\t\022\024\n\014rub"
+ "y_package\030- \001(\t\022C\n\024uninterpreted_option\030"
"\347\007 \003(\0132$.google.protobuf.UninterpretedOp"
- "tion*\t\010\350\007\020\200\200\200\200\002\"\223\001\n\013EnumOptions\022\023\n\013allow"
- "_alias\030\002 \001(\010\022\031\n\ndeprecated\030\003 \001(\010:\005false\022"
+ "tion\":\n\014OptimizeMode\022\t\n\005SPEED\020\001\022\r\n\tCODE_"
+ "SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003*\t\010\350\007\020\200\200\200\200\002J\004\010&\020"
+ "\'\"\362\001\n\016MessageOptions\022&\n\027message_set_wire"
+ "_format\030\001 \001(\010:\005false\022.\n\037no_standard_desc"
+ "riptor_accessor\030\002 \001(\010:\005false\022\031\n\ndeprecat"
+ "ed\030\003 \001(\010:\005false\022\021\n\tmap_entry\030\007 \001(\010\022C\n\024un"
+ "interpreted_option\030\347\007 \003(\0132$.google.proto"
+ "buf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\t"
+ "J\004\010\t\020\n\"\236\003\n\014FieldOptions\022:\n\005ctype\030\001 \001(\0162#"
+ ".google.protobuf.FieldOptions.CType:\006STR"
+ "ING\022\016\n\006packed\030\002 \001(\010\022\?\n\006jstype\030\006 \001(\0162$.go"
+ "ogle.protobuf.FieldOptions.JSType:\tJS_NO"
+ "RMAL\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\024uni"
+ "nterpreted_option\030\347\007 \003(\0132$.google.protob"
+ "uf.UninterpretedOption\"/\n\005CType\022\n\n\006STRIN"
+ "G\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_PIECE\020\002\"5\n\006JSTyp"
+ "e\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_STRING\020\001\022\r\n\tJS_NU"
+ "MBER\020\002*\t\010\350\007\020\200\200\200\200\002J\004\010\004\020\005\"^\n\014OneofOptions\022"
"C\n\024uninterpreted_option\030\347\007 \003(\0132$.google."
- "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J"
- "\004\010\005\020\006\"}\n\020EnumValueOptions\022\031\n\ndeprecated\030"
- "\001 \001(\010:\005false\022C\n\024uninterpreted_option\030\347\007 "
- "\003(\0132$.google.protobuf.UninterpretedOptio"
- "n*\t\010\350\007\020\200\200\200\200\002\"{\n\016ServiceOptions\022\031\n\ndeprec"
- "ated\030! \001(\010:\005false\022C\n\024uninterpreted_optio"
- "n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted"
- "Option*\t\010\350\007\020\200\200\200\200\002\"\255\002\n\rMethodOptions\022\031\n\nd"
- "eprecated\030! \001(\010:\005false\022_\n\021idempotency_le"
- "vel\030\" \001(\0162/.google.protobuf.MethodOption"
- "s.IdempotencyLevel:\023IDEMPOTENCY_UNKNOWN\022"
- "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google."
- "protobuf.UninterpretedOption\"P\n\020Idempote"
- "ncyLevel\022\027\n\023IDEMPOTENCY_UNKNOWN\020\000\022\023\n\017NO_"
- "SIDE_EFFECTS\020\001\022\016\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200"
- "\002\"\236\002\n\023UninterpretedOption\022;\n\004name\030\002 \003(\0132"
- "-.google.protobuf.UninterpretedOption.Na"
- "mePart\022\030\n\020identifier_value\030\003 \001(\t\022\032\n\022posi"
- "tive_int_value\030\004 \001(\004\022\032\n\022negative_int_val"
- "ue\030\005 \001(\003\022\024\n\014double_value\030\006 \001(\001\022\024\n\014string"
- "_value\030\007 \001(\014\022\027\n\017aggregate_value\030\010 \001(\t\0323\n"
- "\010NamePart\022\021\n\tname_part\030\001 \002(\t\022\024\n\014is_exten"
- "sion\030\002 \002(\010\"\325\001\n\016SourceCodeInfo\022:\n\010locatio"
- "n\030\001 \003(\0132(.google.protobuf.SourceCodeInfo"
- ".Location\032\206\001\n\010Location\022\020\n\004path\030\001 \003(\005B\002\020\001"
- "\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020leading_comments\030\003"
- " \001(\t\022\031\n\021trailing_comments\030\004 \001(\t\022!\n\031leadi"
- "ng_detached_comments\030\006 \003(\t\"\247\001\n\021Generated"
- "CodeInfo\022A\n\nannotation\030\001 \003(\0132-.google.pr"
- "otobuf.GeneratedCodeInfo.Annotation\032O\n\nA"
- "nnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\023\n\013source_fi"
- "le\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n"
- "\023com.google.protobufB\020DescriptorProtosH\001"
- "Z>github.com/golang/protobuf/protoc-gen-"
- "go/descriptor;descriptor\370\001\001\242\002\003GPB\252\002\032Goog"
- "le.Protobuf.Reflection"
+ "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\""
+ "\223\001\n\013EnumOptions\022\023\n\013allow_alias\030\002 \001(\010\022\031\n\n"
+ "deprecated\030\003 \001(\010:\005false\022C\n\024uninterpreted"
+ "_option\030\347\007 \003(\0132$.google.protobuf.Uninter"
+ "pretedOption*\t\010\350\007\020\200\200\200\200\002J\004\010\005\020\006\"}\n\020EnumVal"
+ "ueOptions\022\031\n\ndeprecated\030\001 \001(\010:\005false\022C\n\024"
+ "uninterpreted_option\030\347\007 \003(\0132$.google.pro"
+ "tobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"{\n\016"
+ "ServiceOptions\022\031\n\ndeprecated\030! \001(\010:\005fals"
+ "e\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.googl"
+ "e.protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200"
+ "\002\"\255\002\n\rMethodOptions\022\031\n\ndeprecated\030! \001(\010:"
+ "\005false\022_\n\021idempotency_level\030\" \001(\0162/.goog"
+ "le.protobuf.MethodOptions.IdempotencyLev"
+ "el:\023IDEMPOTENCY_UNKNOWN\022C\n\024uninterpreted"
+ "_option\030\347\007 \003(\0132$.google.protobuf.Uninter"
+ "pretedOption\"P\n\020IdempotencyLevel\022\027\n\023IDEM"
+ "POTENCY_UNKNOWN\020\000\022\023\n\017NO_SIDE_EFFECTS\020\001\022\016"
+ "\n\nIDEMPOTENT\020\002*\t\010\350\007\020\200\200\200\200\002\"\236\002\n\023Uninterpre"
+ "tedOption\022;\n\004name\030\002 \003(\0132-.google.protobu"
+ "f.UninterpretedOption.NamePart\022\030\n\020identi"
+ "fier_value\030\003 \001(\t\022\032\n\022positive_int_value\030\004"
+ " \001(\004\022\032\n\022negative_int_value\030\005 \001(\003\022\024\n\014doub"
+ "le_value\030\006 \001(\001\022\024\n\014string_value\030\007 \001(\014\022\027\n\017"
+ "aggregate_value\030\010 \001(\t\0323\n\010NamePart\022\021\n\tnam"
+ "e_part\030\001 \002(\t\022\024\n\014is_extension\030\002 \002(\010\"\325\001\n\016S"
+ "ourceCodeInfo\022:\n\010location\030\001 \003(\0132(.google"
+ ".protobuf.SourceCodeInfo.Location\032\206\001\n\010Lo"
+ "cation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\020\n\004span\030\002 \003(\005B\002"
+ "\020\001\022\030\n\020leading_comments\030\003 \001(\t\022\031\n\021trailing"
+ "_comments\030\004 \001(\t\022!\n\031leading_detached_comm"
+ "ents\030\006 \003(\t\"\247\001\n\021GeneratedCodeInfo\022A\n\nanno"
+ "tation\030\001 \003(\0132-.google.protobuf.Generated"
+ "CodeInfo.Annotation\032O\n\nAnnotation\022\020\n\004pat"
+ "h\030\001 \003(\005B\002\020\001\022\023\n\013source_file\030\002 \001(\t\022\r\n\005begi"
+ "n\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n\023com.google.prot"
+ "obufB\020DescriptorProtosH\001Z>github.com/gol"
+ "ang/protobuf/protoc-gen-go/descriptor;de"
+ "scriptor\370\001\001\242\002\003GPB\252\002\032Google.Protobuf.Refl"
+ "ection"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_deps[1] = {
};
@@ -1196,16 +1194,15 @@
&scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fdescriptor_2eproto = {
- &descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fdescriptor_2eproto, "google/protobuf/descriptor.proto", 6022,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fdescriptor_2eproto, "google/protobuf/descriptor.proto", 6046,
&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_once, descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_sccs, descriptor_table_google_2fprotobuf_2fdescriptor_2eproto_deps, 27, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto, 27, file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto, file_level_service_descriptors_google_2fprotobuf_2fdescriptor_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fdescriptor_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fdescriptor_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FieldDescriptorProto_Type_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto);
@@ -1382,17 +1379,10 @@
}
class FileDescriptorSet::_Internal {
public:
- using HasBits = decltype(std::declval<FileDescriptorSet>()._has_bits_);
};
-FileDescriptorSet::FileDescriptorSet()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet)
-}
FileDescriptorSet::FileDescriptorSet(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
file_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -1400,10 +1390,8 @@
}
FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
- _has_bits_(from._has_bits_),
file_(from.file_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorSet)
}
@@ -1414,10 +1402,11 @@
FileDescriptorSet::~FileDescriptorSet() {
// @@protoc_insertion_point(destructor:google.protobuf.FileDescriptorSet)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void FileDescriptorSet::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void FileDescriptorSet::ArenaDtor(void* object) {
@@ -1442,13 +1431,12 @@
(void) cached_has_bits;
file_.Clear();
- _has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* FileDescriptorSet::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1472,7 +1460,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1502,7 +1492,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileDescriptorSet)
return target;
@@ -1550,7 +1540,7 @@
void FileDescriptorSet::MergeFrom(const FileDescriptorSet& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorSet)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1578,8 +1568,7 @@
void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_has_bits_[0], other->_has_bits_[0]);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
file_.InternalSwap(&other->file_);
}
@@ -1626,40 +1615,8 @@
FileDescriptorProto::_Internal::source_code_info(const FileDescriptorProto* msg) {
return *msg->source_code_info_;
}
-void FileDescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::FileOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000008u;
- } else {
- _has_bits_[0] &= ~0x00000008u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.options)
-}
-void FileDescriptorProto::unsafe_arena_set_allocated_source_code_info(
- PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info) {
- if (GetArenaNoVirtual() == nullptr) {
- delete source_code_info_;
- }
- source_code_info_ = source_code_info;
- if (source_code_info) {
- _has_bits_[0] |= 0x00000010u;
- } else {
- _has_bits_[0] &= ~0x00000010u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.source_code_info)
-}
-FileDescriptorProto::FileDescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto)
-}
FileDescriptorProto::FileDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
dependency_(arena),
message_type_(arena),
enum_type_(arena),
@@ -1673,7 +1630,6 @@
}
FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
dependency_(from.dependency_),
message_type_(from.message_type_),
@@ -1682,21 +1638,21 @@
extension_(from.extension_),
public_dependency_(from.public_dependency_),
weak_dependency_(from.weak_dependency_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_package()) {
package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_package(),
- GetArenaNoVirtual());
+ GetArena());
}
syntax_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_syntax()) {
syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_syntax(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::FileOptions(*from.options_);
@@ -1724,10 +1680,11 @@
FileDescriptorProto::~FileDescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.FileDescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void FileDescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
syntax_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
@@ -1784,13 +1741,13 @@
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* FileDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1902,7 +1859,7 @@
ptr -= 1;
do {
ptr += 1;
- _internal_add_public_dependency(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
+ _internal_add_public_dependency(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<80>(ptr));
@@ -1917,7 +1874,7 @@
ptr -= 1;
do {
ptr += 1;
- _internal_add_weak_dependency(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
+ _internal_add_weak_dependency(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<88>(ptr));
@@ -1943,7 +1900,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -2067,7 +2026,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileDescriptorProto)
return target;
@@ -2200,7 +2159,7 @@
void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -2258,7 +2217,7 @@
void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
dependency_.InternalSwap(&other->dependency_);
message_type_.InternalSwap(&other->message_type_);
@@ -2267,14 +2226,15 @@
extension_.InternalSwap(&other->extension_);
public_dependency_.InternalSwap(&other->public_dependency_);
weak_dependency_.InternalSwap(&other->weak_dependency_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- package_.Swap(&other->package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- syntax_.Swap(&other->syntax_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(options_, other->options_);
- swap(source_code_info_, other->source_code_info_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ package_.Swap(&other->package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ syntax_.Swap(&other->syntax_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(FileDescriptorProto, source_code_info_)
+ + sizeof(FileDescriptorProto::source_code_info_)
+ - PROTOBUF_FIELD_OFFSET(FileDescriptorProto, options_)>(
+ reinterpret_cast<char*>(&options_),
+ reinterpret_cast<char*>(&other->options_));
}
::PROTOBUF_NAMESPACE_ID::Metadata FileDescriptorProto::GetMetadata() const {
@@ -2307,36 +2267,16 @@
DescriptorProto_ExtensionRange::_Internal::options(const DescriptorProto_ExtensionRange* msg) {
return *msg->options_;
}
-void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000001u;
- } else {
- _has_bits_[0] &= ~0x00000001u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options)
-}
-DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ExtensionRange)
-}
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ExtensionRange)
}
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions(*from.options_);
} else {
@@ -2358,10 +2298,11 @@
DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() {
// @@protoc_insertion_point(destructor:google.protobuf.DescriptorProto.ExtensionRange)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void DescriptorProto_ExtensionRange::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
if (this != internal_default_instance()) delete options_;
}
@@ -2397,13 +2338,13 @@
reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* DescriptorProto_ExtensionRange::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -2413,7 +2354,7 @@
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_start(&has_bits);
- start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -2421,7 +2362,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_end(&has_bits);
- end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -2438,7 +2379,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -2482,7 +2425,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto.ExtensionRange)
return target;
@@ -2547,7 +2490,7 @@
void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ExtensionRange)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -2589,11 +2532,14 @@
void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- swap(options_, other->options_);
- swap(start_, other->start_);
- swap(end_, other->end_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(DescriptorProto_ExtensionRange, end_)
+ + sizeof(DescriptorProto_ExtensionRange::end_)
+ - PROTOBUF_FIELD_OFFSET(DescriptorProto_ExtensionRange, options_)>(
+ reinterpret_cast<char*>(&options_),
+ reinterpret_cast<char*>(&other->options_));
}
::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto_ExtensionRange::GetMetadata() const {
@@ -2616,23 +2562,16 @@
}
};
-DescriptorProto_ReservedRange::DescriptorProto_ReservedRange()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ReservedRange)
-}
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ReservedRange)
}
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&start_, &from.start_,
static_cast<size_t>(reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&start_)) + sizeof(end_));
@@ -2648,10 +2587,11 @@
DescriptorProto_ReservedRange::~DescriptorProto_ReservedRange() {
// @@protoc_insertion_point(destructor:google.protobuf.DescriptorProto.ReservedRange)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void DescriptorProto_ReservedRange::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void DescriptorProto_ReservedRange::ArenaDtor(void* object) {
@@ -2682,13 +2622,13 @@
reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* DescriptorProto_ReservedRange::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -2698,7 +2638,7 @@
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_start(&has_bits);
- start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -2706,7 +2646,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_end(&has_bits);
- end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -2716,7 +2656,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -2752,7 +2694,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto.ReservedRange)
return target;
@@ -2810,7 +2752,7 @@
void DescriptorProto_ReservedRange::MergeFrom(const DescriptorProto_ReservedRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ReservedRange)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -2846,10 +2788,14 @@
void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- swap(start_, other->start_);
- swap(end_, other->end_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(DescriptorProto_ReservedRange, end_)
+ + sizeof(DescriptorProto_ReservedRange::end_)
+ - PROTOBUF_FIELD_OFFSET(DescriptorProto_ReservedRange, start_)>(
+ reinterpret_cast<char*>(&start_),
+ reinterpret_cast<char*>(&other->start_));
}
::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto_ReservedRange::GetMetadata() const {
@@ -2879,27 +2825,8 @@
DescriptorProto::_Internal::options(const DescriptorProto* msg) {
return *msg->options_;
}
-void DescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::MessageOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000002u;
- } else {
- _has_bits_[0] &= ~0x00000002u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.options)
-}
-DescriptorProto::DescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto)
-}
DescriptorProto::DescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
field_(arena),
nested_type_(arena),
enum_type_(arena),
@@ -2914,7 +2841,6 @@
}
DescriptorProto::DescriptorProto(const DescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
field_(from.field_),
nested_type_(from.nested_type_),
@@ -2924,11 +2850,11 @@
oneof_decl_(from.oneof_decl_),
reserved_range_(from.reserved_range_),
reserved_name_(from.reserved_name_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::MessageOptions(*from.options_);
@@ -2947,10 +2873,11 @@
DescriptorProto::~DescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.DescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void DescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete options_;
}
@@ -2995,13 +2922,13 @@
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* DescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -3131,7 +3058,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -3239,7 +3168,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DescriptorProto)
return target;
@@ -3354,7 +3283,7 @@
void DescriptorProto::MergeFrom(const DescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -3406,7 +3335,7 @@
void DescriptorProto::InternalSwap(DescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
field_.InternalSwap(&other->field_);
nested_type_.InternalSwap(&other->nested_type_);
@@ -3416,8 +3345,7 @@
oneof_decl_.InternalSwap(&other->oneof_decl_);
reserved_range_.InternalSwap(&other->reserved_range_);
reserved_name_.InternalSwap(&other->reserved_name_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(options_, other->options_);
}
@@ -3432,18 +3360,11 @@
}
class ExtensionRangeOptions::_Internal {
public:
- using HasBits = decltype(std::declval<ExtensionRangeOptions>()._has_bits_);
};
-ExtensionRangeOptions::ExtensionRangeOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.ExtensionRangeOptions)
-}
ExtensionRangeOptions::ExtensionRangeOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -3451,10 +3372,8 @@
}
ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
- _has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.ExtensionRangeOptions)
}
@@ -3466,10 +3385,11 @@
ExtensionRangeOptions::~ExtensionRangeOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.ExtensionRangeOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void ExtensionRangeOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void ExtensionRangeOptions::ArenaDtor(void* object) {
@@ -3495,13 +3415,12 @@
_extensions_.Clear();
uninterpreted_option_.Clear();
- _has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* ExtensionRangeOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -3531,7 +3450,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -3565,7 +3486,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ExtensionRangeOptions)
return target;
@@ -3616,7 +3537,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ExtensionRangeOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -3649,8 +3570,7 @@
void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_has_bits_[0], other->_has_bits_[0]);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
}
@@ -3675,10 +3595,10 @@
(*has_bits)[0] |= 64u;
}
static void set_has_label(HasBits* has_bits) {
- (*has_bits)[0] |= 256u;
+ (*has_bits)[0] |= 512u;
}
static void set_has_type(HasBits* has_bits) {
- (*has_bits)[0] |= 512u;
+ (*has_bits)[0] |= 1024u;
}
static void set_has_type_name(HasBits* has_bits) {
(*has_bits)[0] |= 4u;
@@ -3699,66 +3619,49 @@
static void set_has_options(HasBits* has_bits) {
(*has_bits)[0] |= 32u;
}
+ static void set_has_proto3_optional(HasBits* has_bits) {
+ (*has_bits)[0] |= 256u;
+ }
};
const PROTOBUF_NAMESPACE_ID::FieldOptions&
FieldDescriptorProto::_Internal::options(const FieldDescriptorProto* msg) {
return *msg->options_;
}
-void FieldDescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::FieldOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000020u;
- } else {
- _has_bits_[0] &= ~0x00000020u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.options)
-}
-FieldDescriptorProto::FieldDescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.FieldDescriptorProto)
-}
FieldDescriptorProto::FieldDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto)
}
FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
extendee_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_extendee()) {
extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_extendee(),
- GetArenaNoVirtual());
+ GetArena());
}
type_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_type_name()) {
type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_type_name(),
- GetArenaNoVirtual());
+ GetArena());
}
default_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_default_value()) {
default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_default_value(),
- GetArenaNoVirtual());
+ GetArena());
}
json_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_json_name()) {
json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_json_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::FieldOptions(*from.options_);
@@ -3779,8 +3682,8 @@
default_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
json_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(&options_, 0, static_cast<size_t>(
- reinterpret_cast<char*>(&oneof_index_) -
- reinterpret_cast<char*>(&options_)) + sizeof(oneof_index_));
+ reinterpret_cast<char*>(&proto3_optional_) -
+ reinterpret_cast<char*>(&options_)) + sizeof(proto3_optional_));
label_ = 1;
type_ = 1;
}
@@ -3788,10 +3691,11 @@
FieldDescriptorProto::~FieldDescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.FieldDescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void FieldDescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
extendee_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
type_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
@@ -3848,18 +3752,19 @@
reinterpret_cast<char*>(&oneof_index_) -
reinterpret_cast<char*>(&number_)) + sizeof(oneof_index_));
}
- if (cached_has_bits & 0x00000300u) {
+ if (cached_has_bits & 0x00000700u) {
+ proto3_optional_ = false;
label_ = 1;
type_ = 1;
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* FieldDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -3891,14 +3796,14 @@
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_number(&has_bits);
- number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label_IsValid(val))) {
_internal_set_label(static_cast<PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label>(val));
@@ -3910,7 +3815,7 @@
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type_IsValid(val))) {
_internal_set_type(static_cast<PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type>(val));
@@ -3952,7 +3857,7 @@
case 9:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72)) {
_Internal::set_has_oneof_index(&has_bits);
- oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -3967,13 +3872,23 @@
CHK_(ptr);
} else goto handle_unusual;
continue;
+ // optional bool proto3_optional = 17;
+ case 17:
+ if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 136)) {
+ _Internal::set_has_proto3_optional(&has_bits);
+ proto3_optional_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
+ CHK_(ptr);
+ } else goto handle_unusual;
+ continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -4022,14 +3937,14 @@
}
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
- if (cached_has_bits & 0x00000100u) {
+ if (cached_has_bits & 0x00000200u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
4, this->_internal_label(), target);
}
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
- if (cached_has_bits & 0x00000200u) {
+ if (cached_has_bits & 0x00000400u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
5, this->_internal_type(), target);
@@ -4079,9 +3994,15 @@
10, this->_internal_json_name(), target);
}
+ // optional bool proto3_optional = 17;
+ if (cached_has_bits & 0x00000100u) {
+ target = stream->EnsureSpace(target);
+ target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(17, this->_internal_proto3_optional(), target);
+ }
+
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldDescriptorProto)
return target;
@@ -4154,15 +4075,20 @@
}
}
- if (cached_has_bits & 0x00000300u) {
- // optional .google.protobuf.FieldDescriptorProto.Label label = 4;
+ if (cached_has_bits & 0x00000700u) {
+ // optional bool proto3_optional = 17;
if (cached_has_bits & 0x00000100u) {
+ total_size += 2 + 1;
+ }
+
+ // optional .google.protobuf.FieldDescriptorProto.Label label = 4;
+ if (cached_has_bits & 0x00000200u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_label());
}
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
- if (cached_has_bits & 0x00000200u) {
+ if (cached_has_bits & 0x00000400u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_type());
}
@@ -4195,7 +4121,7 @@
void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -4227,11 +4153,14 @@
}
_has_bits_[0] |= cached_has_bits;
}
- if (cached_has_bits & 0x00000300u) {
+ if (cached_has_bits & 0x00000700u) {
if (cached_has_bits & 0x00000100u) {
- label_ = from.label_;
+ proto3_optional_ = from.proto3_optional_;
}
if (cached_has_bits & 0x00000200u) {
+ label_ = from.label_;
+ }
+ if (cached_has_bits & 0x00000400u) {
type_ = from.type_;
}
_has_bits_[0] |= cached_has_bits;
@@ -4261,21 +4190,19 @@
void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- extendee_.Swap(&other->extendee_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- type_name_.Swap(&other->type_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- default_value_.Swap(&other->default_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- json_name_.Swap(&other->json_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(options_, other->options_);
- swap(number_, other->number_);
- swap(oneof_index_, other->oneof_index_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ extendee_.Swap(&other->extendee_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ type_name_.Swap(&other->type_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ default_value_.Swap(&other->default_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ json_name_.Swap(&other->json_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(FieldDescriptorProto, proto3_optional_)
+ + sizeof(FieldDescriptorProto::proto3_optional_)
+ - PROTOBUF_FIELD_OFFSET(FieldDescriptorProto, options_)>(
+ reinterpret_cast<char*>(&options_),
+ reinterpret_cast<char*>(&other->options_));
swap(label_, other->label_);
swap(type_, other->type_);
}
@@ -4307,40 +4234,20 @@
OneofDescriptorProto::_Internal::options(const OneofDescriptorProto* msg) {
return *msg->options_;
}
-void OneofDescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::OneofOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000002u;
- } else {
- _has_bits_[0] &= ~0x00000002u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.options)
-}
-OneofDescriptorProto::OneofDescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.OneofDescriptorProto)
-}
OneofDescriptorProto::OneofDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto)
}
OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::OneofOptions(*from.options_);
@@ -4359,10 +4266,11 @@
OneofDescriptorProto::~OneofDescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.OneofDescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void OneofDescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete options_;
}
@@ -4399,13 +4307,13 @@
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* OneofDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -4435,7 +4343,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -4477,7 +4387,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.OneofDescriptorProto)
return target;
@@ -4535,7 +4445,7 @@
void OneofDescriptorProto::MergeFrom(const OneofDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.OneofDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -4573,10 +4483,9 @@
void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(options_, other->options_);
}
@@ -4600,23 +4509,16 @@
}
};
-EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
-}
EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
}
EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&start_, &from.start_,
static_cast<size_t>(reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&start_)) + sizeof(end_));
@@ -4632,10 +4534,11 @@
EnumDescriptorProto_EnumReservedRange::~EnumDescriptorProto_EnumReservedRange() {
// @@protoc_insertion_point(destructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void EnumDescriptorProto_EnumReservedRange::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void EnumDescriptorProto_EnumReservedRange::ArenaDtor(void* object) {
@@ -4666,13 +4569,13 @@
reinterpret_cast<char*>(&start_)) + sizeof(end_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* EnumDescriptorProto_EnumReservedRange::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -4682,7 +4585,7 @@
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_start(&has_bits);
- start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -4690,7 +4593,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_end(&has_bits);
- end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -4700,7 +4603,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -4736,7 +4641,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumDescriptorProto.EnumReservedRange)
return target;
@@ -4794,7 +4699,7 @@
void EnumDescriptorProto_EnumReservedRange::MergeFrom(const EnumDescriptorProto_EnumReservedRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -4830,10 +4735,14 @@
void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_EnumReservedRange* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- swap(start_, other->start_);
- swap(end_, other->end_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(EnumDescriptorProto_EnumReservedRange, end_)
+ + sizeof(EnumDescriptorProto_EnumReservedRange::end_)
+ - PROTOBUF_FIELD_OFFSET(EnumDescriptorProto_EnumReservedRange, start_)>(
+ reinterpret_cast<char*>(&start_),
+ reinterpret_cast<char*>(&other->start_));
}
::PROTOBUF_NAMESPACE_ID::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const {
@@ -4863,27 +4772,8 @@
EnumDescriptorProto::_Internal::options(const EnumDescriptorProto* msg) {
return *msg->options_;
}
-void EnumDescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::EnumOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000002u;
- } else {
- _has_bits_[0] &= ~0x00000002u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.options)
-}
-EnumDescriptorProto::EnumDescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto)
-}
EnumDescriptorProto::EnumDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
value_(arena),
reserved_range_(arena),
reserved_name_(arena) {
@@ -4893,16 +4783,15 @@
}
EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
value_(from.value_),
reserved_range_(from.reserved_range_),
reserved_name_(from.reserved_name_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::EnumOptions(*from.options_);
@@ -4921,10 +4810,11 @@
EnumDescriptorProto::~EnumDescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.EnumDescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void EnumDescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete options_;
}
@@ -4964,13 +4854,13 @@
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* EnumDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -5040,7 +4930,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -5108,7 +5000,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumDescriptorProto)
return target;
@@ -5188,7 +5080,7 @@
void EnumDescriptorProto::MergeFrom(const EnumDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -5230,13 +5122,12 @@
void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
value_.InternalSwap(&other->value_);
reserved_range_.InternalSwap(&other->reserved_range_);
reserved_name_.InternalSwap(&other->reserved_name_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(options_, other->options_);
}
@@ -5270,40 +5161,20 @@
EnumValueDescriptorProto::_Internal::options(const EnumValueDescriptorProto* msg) {
return *msg->options_;
}
-void EnumValueDescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::EnumValueOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000002u;
- } else {
- _has_bits_[0] &= ~0x00000002u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
-}
-EnumValueDescriptorProto::EnumValueDescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.EnumValueDescriptorProto)
-}
EnumValueDescriptorProto::EnumValueDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto)
}
EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::EnumValueOptions(*from.options_);
@@ -5325,10 +5196,11 @@
EnumValueDescriptorProto::~EnumValueDescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.EnumValueDescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void EnumValueDescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete options_;
}
@@ -5366,13 +5238,13 @@
}
number_ = 0;
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* EnumValueDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -5393,7 +5265,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_number(&has_bits);
- number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -5410,7 +5282,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -5458,7 +5332,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValueDescriptorProto)
return target;
@@ -5523,7 +5397,7 @@
void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValueDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -5565,12 +5439,15 @@
void EnumValueDescriptorProto::InternalSwap(EnumValueDescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(options_, other->options_);
- swap(number_, other->number_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(EnumValueDescriptorProto, number_)
+ + sizeof(EnumValueDescriptorProto::number_)
+ - PROTOBUF_FIELD_OFFSET(EnumValueDescriptorProto, options_)>(
+ reinterpret_cast<char*>(&options_),
+ reinterpret_cast<char*>(&other->options_));
}
::PROTOBUF_NAMESPACE_ID::Metadata EnumValueDescriptorProto::GetMetadata() const {
@@ -5600,27 +5477,8 @@
ServiceDescriptorProto::_Internal::options(const ServiceDescriptorProto* msg) {
return *msg->options_;
}
-void ServiceDescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::ServiceOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000002u;
- } else {
- _has_bits_[0] &= ~0x00000002u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.options)
-}
-ServiceDescriptorProto::ServiceDescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto)
-}
ServiceDescriptorProto::ServiceDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
method_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -5628,14 +5486,13 @@
}
ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
method_(from.method_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::ServiceOptions(*from.options_);
@@ -5654,10 +5511,11 @@
ServiceDescriptorProto::~ServiceDescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.ServiceDescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void ServiceDescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete options_;
}
@@ -5695,13 +5553,13 @@
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* ServiceDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -5743,7 +5601,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -5793,7 +5653,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ServiceDescriptorProto)
return target;
@@ -5858,7 +5718,7 @@
void ServiceDescriptorProto::MergeFrom(const ServiceDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ServiceDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -5898,11 +5758,10 @@
void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
method_.InternalSwap(&other->method_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(options_, other->options_);
}
@@ -5945,50 +5804,30 @@
MethodDescriptorProto::_Internal::options(const MethodDescriptorProto* msg) {
return *msg->options_;
}
-void MethodDescriptorProto::unsafe_arena_set_allocated_options(
- PROTOBUF_NAMESPACE_ID::MethodOptions* options) {
- if (GetArenaNoVirtual() == nullptr) {
- delete options_;
- }
- options_ = options;
- if (options) {
- _has_bits_[0] |= 0x00000008u;
- } else {
- _has_bits_[0] &= ~0x00000008u;
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.options)
-}
-MethodDescriptorProto::MethodDescriptorProto()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.MethodDescriptorProto)
-}
MethodDescriptorProto::MethodDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto)
}
MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
input_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_input_type()) {
input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_input_type(),
- GetArenaNoVirtual());
+ GetArena());
}
output_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_output_type()) {
output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_output_type(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_options()) {
options_ = new PROTOBUF_NAMESPACE_ID::MethodOptions(*from.options_);
@@ -6014,10 +5853,11 @@
MethodDescriptorProto::~MethodDescriptorProto() {
// @@protoc_insertion_point(destructor:google.protobuf.MethodDescriptorProto)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void MethodDescriptorProto::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
input_type_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
output_type_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
@@ -6065,13 +5905,13 @@
reinterpret_cast<char*>(&server_streaming_) -
reinterpret_cast<char*>(&client_streaming_)) + sizeof(server_streaming_));
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* MethodDescriptorProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -6121,7 +5961,7 @@
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
_Internal::set_has_client_streaming(&has_bits);
- client_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ client_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6129,7 +5969,7 @@
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) {
_Internal::set_has_server_streaming(&has_bits);
- server_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ server_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6139,7 +5979,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -6213,7 +6055,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MethodDescriptorProto)
return target;
@@ -6295,7 +6137,7 @@
void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MethodDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -6346,17 +6188,17 @@
void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- input_type_.Swap(&other->input_type_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- output_type_.Swap(&other->output_type_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(options_, other->options_);
- swap(client_streaming_, other->client_streaming_);
- swap(server_streaming_, other->server_streaming_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ input_type_.Swap(&other->input_type_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ output_type_.Swap(&other->output_type_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(MethodDescriptorProto, server_streaming_)
+ + sizeof(MethodDescriptorProto::server_streaming_)
+ - PROTOBUF_FIELD_OFFSET(MethodDescriptorProto, options_)>(
+ reinterpret_cast<char*>(&options_),
+ reinterpret_cast<char*>(&other->options_));
}
::PROTOBUF_NAMESPACE_ID::Metadata MethodDescriptorProto::GetMetadata() const {
@@ -6387,7 +6229,7 @@
(*has_bits)[0] |= 4096u;
}
static void set_has_optimize_for(HasBits* has_bits) {
- (*has_bits)[0] |= 524288u;
+ (*has_bits)[0] |= 262144u;
}
static void set_has_go_package(HasBits* has_bits) {
(*has_bits)[0] |= 4u;
@@ -6408,7 +6250,7 @@
(*has_bits)[0] |= 131072u;
}
static void set_has_cc_enable_arenas(HasBits* has_bits) {
- (*has_bits)[0] |= 262144u;
+ (*has_bits)[0] |= 524288u;
}
static void set_has_objc_class_prefix(HasBits* has_bits) {
(*has_bits)[0] |= 8u;
@@ -6433,15 +6275,9 @@
}
};
-FileOptions::FileOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.FileOptions)
-}
FileOptions::FileOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -6449,64 +6285,63 @@
}
FileOptions::FileOptions(const FileOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
java_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_java_package()) {
java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_java_package(),
- GetArenaNoVirtual());
+ GetArena());
}
java_outer_classname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_java_outer_classname()) {
java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_java_outer_classname(),
- GetArenaNoVirtual());
+ GetArena());
}
go_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_go_package()) {
go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_go_package(),
- GetArenaNoVirtual());
+ GetArena());
}
objc_class_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_objc_class_prefix()) {
objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_objc_class_prefix(),
- GetArenaNoVirtual());
+ GetArena());
}
csharp_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_csharp_namespace()) {
csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_csharp_namespace(),
- GetArenaNoVirtual());
+ GetArena());
}
swift_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_swift_prefix()) {
swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_swift_prefix(),
- GetArenaNoVirtual());
+ GetArena());
}
php_class_prefix_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_php_class_prefix()) {
php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_php_class_prefix(),
- GetArenaNoVirtual());
+ GetArena());
}
php_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_php_namespace()) {
php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_php_namespace(),
- GetArenaNoVirtual());
+ GetArena());
}
php_metadata_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_php_metadata_namespace()) {
php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_php_metadata_namespace(),
- GetArenaNoVirtual());
+ GetArena());
}
ruby_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_ruby_package()) {
ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_ruby_package(),
- GetArenaNoVirtual());
+ GetArena());
}
::memcpy(&java_multiple_files_, &from.java_multiple_files_,
- static_cast<size_t>(reinterpret_cast<char*>(&optimize_for_) -
- reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(optimize_for_));
+ static_cast<size_t>(reinterpret_cast<char*>(&cc_enable_arenas_) -
+ reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(cc_enable_arenas_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileOptions)
}
@@ -6523,18 +6358,20 @@
php_metadata_namespace_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
ruby_package_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(&java_multiple_files_, 0, static_cast<size_t>(
- reinterpret_cast<char*>(&cc_enable_arenas_) -
- reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(cc_enable_arenas_));
+ reinterpret_cast<char*>(&deprecated_) -
+ reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(deprecated_));
optimize_for_ = 1;
+ cc_enable_arenas_ = true;
}
FileOptions::~FileOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.FileOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void FileOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
java_package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
java_outer_classname_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
go_package_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
@@ -6612,18 +6449,19 @@
}
if (cached_has_bits & 0x000f0000u) {
::memset(&php_generic_services_, 0, static_cast<size_t>(
- reinterpret_cast<char*>(&cc_enable_arenas_) -
- reinterpret_cast<char*>(&php_generic_services_)) + sizeof(cc_enable_arenas_));
+ reinterpret_cast<char*>(&deprecated_) -
+ reinterpret_cast<char*>(&php_generic_services_)) + sizeof(deprecated_));
optimize_for_ = 1;
+ cc_enable_arenas_ = true;
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* FileOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -6654,7 +6492,7 @@
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
case 9:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode_IsValid(val))) {
_internal_set_optimize_for(static_cast<PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode>(val));
@@ -6667,7 +6505,7 @@
case 10:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) {
_Internal::set_has_java_multiple_files(&has_bits);
- java_multiple_files_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ java_multiple_files_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6686,7 +6524,7 @@
case 16:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 128)) {
_Internal::set_has_cc_generic_services(&has_bits);
- cc_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ cc_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6694,7 +6532,7 @@
case 17:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 136)) {
_Internal::set_has_java_generic_services(&has_bits);
- java_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ java_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6702,7 +6540,7 @@
case 18:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 144)) {
_Internal::set_has_py_generic_services(&has_bits);
- py_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ py_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6710,7 +6548,7 @@
case 20:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 160)) {
_Internal::set_has_java_generate_equals_and_hash(&has_bits);
- java_generate_equals_and_hash_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ java_generate_equals_and_hash_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6718,7 +6556,7 @@
case 23:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 184)) {
_Internal::set_has_deprecated(&has_bits);
- deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6726,15 +6564,15 @@
case 27:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 216)) {
_Internal::set_has_java_string_check_utf8(&has_bits);
- java_string_check_utf8_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ java_string_check_utf8_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
- // optional bool cc_enable_arenas = 31 [default = false];
+ // optional bool cc_enable_arenas = 31 [default = true];
case 31:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 248)) {
_Internal::set_has_cc_enable_arenas(&has_bits);
- cc_enable_arenas_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ cc_enable_arenas_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6797,7 +6635,7 @@
case 42:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) {
_Internal::set_has_php_generic_services(&has_bits);
- php_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ php_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -6847,7 +6685,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -6890,7 +6730,7 @@
}
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- if (cached_has_bits & 0x00080000u) {
+ if (cached_has_bits & 0x00040000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
9, this->_internal_optimize_for(), target);
@@ -6948,8 +6788,8 @@
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(27, this->_internal_java_string_check_utf8(), target);
}
- // optional bool cc_enable_arenas = 31 [default = false];
- if (cached_has_bits & 0x00040000u) {
+ // optional bool cc_enable_arenas = 31 [default = true];
+ if (cached_has_bits & 0x00080000u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(31, this->_internal_cc_enable_arenas(), target);
}
@@ -7044,7 +6884,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FileOptions)
return target;
@@ -7183,17 +7023,17 @@
total_size += 2 + 1;
}
- // optional bool cc_enable_arenas = 31 [default = false];
- if (cached_has_bits & 0x00040000u) {
- total_size += 2 + 1;
- }
-
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- if (cached_has_bits & 0x00080000u) {
+ if (cached_has_bits & 0x00040000u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_optimize_for());
}
+ // optional bool cc_enable_arenas = 31 [default = true];
+ if (cached_has_bits & 0x00080000u) {
+ total_size += 2 + 1;
+ }
+
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
@@ -7223,7 +7063,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -7290,10 +7130,10 @@
deprecated_ = from.deprecated_;
}
if (cached_has_bits & 0x00040000u) {
- cc_enable_arenas_ = from.cc_enable_arenas_;
+ optimize_for_ = from.optimize_for_;
}
if (cached_has_bits & 0x00080000u) {
- optimize_for_ = from.optimize_for_;
+ cc_enable_arenas_ = from.cc_enable_arenas_;
}
_has_bits_[0] |= cached_has_bits;
}
@@ -7325,39 +7165,27 @@
void FileOptions::InternalSwap(FileOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
- java_package_.Swap(&other->java_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- java_outer_classname_.Swap(&other->java_outer_classname_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- go_package_.Swap(&other->go_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- objc_class_prefix_.Swap(&other->objc_class_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- csharp_namespace_.Swap(&other->csharp_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swift_prefix_.Swap(&other->swift_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- php_class_prefix_.Swap(&other->php_class_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- php_namespace_.Swap(&other->php_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- php_metadata_namespace_.Swap(&other->php_metadata_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- ruby_package_.Swap(&other->ruby_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(java_multiple_files_, other->java_multiple_files_);
- swap(java_generate_equals_and_hash_, other->java_generate_equals_and_hash_);
- swap(java_string_check_utf8_, other->java_string_check_utf8_);
- swap(cc_generic_services_, other->cc_generic_services_);
- swap(java_generic_services_, other->java_generic_services_);
- swap(py_generic_services_, other->py_generic_services_);
- swap(php_generic_services_, other->php_generic_services_);
- swap(deprecated_, other->deprecated_);
- swap(cc_enable_arenas_, other->cc_enable_arenas_);
+ java_package_.Swap(&other->java_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ java_outer_classname_.Swap(&other->java_outer_classname_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ go_package_.Swap(&other->go_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ objc_class_prefix_.Swap(&other->objc_class_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ csharp_namespace_.Swap(&other->csharp_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ swift_prefix_.Swap(&other->swift_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ php_class_prefix_.Swap(&other->php_class_prefix_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ php_namespace_.Swap(&other->php_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ php_metadata_namespace_.Swap(&other->php_metadata_namespace_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ruby_package_.Swap(&other->ruby_package_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(FileOptions, deprecated_)
+ + sizeof(FileOptions::deprecated_)
+ - PROTOBUF_FIELD_OFFSET(FileOptions, java_multiple_files_)>(
+ reinterpret_cast<char*>(&java_multiple_files_),
+ reinterpret_cast<char*>(&other->java_multiple_files_));
swap(optimize_for_, other->optimize_for_);
+ swap(cc_enable_arenas_, other->cc_enable_arenas_);
}
::PROTOBUF_NAMESPACE_ID::Metadata FileOptions::GetMetadata() const {
@@ -7386,15 +7214,9 @@
}
};
-MessageOptions::MessageOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.MessageOptions)
-}
MessageOptions::MessageOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -7402,10 +7224,9 @@
}
MessageOptions::MessageOptions(const MessageOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&message_set_wire_format_, &from.message_set_wire_format_,
static_cast<size_t>(reinterpret_cast<char*>(&map_entry_) -
@@ -7423,10 +7244,11 @@
MessageOptions::~MessageOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.MessageOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void MessageOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void MessageOptions::ArenaDtor(void* object) {
@@ -7456,13 +7278,13 @@
reinterpret_cast<char*>(&map_entry_) -
reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_));
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* MessageOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -7472,7 +7294,7 @@
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_message_set_wire_format(&has_bits);
- message_set_wire_format_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ message_set_wire_format_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -7480,7 +7302,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_no_standard_descriptor_accessor(&has_bits);
- no_standard_descriptor_accessor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ no_standard_descriptor_accessor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -7488,7 +7310,7 @@
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_deprecated(&has_bits);
- deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -7496,7 +7318,7 @@
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) {
_Internal::set_has_map_entry(&has_bits);
- map_entry_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ map_entry_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -7524,7 +7346,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -7584,7 +7408,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MessageOptions)
return target;
@@ -7658,7 +7482,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MessageOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -7707,13 +7531,15 @@
void MessageOptions::InternalSwap(MessageOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
- swap(message_set_wire_format_, other->message_set_wire_format_);
- swap(no_standard_descriptor_accessor_, other->no_standard_descriptor_accessor_);
- swap(deprecated_, other->deprecated_);
- swap(map_entry_, other->map_entry_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(MessageOptions, map_entry_)
+ + sizeof(MessageOptions::map_entry_)
+ - PROTOBUF_FIELD_OFFSET(MessageOptions, message_set_wire_format_)>(
+ reinterpret_cast<char*>(&message_set_wire_format_),
+ reinterpret_cast<char*>(&other->message_set_wire_format_));
}
::PROTOBUF_NAMESPACE_ID::Metadata MessageOptions::GetMetadata() const {
@@ -7748,15 +7574,9 @@
}
};
-FieldOptions::FieldOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.FieldOptions)
-}
FieldOptions::FieldOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -7764,10 +7584,9 @@
}
FieldOptions::FieldOptions(const FieldOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&ctype_, &from.ctype_,
static_cast<size_t>(reinterpret_cast<char*>(&jstype_) -
@@ -7785,10 +7604,11 @@
FieldOptions::~FieldOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.FieldOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void FieldOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void FieldOptions::ArenaDtor(void* object) {
@@ -7821,13 +7641,13 @@
reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* FieldOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -7836,7 +7656,7 @@
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldOptions_CType_IsValid(val))) {
_internal_set_ctype(static_cast<PROTOBUF_NAMESPACE_ID::FieldOptions_CType>(val));
@@ -7849,7 +7669,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_packed(&has_bits);
- packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -7857,7 +7677,7 @@
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_deprecated(&has_bits);
- deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -7865,14 +7685,14 @@
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
_Internal::set_has_lazy(&has_bits);
- lazy_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ lazy_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::FieldOptions_JSType_IsValid(val))) {
_internal_set_jstype(static_cast<PROTOBUF_NAMESPACE_ID::FieldOptions_JSType>(val));
@@ -7885,7 +7705,7 @@
case 10:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) {
_Internal::set_has_weak(&has_bits);
- weak_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ weak_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -7913,7 +7733,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -7987,7 +7809,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldOptions)
return target;
@@ -8073,7 +7895,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -8128,15 +7950,15 @@
void FieldOptions::InternalSwap(FieldOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
- swap(ctype_, other->ctype_);
- swap(packed_, other->packed_);
- swap(lazy_, other->lazy_);
- swap(deprecated_, other->deprecated_);
- swap(weak_, other->weak_);
- swap(jstype_, other->jstype_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(FieldOptions, jstype_)
+ + sizeof(FieldOptions::jstype_)
+ - PROTOBUF_FIELD_OFFSET(FieldOptions, ctype_)>(
+ reinterpret_cast<char*>(&ctype_),
+ reinterpret_cast<char*>(&other->ctype_));
}
::PROTOBUF_NAMESPACE_ID::Metadata FieldOptions::GetMetadata() const {
@@ -8150,18 +7972,11 @@
}
class OneofOptions::_Internal {
public:
- using HasBits = decltype(std::declval<OneofOptions>()._has_bits_);
};
-OneofOptions::OneofOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.OneofOptions)
-}
OneofOptions::OneofOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -8169,10 +7984,8 @@
}
OneofOptions::OneofOptions(const OneofOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
- _has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.OneofOptions)
}
@@ -8184,10 +7997,11 @@
OneofOptions::~OneofOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.OneofOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void OneofOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void OneofOptions::ArenaDtor(void* object) {
@@ -8213,13 +8027,12 @@
_extensions_.Clear();
uninterpreted_option_.Clear();
- _has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* OneofOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -8249,7 +8062,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -8283,7 +8098,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.OneofOptions)
return target;
@@ -8334,7 +8149,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.OneofOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -8367,8 +8182,7 @@
void OneofOptions::InternalSwap(OneofOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_has_bits_[0], other->_has_bits_[0]);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
}
@@ -8392,15 +8206,9 @@
}
};
-EnumOptions::EnumOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.EnumOptions)
-}
EnumOptions::EnumOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -8408,10 +8216,9 @@
}
EnumOptions::EnumOptions(const EnumOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&allow_alias_, &from.allow_alias_,
static_cast<size_t>(reinterpret_cast<char*>(&deprecated_) -
@@ -8429,10 +8236,11 @@
EnumOptions::~EnumOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.EnumOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void EnumOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void EnumOptions::ArenaDtor(void* object) {
@@ -8462,13 +8270,13 @@
reinterpret_cast<char*>(&deprecated_) -
reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_));
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* EnumOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -8478,7 +8286,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_allow_alias(&has_bits);
- allow_alias_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ allow_alias_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -8486,7 +8294,7 @@
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_deprecated(&has_bits);
- deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -8514,7 +8322,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -8562,7 +8372,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumOptions)
return target;
@@ -8626,7 +8436,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -8669,11 +8479,15 @@
void EnumOptions::InternalSwap(EnumOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
- swap(allow_alias_, other->allow_alias_);
- swap(deprecated_, other->deprecated_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(EnumOptions, deprecated_)
+ + sizeof(EnumOptions::deprecated_)
+ - PROTOBUF_FIELD_OFFSET(EnumOptions, allow_alias_)>(
+ reinterpret_cast<char*>(&allow_alias_),
+ reinterpret_cast<char*>(&other->allow_alias_));
}
::PROTOBUF_NAMESPACE_ID::Metadata EnumOptions::GetMetadata() const {
@@ -8693,15 +8507,9 @@
}
};
-EnumValueOptions::EnumValueOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions)
-}
EnumValueOptions::EnumValueOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -8709,10 +8517,9 @@
}
EnumValueOptions::EnumValueOptions(const EnumValueOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
deprecated_ = from.deprecated_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueOptions)
@@ -8726,10 +8533,11 @@
EnumValueOptions::~EnumValueOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.EnumValueOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void EnumValueOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void EnumValueOptions::ArenaDtor(void* object) {
@@ -8757,13 +8565,13 @@
uninterpreted_option_.Clear();
deprecated_ = false;
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* EnumValueOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -8773,7 +8581,7 @@
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_deprecated(&has_bits);
- deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -8801,7 +8609,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -8843,7 +8653,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValueOptions)
return target;
@@ -8900,7 +8710,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValueOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -8936,7 +8746,7 @@
void EnumValueOptions::InternalSwap(EnumValueOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
swap(deprecated_, other->deprecated_);
@@ -8959,15 +8769,9 @@
}
};
-ServiceOptions::ServiceOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions)
-}
ServiceOptions::ServiceOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -8975,10 +8779,9 @@
}
ServiceOptions::ServiceOptions(const ServiceOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
deprecated_ = from.deprecated_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceOptions)
@@ -8992,10 +8795,11 @@
ServiceOptions::~ServiceOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.ServiceOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void ServiceOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void ServiceOptions::ArenaDtor(void* object) {
@@ -9023,13 +8827,13 @@
uninterpreted_option_.Clear();
deprecated_ = false;
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* ServiceOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -9039,7 +8843,7 @@
case 33:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_deprecated(&has_bits);
- deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -9067,7 +8871,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -9109,7 +8915,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ServiceOptions)
return target;
@@ -9166,7 +8972,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ServiceOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -9202,7 +9008,7 @@
void ServiceOptions::InternalSwap(ServiceOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
swap(deprecated_, other->deprecated_);
@@ -9228,15 +9034,9 @@
}
};
-MethodOptions::MethodOptions()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.MethodOptions)
-}
MethodOptions::MethodOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
_extensions_(arena),
- _internal_metadata_(arena),
uninterpreted_option_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -9244,10 +9044,9 @@
}
MethodOptions::MethodOptions(const MethodOptions& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
uninterpreted_option_(from.uninterpreted_option_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
_extensions_.MergeFrom(from._extensions_);
::memcpy(&deprecated_, &from.deprecated_,
static_cast<size_t>(reinterpret_cast<char*>(&idempotency_level_) -
@@ -9265,10 +9064,11 @@
MethodOptions::~MethodOptions() {
// @@protoc_insertion_point(destructor:google.protobuf.MethodOptions)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void MethodOptions::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void MethodOptions::ArenaDtor(void* object) {
@@ -9301,13 +9101,13 @@
reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* MethodOptions::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -9317,14 +9117,14 @@
case 33:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
_Internal::set_has_deprecated(&has_bits);
- deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
case 34:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel_IsValid(val))) {
_internal_set_idempotency_level(static_cast<PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel>(val));
@@ -9357,7 +9157,9 @@
CHK_(ptr != nullptr);
continue;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -9406,7 +9208,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.MethodOptions)
return target;
@@ -9471,7 +9273,7 @@
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MethodOptions)
GOOGLE_DCHECK_NE(&from, this);
_extensions_.MergeFrom(from._extensions_);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -9514,11 +9316,15 @@
void MethodOptions::InternalSwap(MethodOptions* other) {
using std::swap;
_extensions_.Swap(&other->_extensions_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
uninterpreted_option_.InternalSwap(&other->uninterpreted_option_);
- swap(deprecated_, other->deprecated_);
- swap(idempotency_level_, other->idempotency_level_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(MethodOptions, idempotency_level_)
+ + sizeof(MethodOptions::idempotency_level_)
+ - PROTOBUF_FIELD_OFFSET(MethodOptions, deprecated_)>(
+ reinterpret_cast<char*>(&deprecated_),
+ reinterpret_cast<char*>(&other->deprecated_));
}
::PROTOBUF_NAMESPACE_ID::Metadata MethodOptions::GetMetadata() const {
@@ -9539,29 +9345,25 @@
static void set_has_is_extension(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
+ static bool MissingRequiredFields(const HasBits& has_bits) {
+ return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0;
+ }
};
-UninterpretedOption_NamePart::UninterpretedOption_NamePart()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption.NamePart)
-}
UninterpretedOption_NamePart::UninterpretedOption_NamePart(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption.NamePart)
}
UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_part_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_name_part()) {
name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name_part(),
- GetArenaNoVirtual());
+ GetArena());
}
is_extension_ = from.is_extension_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption.NamePart)
@@ -9576,10 +9378,11 @@
UninterpretedOption_NamePart::~UninterpretedOption_NamePart() {
// @@protoc_insertion_point(destructor:google.protobuf.UninterpretedOption.NamePart)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void UninterpretedOption_NamePart::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_part_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
@@ -9610,13 +9413,13 @@
}
is_extension_ = false;
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* UninterpretedOption_NamePart::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -9637,7 +9440,7 @@
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_Internal::set_has_is_extension(&has_bits);
- is_extension_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ is_extension_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -9647,7 +9450,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -9687,7 +9492,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UninterpretedOption.NamePart)
return target;
@@ -9758,7 +9563,7 @@
void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption.NamePart)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -9789,16 +9594,15 @@
}
bool UninterpretedOption_NamePart::IsInitialized() const {
- if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
+ if (_Internal::MissingRequiredFields(_has_bits_)) return false;
return true;
}
void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
- name_part_.Swap(&other->name_part_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ name_part_.Swap(&other->name_part_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(is_extension_, other->is_extension_);
}
@@ -9834,14 +9638,8 @@
}
};
-UninterpretedOption::UninterpretedOption()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption)
-}
UninterpretedOption::UninterpretedOption(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
name_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -9849,24 +9647,23 @@
}
UninterpretedOption::UninterpretedOption(const UninterpretedOption& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
name_(from.name_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
identifier_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_identifier_value()) {
identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_identifier_value(),
- GetArenaNoVirtual());
+ GetArena());
}
string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_string_value()) {
string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_string_value(),
- GetArenaNoVirtual());
+ GetArena());
}
aggregate_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_aggregate_value()) {
aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_aggregate_value(),
- GetArenaNoVirtual());
+ GetArena());
}
::memcpy(&positive_int_value_, &from.positive_int_value_,
static_cast<size_t>(reinterpret_cast<char*>(&double_value_) -
@@ -9887,10 +9684,11 @@
UninterpretedOption::~UninterpretedOption() {
// @@protoc_insertion_point(destructor:google.protobuf.UninterpretedOption)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void UninterpretedOption::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
identifier_value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
string_value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
aggregate_value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
@@ -9936,13 +9734,13 @@
reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* UninterpretedOption::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -9975,7 +9773,7 @@
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
_Internal::set_has_positive_int_value(&has_bits);
- positive_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ positive_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -9983,7 +9781,7 @@
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
_Internal::set_has_negative_int_value(&has_bits);
- negative_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ negative_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -10020,7 +9818,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -10096,7 +9896,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UninterpretedOption)
return target;
@@ -10187,7 +9987,7 @@
void UninterpretedOption::MergeFrom(const UninterpretedOption& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -10237,18 +10037,18 @@
void UninterpretedOption::InternalSwap(UninterpretedOption* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
name_.InternalSwap(&other->name_);
- identifier_value_.Swap(&other->identifier_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- string_value_.Swap(&other->string_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- aggregate_value_.Swap(&other->aggregate_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(positive_int_value_, other->positive_int_value_);
- swap(negative_int_value_, other->negative_int_value_);
- swap(double_value_, other->double_value_);
+ identifier_value_.Swap(&other->identifier_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ string_value_.Swap(&other->string_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ aggregate_value_.Swap(&other->aggregate_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(UninterpretedOption, double_value_)
+ + sizeof(UninterpretedOption::double_value_)
+ - PROTOBUF_FIELD_OFFSET(UninterpretedOption, positive_int_value_)>(
+ reinterpret_cast<char*>(&positive_int_value_),
+ reinterpret_cast<char*>(&other->positive_int_value_));
}
::PROTOBUF_NAMESPACE_ID::Metadata UninterpretedOption::GetMetadata() const {
@@ -10271,14 +10071,8 @@
}
};
-SourceCodeInfo_Location::SourceCodeInfo_Location()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location)
-}
SourceCodeInfo_Location::SourceCodeInfo_Location(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
path_(arena),
span_(arena),
leading_detached_comments_(arena) {
@@ -10288,21 +10082,20 @@
}
SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
path_(from.path_),
span_(from.span_),
leading_detached_comments_(from.leading_detached_comments_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
leading_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_leading_comments()) {
leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_leading_comments(),
- GetArenaNoVirtual());
+ GetArena());
}
trailing_comments_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_trailing_comments()) {
trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_trailing_comments(),
- GetArenaNoVirtual());
+ GetArena());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo.Location)
}
@@ -10316,10 +10109,11 @@
SourceCodeInfo_Location::~SourceCodeInfo_Location() {
// @@protoc_insertion_point(destructor:google.protobuf.SourceCodeInfo.Location)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void SourceCodeInfo_Location::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
leading_comments_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
trailing_comments_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
@@ -10358,13 +10152,13 @@
}
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SourceCodeInfo_Location::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -10376,7 +10170,7 @@
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(_internal_mutable_path(), ptr, ctx);
CHK_(ptr);
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8) {
- _internal_add_path(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
+ _internal_add_path(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -10386,7 +10180,7 @@
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(_internal_mutable_span(), ptr, ctx);
CHK_(ptr);
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16) {
- _internal_add_span(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
+ _internal_add_span(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -10434,7 +10228,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -10506,7 +10302,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceCodeInfo.Location)
return target;
@@ -10602,7 +10398,7 @@
void SourceCodeInfo_Location::MergeFrom(const SourceCodeInfo_Location& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo.Location)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -10640,15 +10436,13 @@
void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
path_.InternalSwap(&other->path_);
span_.InternalSwap(&other->span_);
leading_detached_comments_.InternalSwap(&other->leading_detached_comments_);
- leading_comments_.Swap(&other->leading_comments_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- trailing_comments_.Swap(&other->trailing_comments_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ leading_comments_.Swap(&other->leading_comments_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ trailing_comments_.Swap(&other->trailing_comments_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
::PROTOBUF_NAMESPACE_ID::Metadata SourceCodeInfo_Location::GetMetadata() const {
@@ -10662,17 +10456,10 @@
}
class SourceCodeInfo::_Internal {
public:
- using HasBits = decltype(std::declval<SourceCodeInfo>()._has_bits_);
};
-SourceCodeInfo::SourceCodeInfo()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo)
-}
SourceCodeInfo::SourceCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
location_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -10680,10 +10467,8 @@
}
SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
- _has_bits_(from._has_bits_),
location_(from.location_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo)
}
@@ -10694,10 +10479,11 @@
SourceCodeInfo::~SourceCodeInfo() {
// @@protoc_insertion_point(destructor:google.protobuf.SourceCodeInfo)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void SourceCodeInfo::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void SourceCodeInfo::ArenaDtor(void* object) {
@@ -10722,13 +10508,12 @@
(void) cached_has_bits;
location_.Clear();
- _has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SourceCodeInfo::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -10752,7 +10537,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -10782,7 +10569,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceCodeInfo)
return target;
@@ -10830,7 +10617,7 @@
void SourceCodeInfo::MergeFrom(const SourceCodeInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -10857,8 +10644,7 @@
void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_has_bits_[0], other->_has_bits_[0]);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
location_.InternalSwap(&other->location_);
}
@@ -10885,14 +10671,8 @@
}
};
-GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation)
-}
GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
path_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -10900,14 +10680,13 @@
}
GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeInfo_Annotation& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
_has_bits_(from._has_bits_),
path_(from.path_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
source_file_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_source_file()) {
source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_source_file(),
- GetArenaNoVirtual());
+ GetArena());
}
::memcpy(&begin_, &from.begin_,
static_cast<size_t>(reinterpret_cast<char*>(&end_) -
@@ -10926,10 +10705,11 @@
GeneratedCodeInfo_Annotation::~GeneratedCodeInfo_Annotation() {
// @@protoc_insertion_point(destructor:google.protobuf.GeneratedCodeInfo.Annotation)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void GeneratedCodeInfo_Annotation::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
source_file_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
@@ -10965,13 +10745,13 @@
reinterpret_cast<char*>(&begin_)) + sizeof(end_));
}
_has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -10983,7 +10763,7 @@
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(_internal_mutable_path(), ptr, ctx);
CHK_(ptr);
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8) {
- _internal_add_path(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
+ _internal_add_path(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -11002,7 +10782,7 @@
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
_Internal::set_has_begin(&has_bits);
- begin_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ begin_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -11010,7 +10790,7 @@
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
_Internal::set_has_end(&has_bits);
- end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -11020,7 +10800,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -11075,7 +10857,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.GeneratedCodeInfo.Annotation)
return target;
@@ -11155,7 +10937,7 @@
void GeneratedCodeInfo_Annotation::MergeFrom(const GeneratedCodeInfo_Annotation& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo.Annotation)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -11195,13 +10977,16 @@
void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
path_.InternalSwap(&other->path_);
- source_file_.Swap(&other->source_file_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(begin_, other->begin_);
- swap(end_, other->end_);
+ source_file_.Swap(&other->source_file_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(GeneratedCodeInfo_Annotation, end_)
+ + sizeof(GeneratedCodeInfo_Annotation::end_)
+ - PROTOBUF_FIELD_OFFSET(GeneratedCodeInfo_Annotation, begin_)>(
+ reinterpret_cast<char*>(&begin_),
+ reinterpret_cast<char*>(&other->begin_));
}
::PROTOBUF_NAMESPACE_ID::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const {
@@ -11215,17 +11000,10 @@
}
class GeneratedCodeInfo::_Internal {
public:
- using HasBits = decltype(std::declval<GeneratedCodeInfo>()._has_bits_);
};
-GeneratedCodeInfo::GeneratedCodeInfo()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo)
-}
GeneratedCodeInfo::GeneratedCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
annotation_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -11233,10 +11011,8 @@
}
GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
- _has_bits_(from._has_bits_),
annotation_(from.annotation_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo)
}
@@ -11247,10 +11023,11 @@
GeneratedCodeInfo::~GeneratedCodeInfo() {
// @@protoc_insertion_point(destructor:google.protobuf.GeneratedCodeInfo)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void GeneratedCodeInfo::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void GeneratedCodeInfo::ArenaDtor(void* object) {
@@ -11275,13 +11052,12 @@
(void) cached_has_bits;
annotation_.Clear();
- _has_bits_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* GeneratedCodeInfo::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -11305,7 +11081,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -11335,7 +11113,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.GeneratedCodeInfo)
return target;
@@ -11383,7 +11161,7 @@
void GeneratedCodeInfo::MergeFrom(const GeneratedCodeInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -11410,8 +11188,7 @@
void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- swap(_has_bits_[0], other->_has_bits_[0]);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
annotation_.InternalSwap(&other->annotation_);
}
diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h
index 20912ff..28f73ba 100644
--- a/src/google/protobuf/descriptor.pb.h
+++ b/src/google/protobuf/descriptor.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -330,10 +330,10 @@
}
// ===================================================================
-class PROTOBUF_EXPORT FileDescriptorSet :
+class PROTOBUF_EXPORT FileDescriptorSet PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorSet) */ {
public:
- FileDescriptorSet();
+ inline FileDescriptorSet() : FileDescriptorSet(nullptr) {};
virtual ~FileDescriptorSet();
FileDescriptorSet(const FileDescriptorSet& from);
@@ -347,7 +347,7 @@
return *this;
}
inline FileDescriptorSet& operator=(FileDescriptorSet&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -356,18 +356,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -392,7 +386,7 @@
}
inline void Swap(FileDescriptorSet* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -400,7 +394,7 @@
}
void UnsafeArenaSwap(FileDescriptorSet* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -440,13 +434,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -487,21 +474,19 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
- mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::FileDescriptorProto > file_;
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT FileDescriptorProto :
+class PROTOBUF_EXPORT FileDescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ {
public:
- FileDescriptorProto();
+ inline FileDescriptorProto() : FileDescriptorProto(nullptr) {};
virtual ~FileDescriptorProto();
FileDescriptorProto(const FileDescriptorProto& from);
@@ -515,7 +500,7 @@
return *this;
}
inline FileDescriptorProto& operator=(FileDescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -524,18 +509,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -560,7 +539,7 @@
}
inline void Swap(FileDescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -568,7 +547,7 @@
}
void UnsafeArenaSwap(FileDescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -608,13 +587,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -911,7 +883,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -933,10 +904,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT DescriptorProto_ExtensionRange :
+class PROTOBUF_EXPORT DescriptorProto_ExtensionRange PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ {
public:
- DescriptorProto_ExtensionRange();
+ inline DescriptorProto_ExtensionRange() : DescriptorProto_ExtensionRange(nullptr) {};
virtual ~DescriptorProto_ExtensionRange();
DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from);
@@ -950,7 +921,7 @@
return *this;
}
inline DescriptorProto_ExtensionRange& operator=(DescriptorProto_ExtensionRange&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -959,18 +930,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -995,7 +960,7 @@
}
inline void Swap(DescriptorProto_ExtensionRange* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1003,7 +968,7 @@
}
void UnsafeArenaSwap(DescriptorProto_ExtensionRange* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1043,13 +1008,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1118,7 +1076,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1131,10 +1088,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT DescriptorProto_ReservedRange :
+class PROTOBUF_EXPORT DescriptorProto_ReservedRange PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ {
public:
- DescriptorProto_ReservedRange();
+ inline DescriptorProto_ReservedRange() : DescriptorProto_ReservedRange(nullptr) {};
virtual ~DescriptorProto_ReservedRange();
DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from);
@@ -1148,7 +1105,7 @@
return *this;
}
inline DescriptorProto_ReservedRange& operator=(DescriptorProto_ReservedRange&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1157,18 +1114,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1193,7 +1144,7 @@
}
inline void Swap(DescriptorProto_ReservedRange* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1201,7 +1152,7 @@
}
void UnsafeArenaSwap(DescriptorProto_ReservedRange* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1241,13 +1192,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1297,7 +1241,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1309,10 +1252,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT DescriptorProto :
+class PROTOBUF_EXPORT DescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ {
public:
- DescriptorProto();
+ inline DescriptorProto() : DescriptorProto(nullptr) {};
virtual ~DescriptorProto();
DescriptorProto(const DescriptorProto& from);
@@ -1326,7 +1269,7 @@
return *this;
}
inline DescriptorProto& operator=(DescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1335,18 +1278,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1371,7 +1308,7 @@
}
inline void Swap(DescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1379,7 +1316,7 @@
}
void UnsafeArenaSwap(DescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1419,13 +1356,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1657,7 +1587,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1677,10 +1606,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT ExtensionRangeOptions :
+class PROTOBUF_EXPORT ExtensionRangeOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ {
public:
- ExtensionRangeOptions();
+ inline ExtensionRangeOptions() : ExtensionRangeOptions(nullptr) {};
virtual ~ExtensionRangeOptions();
ExtensionRangeOptions(const ExtensionRangeOptions& from);
@@ -1694,7 +1623,7 @@
return *this;
}
inline ExtensionRangeOptions& operator=(ExtensionRangeOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1703,18 +1632,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1739,7 +1662,7 @@
}
inline void Swap(ExtensionRangeOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1747,7 +1670,7 @@
}
void UnsafeArenaSwap(ExtensionRangeOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1787,13 +1710,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1837,21 +1753,19 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
- mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_;
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT FieldDescriptorProto :
+class PROTOBUF_EXPORT FieldDescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ {
public:
- FieldDescriptorProto();
+ inline FieldDescriptorProto() : FieldDescriptorProto(nullptr) {};
virtual ~FieldDescriptorProto();
FieldDescriptorProto(const FieldDescriptorProto& from);
@@ -1865,7 +1779,7 @@
return *this;
}
inline FieldDescriptorProto& operator=(FieldDescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1874,18 +1788,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1910,7 +1818,7 @@
}
inline void Swap(FieldDescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1918,7 +1826,7 @@
}
void UnsafeArenaSwap(FieldDescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1958,13 +1866,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -2083,6 +1984,7 @@
kOptionsFieldNumber = 8,
kNumberFieldNumber = 3,
kOneofIndexFieldNumber = 9,
+ kProto3OptionalFieldNumber = 17,
kLabelFieldNumber = 4,
kTypeFieldNumber = 5,
};
@@ -2275,6 +2177,19 @@
void _internal_set_oneof_index(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
+ // optional bool proto3_optional = 17;
+ bool has_proto3_optional() const;
+ private:
+ bool _internal_has_proto3_optional() const;
+ public:
+ void clear_proto3_optional();
+ bool proto3_optional() const;
+ void set_proto3_optional(bool value);
+ private:
+ bool _internal_proto3_optional() const;
+ void _internal_set_proto3_optional(bool value);
+ public:
+
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
bool has_label() const;
private:
@@ -2305,7 +2220,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -2319,16 +2233,17 @@
PROTOBUF_NAMESPACE_ID::FieldOptions* options_;
::PROTOBUF_NAMESPACE_ID::int32 number_;
::PROTOBUF_NAMESPACE_ID::int32 oneof_index_;
+ bool proto3_optional_;
int label_;
int type_;
friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT OneofDescriptorProto :
+class PROTOBUF_EXPORT OneofDescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ {
public:
- OneofDescriptorProto();
+ inline OneofDescriptorProto() : OneofDescriptorProto(nullptr) {};
virtual ~OneofDescriptorProto();
OneofDescriptorProto(const OneofDescriptorProto& from);
@@ -2342,7 +2257,7 @@
return *this;
}
inline OneofDescriptorProto& operator=(OneofDescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -2351,18 +2266,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -2387,7 +2296,7 @@
}
inline void Swap(OneofDescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -2395,7 +2304,7 @@
}
void UnsafeArenaSwap(OneofDescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -2435,13 +2344,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -2512,7 +2414,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -2524,10 +2425,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange :
+class PROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ {
public:
- EnumDescriptorProto_EnumReservedRange();
+ inline EnumDescriptorProto_EnumReservedRange() : EnumDescriptorProto_EnumReservedRange(nullptr) {};
virtual ~EnumDescriptorProto_EnumReservedRange();
EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from);
@@ -2541,7 +2442,7 @@
return *this;
}
inline EnumDescriptorProto_EnumReservedRange& operator=(EnumDescriptorProto_EnumReservedRange&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -2550,18 +2451,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -2586,7 +2481,7 @@
}
inline void Swap(EnumDescriptorProto_EnumReservedRange* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -2594,7 +2489,7 @@
}
void UnsafeArenaSwap(EnumDescriptorProto_EnumReservedRange* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -2634,13 +2529,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -2690,7 +2578,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -2702,10 +2589,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT EnumDescriptorProto :
+class PROTOBUF_EXPORT EnumDescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ {
public:
- EnumDescriptorProto();
+ inline EnumDescriptorProto() : EnumDescriptorProto(nullptr) {};
virtual ~EnumDescriptorProto();
EnumDescriptorProto(const EnumDescriptorProto& from);
@@ -2719,7 +2606,7 @@
return *this;
}
inline EnumDescriptorProto& operator=(EnumDescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -2728,18 +2615,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -2764,7 +2645,7 @@
}
inline void Swap(EnumDescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -2772,7 +2653,7 @@
}
void UnsafeArenaSwap(EnumDescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -2812,13 +2693,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -2954,7 +2828,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -2969,10 +2842,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT EnumValueDescriptorProto :
+class PROTOBUF_EXPORT EnumValueDescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ {
public:
- EnumValueDescriptorProto();
+ inline EnumValueDescriptorProto() : EnumValueDescriptorProto(nullptr) {};
virtual ~EnumValueDescriptorProto();
EnumValueDescriptorProto(const EnumValueDescriptorProto& from);
@@ -2986,7 +2859,7 @@
return *this;
}
inline EnumValueDescriptorProto& operator=(EnumValueDescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -2995,18 +2868,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -3031,7 +2898,7 @@
}
inline void Swap(EnumValueDescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -3039,7 +2906,7 @@
}
void UnsafeArenaSwap(EnumValueDescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -3079,13 +2946,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -3170,7 +3030,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -3183,10 +3042,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT ServiceDescriptorProto :
+class PROTOBUF_EXPORT ServiceDescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ {
public:
- ServiceDescriptorProto();
+ inline ServiceDescriptorProto() : ServiceDescriptorProto(nullptr) {};
virtual ~ServiceDescriptorProto();
ServiceDescriptorProto(const ServiceDescriptorProto& from);
@@ -3200,7 +3059,7 @@
return *this;
}
inline ServiceDescriptorProto& operator=(ServiceDescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -3209,18 +3068,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -3245,7 +3098,7 @@
}
inline void Swap(ServiceDescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -3253,7 +3106,7 @@
}
void UnsafeArenaSwap(ServiceDescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -3293,13 +3146,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -3389,7 +3235,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -3402,10 +3247,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT MethodDescriptorProto :
+class PROTOBUF_EXPORT MethodDescriptorProto PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ {
public:
- MethodDescriptorProto();
+ inline MethodDescriptorProto() : MethodDescriptorProto(nullptr) {};
virtual ~MethodDescriptorProto();
MethodDescriptorProto(const MethodDescriptorProto& from);
@@ -3419,7 +3264,7 @@
return *this;
}
inline MethodDescriptorProto& operator=(MethodDescriptorProto&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -3428,18 +3273,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -3464,7 +3303,7 @@
}
inline void Swap(MethodDescriptorProto* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -3472,7 +3311,7 @@
}
void UnsafeArenaSwap(MethodDescriptorProto* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -3512,13 +3351,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -3677,7 +3509,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -3693,10 +3524,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT FileOptions :
+class PROTOBUF_EXPORT FileOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ {
public:
- FileOptions();
+ inline FileOptions() : FileOptions(nullptr) {};
virtual ~FileOptions();
FileOptions(const FileOptions& from);
@@ -3710,7 +3541,7 @@
return *this;
}
inline FileOptions& operator=(FileOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -3719,18 +3550,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -3755,7 +3580,7 @@
}
inline void Swap(FileOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -3763,7 +3588,7 @@
}
void UnsafeArenaSwap(FileOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -3803,13 +3628,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -3877,8 +3695,8 @@
kPyGenericServicesFieldNumber = 18,
kPhpGenericServicesFieldNumber = 42,
kDeprecatedFieldNumber = 23,
- kCcEnableArenasFieldNumber = 31,
kOptimizeForFieldNumber = 9,
+ kCcEnableArenasFieldNumber = 31,
};
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
int uninterpreted_option_size() const;
@@ -4292,19 +4110,6 @@
void _internal_set_deprecated(bool value);
public:
- // optional bool cc_enable_arenas = 31 [default = false];
- bool has_cc_enable_arenas() const;
- private:
- bool _internal_has_cc_enable_arenas() const;
- public:
- void clear_cc_enable_arenas();
- bool cc_enable_arenas() const;
- void set_cc_enable_arenas(bool value);
- private:
- bool _internal_cc_enable_arenas() const;
- void _internal_set_cc_enable_arenas(bool value);
- public:
-
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
bool has_optimize_for() const;
private:
@@ -4318,6 +4123,19 @@
void _internal_set_optimize_for(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode value);
public:
+ // optional bool cc_enable_arenas = 31 [default = true];
+ bool has_cc_enable_arenas() const;
+ private:
+ bool _internal_has_cc_enable_arenas() const;
+ public:
+ void clear_cc_enable_arenas();
+ bool cc_enable_arenas() const;
+ void set_cc_enable_arenas(bool value);
+ private:
+ bool _internal_cc_enable_arenas() const;
+ void _internal_set_cc_enable_arenas(bool value);
+ public:
+
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FileOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.FileOptions)
private:
@@ -4325,7 +4143,6 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -4350,16 +4167,16 @@
bool py_generic_services_;
bool php_generic_services_;
bool deprecated_;
- bool cc_enable_arenas_;
int optimize_for_;
+ bool cc_enable_arenas_;
friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT MessageOptions :
+class PROTOBUF_EXPORT MessageOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ {
public:
- MessageOptions();
+ inline MessageOptions() : MessageOptions(nullptr) {};
virtual ~MessageOptions();
MessageOptions(const MessageOptions& from);
@@ -4373,7 +4190,7 @@
return *this;
}
inline MessageOptions& operator=(MessageOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -4382,18 +4199,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -4418,7 +4229,7 @@
}
inline void Swap(MessageOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -4426,7 +4237,7 @@
}
void UnsafeArenaSwap(MessageOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -4466,13 +4277,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -4572,7 +4376,6 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -4587,10 +4390,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT FieldOptions :
+class PROTOBUF_EXPORT FieldOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ {
public:
- FieldOptions();
+ inline FieldOptions() : FieldOptions(nullptr) {};
virtual ~FieldOptions();
FieldOptions(const FieldOptions& from);
@@ -4604,7 +4407,7 @@
return *this;
}
inline FieldOptions& operator=(FieldOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -4613,18 +4416,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -4649,7 +4446,7 @@
}
inline void Swap(FieldOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -4657,7 +4454,7 @@
}
void UnsafeArenaSwap(FieldOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -4697,13 +4494,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -4895,7 +4685,6 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -4912,10 +4701,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT OneofOptions :
+class PROTOBUF_EXPORT OneofOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ {
public:
- OneofOptions();
+ inline OneofOptions() : OneofOptions(nullptr) {};
virtual ~OneofOptions();
OneofOptions(const OneofOptions& from);
@@ -4929,7 +4718,7 @@
return *this;
}
inline OneofOptions& operator=(OneofOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -4938,18 +4727,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -4974,7 +4757,7 @@
}
inline void Swap(OneofOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -4982,7 +4765,7 @@
}
void UnsafeArenaSwap(OneofOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -5022,13 +4805,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -5072,21 +4848,19 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
- mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_;
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT EnumOptions :
+class PROTOBUF_EXPORT EnumOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ {
public:
- EnumOptions();
+ inline EnumOptions() : EnumOptions(nullptr) {};
virtual ~EnumOptions();
EnumOptions(const EnumOptions& from);
@@ -5100,7 +4874,7 @@
return *this;
}
inline EnumOptions& operator=(EnumOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -5109,18 +4883,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -5145,7 +4913,7 @@
}
inline void Swap(EnumOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -5153,7 +4921,7 @@
}
void UnsafeArenaSwap(EnumOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -5193,13 +4961,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -5271,7 +5032,6 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -5284,10 +5044,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT EnumValueOptions :
+class PROTOBUF_EXPORT EnumValueOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ {
public:
- EnumValueOptions();
+ inline EnumValueOptions() : EnumValueOptions(nullptr) {};
virtual ~EnumValueOptions();
EnumValueOptions(const EnumValueOptions& from);
@@ -5301,7 +5061,7 @@
return *this;
}
inline EnumValueOptions& operator=(EnumValueOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -5310,18 +5070,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -5346,7 +5100,7 @@
}
inline void Swap(EnumValueOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -5354,7 +5108,7 @@
}
void UnsafeArenaSwap(EnumValueOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -5394,13 +5148,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -5458,7 +5205,6 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -5470,10 +5216,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT ServiceOptions :
+class PROTOBUF_EXPORT ServiceOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ {
public:
- ServiceOptions();
+ inline ServiceOptions() : ServiceOptions(nullptr) {};
virtual ~ServiceOptions();
ServiceOptions(const ServiceOptions& from);
@@ -5487,7 +5233,7 @@
return *this;
}
inline ServiceOptions& operator=(ServiceOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -5496,18 +5242,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -5532,7 +5272,7 @@
}
inline void Swap(ServiceOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -5540,7 +5280,7 @@
}
void UnsafeArenaSwap(ServiceOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -5580,13 +5320,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -5644,7 +5377,6 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -5656,10 +5388,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT MethodOptions :
+class PROTOBUF_EXPORT MethodOptions PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ {
public:
- MethodOptions();
+ inline MethodOptions() : MethodOptions(nullptr) {};
virtual ~MethodOptions();
MethodOptions(const MethodOptions& from);
@@ -5673,7 +5405,7 @@
return *this;
}
inline MethodOptions& operator=(MethodOptions&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -5682,18 +5414,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -5718,7 +5444,7 @@
}
inline void Swap(MethodOptions* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -5726,7 +5452,7 @@
}
void UnsafeArenaSwap(MethodOptions* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -5766,13 +5492,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -5876,7 +5595,6 @@
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -5889,10 +5607,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT UninterpretedOption_NamePart :
+class PROTOBUF_EXPORT UninterpretedOption_NamePart PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ {
public:
- UninterpretedOption_NamePart();
+ inline UninterpretedOption_NamePart() : UninterpretedOption_NamePart(nullptr) {};
virtual ~UninterpretedOption_NamePart();
UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from);
@@ -5906,7 +5624,7 @@
return *this;
}
inline UninterpretedOption_NamePart& operator=(UninterpretedOption_NamePart&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -5915,18 +5633,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -5951,7 +5663,7 @@
}
inline void Swap(UninterpretedOption_NamePart* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -5959,7 +5671,7 @@
}
void UnsafeArenaSwap(UninterpretedOption_NamePart* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -5999,13 +5711,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -6074,7 +5779,6 @@
// helper for ByteSizeLong()
size_t RequiredFieldsByteSizeFallback() const;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -6086,10 +5790,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT UninterpretedOption :
+class PROTOBUF_EXPORT UninterpretedOption PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ {
public:
- UninterpretedOption();
+ inline UninterpretedOption() : UninterpretedOption(nullptr) {};
virtual ~UninterpretedOption();
UninterpretedOption(const UninterpretedOption& from);
@@ -6103,7 +5807,7 @@
return *this;
}
inline UninterpretedOption& operator=(UninterpretedOption&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -6112,18 +5816,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -6148,7 +5846,7 @@
}
inline void Swap(UninterpretedOption* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -6156,7 +5854,7 @@
}
void UnsafeArenaSwap(UninterpretedOption* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -6196,13 +5894,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -6377,7 +6068,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -6394,10 +6084,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT SourceCodeInfo_Location :
+class PROTOBUF_EXPORT SourceCodeInfo_Location PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ {
public:
- SourceCodeInfo_Location();
+ inline SourceCodeInfo_Location() : SourceCodeInfo_Location(nullptr) {};
virtual ~SourceCodeInfo_Location();
SourceCodeInfo_Location(const SourceCodeInfo_Location& from);
@@ -6411,7 +6101,7 @@
return *this;
}
inline SourceCodeInfo_Location& operator=(SourceCodeInfo_Location&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -6420,18 +6110,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -6456,7 +6140,7 @@
}
inline void Swap(SourceCodeInfo_Location* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -6464,7 +6148,7 @@
}
void UnsafeArenaSwap(SourceCodeInfo_Location* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -6504,13 +6188,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -6663,7 +6340,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -6680,10 +6356,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT SourceCodeInfo :
+class PROTOBUF_EXPORT SourceCodeInfo PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ {
public:
- SourceCodeInfo();
+ inline SourceCodeInfo() : SourceCodeInfo(nullptr) {};
virtual ~SourceCodeInfo();
SourceCodeInfo(const SourceCodeInfo& from);
@@ -6697,7 +6373,7 @@
return *this;
}
inline SourceCodeInfo& operator=(SourceCodeInfo&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -6706,18 +6382,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -6742,7 +6412,7 @@
}
inline void Swap(SourceCodeInfo* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -6750,7 +6420,7 @@
}
void UnsafeArenaSwap(SourceCodeInfo* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -6790,13 +6460,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -6839,21 +6502,19 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
- mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location > location_;
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT GeneratedCodeInfo_Annotation :
+class PROTOBUF_EXPORT GeneratedCodeInfo_Annotation PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ {
public:
- GeneratedCodeInfo_Annotation();
+ inline GeneratedCodeInfo_Annotation() : GeneratedCodeInfo_Annotation(nullptr) {};
virtual ~GeneratedCodeInfo_Annotation();
GeneratedCodeInfo_Annotation(const GeneratedCodeInfo_Annotation& from);
@@ -6867,7 +6528,7 @@
return *this;
}
inline GeneratedCodeInfo_Annotation& operator=(GeneratedCodeInfo_Annotation&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -6876,18 +6537,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -6912,7 +6567,7 @@
}
inline void Swap(GeneratedCodeInfo_Annotation* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -6920,7 +6575,7 @@
}
void UnsafeArenaSwap(GeneratedCodeInfo_Annotation* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -6960,13 +6615,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -7069,7 +6717,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -7084,10 +6731,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT GeneratedCodeInfo :
+class PROTOBUF_EXPORT GeneratedCodeInfo PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ {
public:
- GeneratedCodeInfo();
+ inline GeneratedCodeInfo() : GeneratedCodeInfo(nullptr) {};
virtual ~GeneratedCodeInfo();
GeneratedCodeInfo(const GeneratedCodeInfo& from);
@@ -7101,7 +6748,7 @@
return *this;
}
inline GeneratedCodeInfo& operator=(GeneratedCodeInfo&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -7110,18 +6757,12 @@
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
- return _internal_metadata_.unknown_fields();
+ return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
- return _internal_metadata_.mutable_unknown_fields();
+ return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -7146,7 +6787,7 @@
}
inline void Swap(GeneratedCodeInfo* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -7154,7 +6795,7 @@
}
void UnsafeArenaSwap(GeneratedCodeInfo* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -7194,13 +6835,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -7243,13 +6877,11 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
- mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation > annotation_;
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// ===================================================================
@@ -7315,7 +6947,7 @@
return _internal_has_name();
}
inline void FileDescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& FileDescriptorProto::name() const {
@@ -7335,31 +6967,31 @@
}
inline void FileDescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileDescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.name)
}
inline void FileDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.name)
}
inline void FileDescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.name)
}
inline std::string* FileDescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name)
@@ -7367,7 +6999,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileDescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -7376,26 +7008,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.name)
}
inline std::string* FileDescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileDescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.name)
}
@@ -7408,7 +7040,7 @@
return _internal_has_package();
}
inline void FileDescriptorProto::clear_package() {
- package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& FileDescriptorProto::package() const {
@@ -7428,31 +7060,31 @@
}
inline void FileDescriptorProto::_internal_set_package(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
- package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileDescriptorProto::set_package(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
package_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.package)
}
inline void FileDescriptorProto::set_package(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.package)
}
inline void FileDescriptorProto::set_package(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.package)
}
inline std::string* FileDescriptorProto::_internal_mutable_package() {
_has_bits_[0] |= 0x00000002u;
- return package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileDescriptorProto::release_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package)
@@ -7460,7 +7092,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
- return package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileDescriptorProto::set_allocated_package(std::string* package) {
if (package != nullptr) {
@@ -7469,26 +7101,26 @@
_has_bits_[0] &= ~0x00000002u;
}
package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), package,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.package)
}
inline std::string* FileDescriptorProto::unsafe_arena_release_package() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.package)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000002u;
return package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileDescriptorProto::unsafe_arena_set_allocated_package(
std::string* package) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (package != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- package, GetArenaNoVirtual());
+ package, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.package)
}
@@ -7838,9 +7470,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options)
return _internal_options();
}
+inline void FileDescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::FileOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000008u;
+ } else {
+ _has_bits_[0] &= ~0x00000008u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000008u;
+ PROTOBUF_NAMESPACE_ID::FileOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -7855,7 +7502,7 @@
inline PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000008u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::FileOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::FileOptions>(GetArena());
options_ = p;
}
return options_;
@@ -7865,7 +7512,7 @@
return _internal_mutable_options();
}
inline void FileDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::FileOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -7906,9 +7553,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info)
return _internal_source_code_info();
}
+inline void FileDescriptorProto::unsafe_arena_set_allocated_source_code_info(
+ PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_code_info_);
+ }
+ source_code_info_ = source_code_info;
+ if (source_code_info) {
+ _has_bits_[0] |= 0x00000010u;
+ } else {
+ _has_bits_[0] &= ~0x00000010u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.source_code_info)
+}
inline PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::release_source_code_info() {
- auto temp = unsafe_arena_release_source_code_info();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000010u;
+ PROTOBUF_NAMESPACE_ID::SourceCodeInfo* temp = source_code_info_;
+ source_code_info_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -7923,7 +7585,7 @@
inline PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::_internal_mutable_source_code_info() {
_has_bits_[0] |= 0x00000010u;
if (source_code_info_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceCodeInfo>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceCodeInfo>(GetArena());
source_code_info_ = p;
}
return source_code_info_;
@@ -7933,7 +7595,7 @@
return _internal_mutable_source_code_info();
}
inline void FileDescriptorProto::set_allocated_source_code_info(PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete source_code_info_;
}
@@ -7961,7 +7623,7 @@
return _internal_has_syntax();
}
inline void FileDescriptorProto::clear_syntax() {
- syntax_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ syntax_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& FileDescriptorProto::syntax() const {
@@ -7981,31 +7643,31 @@
}
inline void FileDescriptorProto::_internal_set_syntax(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
- syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileDescriptorProto::set_syntax(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
syntax_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.syntax)
}
inline void FileDescriptorProto::set_syntax(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.syntax)
}
inline void FileDescriptorProto::set_syntax(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
syntax_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.syntax)
}
inline std::string* FileDescriptorProto::_internal_mutable_syntax() {
_has_bits_[0] |= 0x00000004u;
- return syntax_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return syntax_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileDescriptorProto::release_syntax() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax)
@@ -8013,7 +7675,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
- return syntax_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return syntax_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileDescriptorProto::set_allocated_syntax(std::string* syntax) {
if (syntax != nullptr) {
@@ -8022,26 +7684,26 @@
_has_bits_[0] &= ~0x00000004u;
}
syntax_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), syntax,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.syntax)
}
inline std::string* FileDescriptorProto::unsafe_arena_release_syntax() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.syntax)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000004u;
return syntax_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileDescriptorProto::unsafe_arena_set_allocated_syntax(
std::string* syntax) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (syntax != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
syntax_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- syntax, GetArenaNoVirtual());
+ syntax, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.syntax)
}
@@ -8127,9 +7789,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.options)
return _internal_options();
}
+inline void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000001u;
+ } else {
+ _has_bits_[0] &= ~0x00000001u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options)
+}
inline PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000001u;
+ PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -8144,7 +7821,7 @@
inline PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::_internal_mutable_options() {
_has_bits_[0] |= 0x00000001u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions>(GetArena());
options_ = p;
}
return options_;
@@ -8154,7 +7831,7 @@
return _internal_mutable_options();
}
inline void DescriptorProto_ExtensionRange::set_allocated_options(PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -8246,7 +7923,7 @@
return _internal_has_name();
}
inline void DescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& DescriptorProto::name() const {
@@ -8266,31 +7943,31 @@
}
inline void DescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void DescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.DescriptorProto.name)
}
inline void DescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.name)
}
inline void DescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.name)
}
inline std::string* DescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* DescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name)
@@ -8298,7 +7975,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void DescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -8307,26 +7984,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.name)
}
inline std::string* DescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void DescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.name)
}
@@ -8586,9 +8263,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options)
return _internal_options();
}
+inline void DescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::MessageOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000002u;
+ } else {
+ _has_bits_[0] &= ~0x00000002u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000002u;
+ PROTOBUF_NAMESPACE_ID::MessageOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -8603,7 +8295,7 @@
inline PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000002u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::MessageOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::MessageOptions>(GetArena());
options_ = p;
}
return options_;
@@ -8613,7 +8305,7 @@
return _internal_mutable_options();
}
inline void DescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::MessageOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -8801,7 +8493,7 @@
return _internal_has_name();
}
inline void FieldDescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& FieldDescriptorProto::name() const {
@@ -8821,31 +8513,31 @@
}
inline void FieldDescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FieldDescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.name)
}
inline void FieldDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.name)
}
inline void FieldDescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.name)
}
inline std::string* FieldDescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FieldDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name)
@@ -8853,7 +8545,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FieldDescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -8862,26 +8554,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.name)
}
inline std::string* FieldDescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FieldDescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.name)
}
@@ -8915,7 +8607,7 @@
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
inline bool FieldDescriptorProto::_internal_has_label() const {
- bool value = (_has_bits_[0] & 0x00000100u) != 0;
+ bool value = (_has_bits_[0] & 0x00000200u) != 0;
return value;
}
inline bool FieldDescriptorProto::has_label() const {
@@ -8923,7 +8615,7 @@
}
inline void FieldDescriptorProto::clear_label() {
label_ = 1;
- _has_bits_[0] &= ~0x00000100u;
+ _has_bits_[0] &= ~0x00000200u;
}
inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label FieldDescriptorProto::_internal_label() const {
return static_cast< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label >(label_);
@@ -8934,7 +8626,7 @@
}
inline void FieldDescriptorProto::_internal_set_label(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label value) {
assert(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label_IsValid(value));
- _has_bits_[0] |= 0x00000100u;
+ _has_bits_[0] |= 0x00000200u;
label_ = value;
}
inline void FieldDescriptorProto::set_label(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label value) {
@@ -8944,7 +8636,7 @@
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
inline bool FieldDescriptorProto::_internal_has_type() const {
- bool value = (_has_bits_[0] & 0x00000200u) != 0;
+ bool value = (_has_bits_[0] & 0x00000400u) != 0;
return value;
}
inline bool FieldDescriptorProto::has_type() const {
@@ -8952,7 +8644,7 @@
}
inline void FieldDescriptorProto::clear_type() {
type_ = 1;
- _has_bits_[0] &= ~0x00000200u;
+ _has_bits_[0] &= ~0x00000400u;
}
inline PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type FieldDescriptorProto::_internal_type() const {
return static_cast< PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type >(type_);
@@ -8963,7 +8655,7 @@
}
inline void FieldDescriptorProto::_internal_set_type(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type value) {
assert(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type_IsValid(value));
- _has_bits_[0] |= 0x00000200u;
+ _has_bits_[0] |= 0x00000400u;
type_ = value;
}
inline void FieldDescriptorProto::set_type(PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type value) {
@@ -8980,7 +8672,7 @@
return _internal_has_type_name();
}
inline void FieldDescriptorProto::clear_type_name() {
- type_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ type_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& FieldDescriptorProto::type_name() const {
@@ -9000,31 +8692,31 @@
}
inline void FieldDescriptorProto::_internal_set_type_name(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
- type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FieldDescriptorProto::set_type_name(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
type_name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.type_name)
}
inline void FieldDescriptorProto::set_type_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.type_name)
}
inline void FieldDescriptorProto::set_type_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
type_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.type_name)
}
inline std::string* FieldDescriptorProto::_internal_mutable_type_name() {
_has_bits_[0] |= 0x00000004u;
- return type_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return type_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FieldDescriptorProto::release_type_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name)
@@ -9032,7 +8724,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
- return type_name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return type_name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FieldDescriptorProto::set_allocated_type_name(std::string* type_name) {
if (type_name != nullptr) {
@@ -9041,26 +8733,26 @@
_has_bits_[0] &= ~0x00000004u;
}
type_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.type_name)
}
inline std::string* FieldDescriptorProto::unsafe_arena_release_type_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.type_name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000004u;
return type_name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FieldDescriptorProto::unsafe_arena_set_allocated_type_name(
std::string* type_name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (type_name != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
type_name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- type_name, GetArenaNoVirtual());
+ type_name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.type_name)
}
@@ -9073,7 +8765,7 @@
return _internal_has_extendee();
}
inline void FieldDescriptorProto::clear_extendee() {
- extendee_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ extendee_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& FieldDescriptorProto::extendee() const {
@@ -9093,31 +8785,31 @@
}
inline void FieldDescriptorProto::_internal_set_extendee(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
- extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FieldDescriptorProto::set_extendee(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
extendee_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.extendee)
}
inline void FieldDescriptorProto::set_extendee(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.extendee)
}
inline void FieldDescriptorProto::set_extendee(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
extendee_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.extendee)
}
inline std::string* FieldDescriptorProto::_internal_mutable_extendee() {
_has_bits_[0] |= 0x00000002u;
- return extendee_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return extendee_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FieldDescriptorProto::release_extendee() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee)
@@ -9125,7 +8817,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
- return extendee_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return extendee_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FieldDescriptorProto::set_allocated_extendee(std::string* extendee) {
if (extendee != nullptr) {
@@ -9134,26 +8826,26 @@
_has_bits_[0] &= ~0x00000002u;
}
extendee_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), extendee,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.extendee)
}
inline std::string* FieldDescriptorProto::unsafe_arena_release_extendee() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.extendee)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000002u;
return extendee_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FieldDescriptorProto::unsafe_arena_set_allocated_extendee(
std::string* extendee) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (extendee != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
extendee_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- extendee, GetArenaNoVirtual());
+ extendee, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.extendee)
}
@@ -9166,7 +8858,7 @@
return _internal_has_default_value();
}
inline void FieldDescriptorProto::clear_default_value() {
- default_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ default_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000008u;
}
inline const std::string& FieldDescriptorProto::default_value() const {
@@ -9186,31 +8878,31 @@
}
inline void FieldDescriptorProto::_internal_set_default_value(const std::string& value) {
_has_bits_[0] |= 0x00000008u;
- default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FieldDescriptorProto::set_default_value(std::string&& value) {
_has_bits_[0] |= 0x00000008u;
default_value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.default_value)
}
inline void FieldDescriptorProto::set_default_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000008u;
default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.default_value)
}
inline void FieldDescriptorProto::set_default_value(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000008u;
default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.default_value)
}
inline std::string* FieldDescriptorProto::_internal_mutable_default_value() {
_has_bits_[0] |= 0x00000008u;
- return default_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return default_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FieldDescriptorProto::release_default_value() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value)
@@ -9218,7 +8910,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000008u;
- return default_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return default_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FieldDescriptorProto::set_allocated_default_value(std::string* default_value) {
if (default_value != nullptr) {
@@ -9227,26 +8919,26 @@
_has_bits_[0] &= ~0x00000008u;
}
default_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), default_value,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.default_value)
}
inline std::string* FieldDescriptorProto::unsafe_arena_release_default_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.default_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000008u;
return default_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FieldDescriptorProto::unsafe_arena_set_allocated_default_value(
std::string* default_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (default_value != nullptr) {
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
default_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- default_value, GetArenaNoVirtual());
+ default_value, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.default_value)
}
@@ -9287,7 +8979,7 @@
return _internal_has_json_name();
}
inline void FieldDescriptorProto::clear_json_name() {
- json_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ json_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000010u;
}
inline const std::string& FieldDescriptorProto::json_name() const {
@@ -9307,31 +8999,31 @@
}
inline void FieldDescriptorProto::_internal_set_json_name(const std::string& value) {
_has_bits_[0] |= 0x00000010u;
- json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FieldDescriptorProto::set_json_name(std::string&& value) {
_has_bits_[0] |= 0x00000010u;
json_name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.json_name)
}
inline void FieldDescriptorProto::set_json_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000010u;
json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.json_name)
}
inline void FieldDescriptorProto::set_json_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000010u;
json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.json_name)
}
inline std::string* FieldDescriptorProto::_internal_mutable_json_name() {
_has_bits_[0] |= 0x00000010u;
- return json_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return json_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FieldDescriptorProto::release_json_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name)
@@ -9339,7 +9031,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000010u;
- return json_name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return json_name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FieldDescriptorProto::set_allocated_json_name(std::string* json_name) {
if (json_name != nullptr) {
@@ -9348,26 +9040,26 @@
_has_bits_[0] &= ~0x00000010u;
}
json_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), json_name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.json_name)
}
inline std::string* FieldDescriptorProto::unsafe_arena_release_json_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.json_name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000010u;
return json_name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FieldDescriptorProto::unsafe_arena_set_allocated_json_name(
std::string* json_name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (json_name != nullptr) {
_has_bits_[0] |= 0x00000010u;
} else {
_has_bits_[0] &= ~0x00000010u;
}
json_name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- json_name, GetArenaNoVirtual());
+ json_name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.json_name)
}
@@ -9393,9 +9085,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options)
return _internal_options();
}
+inline void FieldDescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::FieldOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000020u;
+ } else {
+ _has_bits_[0] &= ~0x00000020u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000020u;
+ PROTOBUF_NAMESPACE_ID::FieldOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -9410,7 +9117,7 @@
inline PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000020u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::FieldOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::FieldOptions>(GetArena());
options_ = p;
}
return options_;
@@ -9420,7 +9127,7 @@
return _internal_mutable_options();
}
inline void FieldDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::FieldOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -9439,6 +9146,34 @@
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.options)
}
+// optional bool proto3_optional = 17;
+inline bool FieldDescriptorProto::_internal_has_proto3_optional() const {
+ bool value = (_has_bits_[0] & 0x00000100u) != 0;
+ return value;
+}
+inline bool FieldDescriptorProto::has_proto3_optional() const {
+ return _internal_has_proto3_optional();
+}
+inline void FieldDescriptorProto::clear_proto3_optional() {
+ proto3_optional_ = false;
+ _has_bits_[0] &= ~0x00000100u;
+}
+inline bool FieldDescriptorProto::_internal_proto3_optional() const {
+ return proto3_optional_;
+}
+inline bool FieldDescriptorProto::proto3_optional() const {
+ // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.proto3_optional)
+ return _internal_proto3_optional();
+}
+inline void FieldDescriptorProto::_internal_set_proto3_optional(bool value) {
+ _has_bits_[0] |= 0x00000100u;
+ proto3_optional_ = value;
+}
+inline void FieldDescriptorProto::set_proto3_optional(bool value) {
+ _internal_set_proto3_optional(value);
+ // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.proto3_optional)
+}
+
// -------------------------------------------------------------------
// OneofDescriptorProto
@@ -9452,7 +9187,7 @@
return _internal_has_name();
}
inline void OneofDescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& OneofDescriptorProto::name() const {
@@ -9472,31 +9207,31 @@
}
inline void OneofDescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void OneofDescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.OneofDescriptorProto.name)
}
inline void OneofDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.OneofDescriptorProto.name)
}
inline void OneofDescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.OneofDescriptorProto.name)
}
inline std::string* OneofDescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* OneofDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name)
@@ -9504,7 +9239,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void OneofDescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -9513,26 +9248,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.name)
}
inline std::string* OneofDescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.OneofDescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void OneofDescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.name)
}
@@ -9558,9 +9293,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options)
return _internal_options();
}
+inline void OneofDescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::OneofOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000002u;
+ } else {
+ _has_bits_[0] &= ~0x00000002u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000002u;
+ PROTOBUF_NAMESPACE_ID::OneofOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -9575,7 +9325,7 @@
inline PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000002u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::OneofOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::OneofOptions>(GetArena());
options_ = p;
}
return options_;
@@ -9585,7 +9335,7 @@
return _internal_mutable_options();
}
inline void OneofDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::OneofOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -9677,7 +9427,7 @@
return _internal_has_name();
}
inline void EnumDescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& EnumDescriptorProto::name() const {
@@ -9697,31 +9447,31 @@
}
inline void EnumDescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void EnumDescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumDescriptorProto.name)
}
inline void EnumDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.name)
}
inline void EnumDescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.name)
}
inline std::string* EnumDescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* EnumDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name)
@@ -9729,7 +9479,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void EnumDescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -9738,26 +9488,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.name)
}
inline std::string* EnumDescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumDescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void EnumDescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.name)
}
@@ -9822,9 +9572,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options)
return _internal_options();
}
+inline void EnumDescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::EnumOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000002u;
+ } else {
+ _has_bits_[0] &= ~0x00000002u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000002u;
+ PROTOBUF_NAMESPACE_ID::EnumOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -9839,7 +9604,7 @@
inline PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000002u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::EnumOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::EnumOptions>(GetArena());
options_ = p;
}
return options_;
@@ -9849,7 +9614,7 @@
return _internal_mutable_options();
}
inline void EnumDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::EnumOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -9994,7 +9759,7 @@
return _internal_has_name();
}
inline void EnumValueDescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& EnumValueDescriptorProto::name() const {
@@ -10014,31 +9779,31 @@
}
inline void EnumValueDescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void EnumValueDescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumValueDescriptorProto.name)
}
inline void EnumValueDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumValueDescriptorProto.name)
}
inline void EnumValueDescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValueDescriptorProto.name)
}
inline std::string* EnumValueDescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* EnumValueDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name)
@@ -10046,7 +9811,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void EnumValueDescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -10055,26 +9820,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.name)
}
inline std::string* EnumValueDescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValueDescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.name)
}
@@ -10128,9 +9893,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options)
return _internal_options();
}
+inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::EnumValueOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000002u;
+ } else {
+ _has_bits_[0] &= ~0x00000002u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000002u;
+ PROTOBUF_NAMESPACE_ID::EnumValueOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -10145,7 +9925,7 @@
inline PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000002u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::EnumValueOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::EnumValueOptions>(GetArena());
options_ = p;
}
return options_;
@@ -10155,7 +9935,7 @@
return _internal_mutable_options();
}
inline void EnumValueDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::EnumValueOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -10187,7 +9967,7 @@
return _internal_has_name();
}
inline void ServiceDescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& ServiceDescriptorProto::name() const {
@@ -10207,31 +9987,31 @@
}
inline void ServiceDescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void ServiceDescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.ServiceDescriptorProto.name)
}
inline void ServiceDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.ServiceDescriptorProto.name)
}
inline void ServiceDescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.ServiceDescriptorProto.name)
}
inline std::string* ServiceDescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* ServiceDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name)
@@ -10239,7 +10019,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void ServiceDescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -10248,26 +10028,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.name)
}
inline std::string* ServiceDescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.ServiceDescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void ServiceDescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.name)
}
@@ -10332,9 +10112,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options)
return _internal_options();
}
+inline void ServiceDescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::ServiceOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000002u;
+ } else {
+ _has_bits_[0] &= ~0x00000002u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000002u;
+ PROTOBUF_NAMESPACE_ID::ServiceOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -10349,7 +10144,7 @@
inline PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000002u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::ServiceOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::ServiceOptions>(GetArena());
options_ = p;
}
return options_;
@@ -10359,7 +10154,7 @@
return _internal_mutable_options();
}
inline void ServiceDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::ServiceOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -10391,7 +10186,7 @@
return _internal_has_name();
}
inline void MethodDescriptorProto::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& MethodDescriptorProto::name() const {
@@ -10411,31 +10206,31 @@
}
inline void MethodDescriptorProto::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void MethodDescriptorProto::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.name)
}
inline void MethodDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.name)
}
inline void MethodDescriptorProto::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.name)
}
inline std::string* MethodDescriptorProto::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* MethodDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name)
@@ -10443,7 +10238,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void MethodDescriptorProto::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -10452,26 +10247,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.name)
}
inline std::string* MethodDescriptorProto::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void MethodDescriptorProto::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.name)
}
@@ -10484,7 +10279,7 @@
return _internal_has_input_type();
}
inline void MethodDescriptorProto::clear_input_type() {
- input_type_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ input_type_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& MethodDescriptorProto::input_type() const {
@@ -10504,31 +10299,31 @@
}
inline void MethodDescriptorProto::_internal_set_input_type(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
- input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void MethodDescriptorProto::set_input_type(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
input_type_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.input_type)
}
inline void MethodDescriptorProto::set_input_type(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.input_type)
}
inline void MethodDescriptorProto::set_input_type(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
input_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.input_type)
}
inline std::string* MethodDescriptorProto::_internal_mutable_input_type() {
_has_bits_[0] |= 0x00000002u;
- return input_type_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return input_type_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* MethodDescriptorProto::release_input_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type)
@@ -10536,7 +10331,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
- return input_type_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return input_type_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void MethodDescriptorProto::set_allocated_input_type(std::string* input_type) {
if (input_type != nullptr) {
@@ -10545,26 +10340,26 @@
_has_bits_[0] &= ~0x00000002u;
}
input_type_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), input_type,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.input_type)
}
inline std::string* MethodDescriptorProto::unsafe_arena_release_input_type() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.input_type)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000002u;
return input_type_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void MethodDescriptorProto::unsafe_arena_set_allocated_input_type(
std::string* input_type) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (input_type != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
input_type_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- input_type, GetArenaNoVirtual());
+ input_type, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.input_type)
}
@@ -10577,7 +10372,7 @@
return _internal_has_output_type();
}
inline void MethodDescriptorProto::clear_output_type() {
- output_type_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ output_type_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& MethodDescriptorProto::output_type() const {
@@ -10597,31 +10392,31 @@
}
inline void MethodDescriptorProto::_internal_set_output_type(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
- output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void MethodDescriptorProto::set_output_type(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
output_type_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.output_type)
}
inline void MethodDescriptorProto::set_output_type(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.output_type)
}
inline void MethodDescriptorProto::set_output_type(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
output_type_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.output_type)
}
inline std::string* MethodDescriptorProto::_internal_mutable_output_type() {
_has_bits_[0] |= 0x00000004u;
- return output_type_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return output_type_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* MethodDescriptorProto::release_output_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type)
@@ -10629,7 +10424,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
- return output_type_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return output_type_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void MethodDescriptorProto::set_allocated_output_type(std::string* output_type) {
if (output_type != nullptr) {
@@ -10638,26 +10433,26 @@
_has_bits_[0] &= ~0x00000004u;
}
output_type_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), output_type,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.output_type)
}
inline std::string* MethodDescriptorProto::unsafe_arena_release_output_type() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.output_type)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000004u;
return output_type_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void MethodDescriptorProto::unsafe_arena_set_allocated_output_type(
std::string* output_type) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (output_type != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
output_type_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- output_type, GetArenaNoVirtual());
+ output_type, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.output_type)
}
@@ -10683,9 +10478,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options)
return _internal_options();
}
+inline void MethodDescriptorProto::unsafe_arena_set_allocated_options(
+ PROTOBUF_NAMESPACE_ID::MethodOptions* options) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_);
+ }
+ options_ = options;
+ if (options) {
+ _has_bits_[0] |= 0x00000008u;
+ } else {
+ _has_bits_[0] &= ~0x00000008u;
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.options)
+}
inline PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::release_options() {
- auto temp = unsafe_arena_release_options();
- if (GetArenaNoVirtual() != nullptr) {
+ _has_bits_[0] &= ~0x00000008u;
+ PROTOBUF_NAMESPACE_ID::MethodOptions* temp = options_;
+ options_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -10700,7 +10510,7 @@
inline PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::_internal_mutable_options() {
_has_bits_[0] |= 0x00000008u;
if (options_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::MethodOptions>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::MethodOptions>(GetArena());
options_ = p;
}
return options_;
@@ -10710,7 +10520,7 @@
return _internal_mutable_options();
}
inline void MethodDescriptorProto::set_allocated_options(PROTOBUF_NAMESPACE_ID::MethodOptions* options) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete options_;
}
@@ -10798,7 +10608,7 @@
return _internal_has_java_package();
}
inline void FileOptions::clear_java_package() {
- java_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ java_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& FileOptions::java_package() const {
@@ -10818,31 +10628,31 @@
}
inline void FileOptions::_internal_set_java_package(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_java_package(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
java_package_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_package)
}
inline void FileOptions::set_java_package(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_package)
}
inline void FileOptions::set_java_package(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
java_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_package)
}
inline std::string* FileOptions::_internal_mutable_java_package() {
_has_bits_[0] |= 0x00000001u;
- return java_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return java_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_java_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package)
@@ -10850,7 +10660,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return java_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return java_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_java_package(std::string* java_package) {
if (java_package != nullptr) {
@@ -10859,26 +10669,26 @@
_has_bits_[0] &= ~0x00000001u;
}
java_package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), java_package,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_package)
}
inline std::string* FileOptions::unsafe_arena_release_java_package() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.java_package)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return java_package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_java_package(
std::string* java_package) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (java_package != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
java_package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- java_package, GetArenaNoVirtual());
+ java_package, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.java_package)
}
@@ -10891,7 +10701,7 @@
return _internal_has_java_outer_classname();
}
inline void FileOptions::clear_java_outer_classname() {
- java_outer_classname_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ java_outer_classname_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& FileOptions::java_outer_classname() const {
@@ -10911,31 +10721,31 @@
}
inline void FileOptions::_internal_set_java_outer_classname(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
- java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_java_outer_classname(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
java_outer_classname_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_outer_classname)
}
inline void FileOptions::set_java_outer_classname(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_outer_classname)
}
inline void FileOptions::set_java_outer_classname(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
java_outer_classname_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_outer_classname)
}
inline std::string* FileOptions::_internal_mutable_java_outer_classname() {
_has_bits_[0] |= 0x00000002u;
- return java_outer_classname_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return java_outer_classname_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_java_outer_classname() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname)
@@ -10943,7 +10753,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
- return java_outer_classname_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return java_outer_classname_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_java_outer_classname(std::string* java_outer_classname) {
if (java_outer_classname != nullptr) {
@@ -10952,26 +10762,26 @@
_has_bits_[0] &= ~0x00000002u;
}
java_outer_classname_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), java_outer_classname,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_outer_classname)
}
inline std::string* FileOptions::unsafe_arena_release_java_outer_classname() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.java_outer_classname)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000002u;
return java_outer_classname_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_java_outer_classname(
std::string* java_outer_classname) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (java_outer_classname != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
java_outer_classname_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- java_outer_classname, GetArenaNoVirtual());
+ java_outer_classname, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.java_outer_classname)
}
@@ -11061,7 +10871,7 @@
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
inline bool FileOptions::_internal_has_optimize_for() const {
- bool value = (_has_bits_[0] & 0x00080000u) != 0;
+ bool value = (_has_bits_[0] & 0x00040000u) != 0;
return value;
}
inline bool FileOptions::has_optimize_for() const {
@@ -11069,7 +10879,7 @@
}
inline void FileOptions::clear_optimize_for() {
optimize_for_ = 1;
- _has_bits_[0] &= ~0x00080000u;
+ _has_bits_[0] &= ~0x00040000u;
}
inline PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode FileOptions::_internal_optimize_for() const {
return static_cast< PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode >(optimize_for_);
@@ -11080,7 +10890,7 @@
}
inline void FileOptions::_internal_set_optimize_for(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode value) {
assert(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode_IsValid(value));
- _has_bits_[0] |= 0x00080000u;
+ _has_bits_[0] |= 0x00040000u;
optimize_for_ = value;
}
inline void FileOptions::set_optimize_for(PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode value) {
@@ -11097,7 +10907,7 @@
return _internal_has_go_package();
}
inline void FileOptions::clear_go_package() {
- go_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ go_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& FileOptions::go_package() const {
@@ -11117,31 +10927,31 @@
}
inline void FileOptions::_internal_set_go_package(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
- go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_go_package(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
go_package_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.go_package)
}
inline void FileOptions::set_go_package(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.go_package)
}
inline void FileOptions::set_go_package(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
go_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.go_package)
}
inline std::string* FileOptions::_internal_mutable_go_package() {
_has_bits_[0] |= 0x00000004u;
- return go_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return go_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_go_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package)
@@ -11149,7 +10959,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
- return go_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return go_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_go_package(std::string* go_package) {
if (go_package != nullptr) {
@@ -11158,26 +10968,26 @@
_has_bits_[0] &= ~0x00000004u;
}
go_package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), go_package,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.go_package)
}
inline std::string* FileOptions::unsafe_arena_release_go_package() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.go_package)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000004u;
return go_package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_go_package(
std::string* go_package) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (go_package != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
go_package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- go_package, GetArenaNoVirtual());
+ go_package, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.go_package)
}
@@ -11321,17 +11131,17 @@
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.deprecated)
}
-// optional bool cc_enable_arenas = 31 [default = false];
+// optional bool cc_enable_arenas = 31 [default = true];
inline bool FileOptions::_internal_has_cc_enable_arenas() const {
- bool value = (_has_bits_[0] & 0x00040000u) != 0;
+ bool value = (_has_bits_[0] & 0x00080000u) != 0;
return value;
}
inline bool FileOptions::has_cc_enable_arenas() const {
return _internal_has_cc_enable_arenas();
}
inline void FileOptions::clear_cc_enable_arenas() {
- cc_enable_arenas_ = false;
- _has_bits_[0] &= ~0x00040000u;
+ cc_enable_arenas_ = true;
+ _has_bits_[0] &= ~0x00080000u;
}
inline bool FileOptions::_internal_cc_enable_arenas() const {
return cc_enable_arenas_;
@@ -11341,7 +11151,7 @@
return _internal_cc_enable_arenas();
}
inline void FileOptions::_internal_set_cc_enable_arenas(bool value) {
- _has_bits_[0] |= 0x00040000u;
+ _has_bits_[0] |= 0x00080000u;
cc_enable_arenas_ = value;
}
inline void FileOptions::set_cc_enable_arenas(bool value) {
@@ -11358,7 +11168,7 @@
return _internal_has_objc_class_prefix();
}
inline void FileOptions::clear_objc_class_prefix() {
- objc_class_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ objc_class_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000008u;
}
inline const std::string& FileOptions::objc_class_prefix() const {
@@ -11378,31 +11188,31 @@
}
inline void FileOptions::_internal_set_objc_class_prefix(const std::string& value) {
_has_bits_[0] |= 0x00000008u;
- objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_objc_class_prefix(std::string&& value) {
_has_bits_[0] |= 0x00000008u;
objc_class_prefix_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.objc_class_prefix)
}
inline void FileOptions::set_objc_class_prefix(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000008u;
objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.objc_class_prefix)
}
inline void FileOptions::set_objc_class_prefix(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000008u;
objc_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.objc_class_prefix)
}
inline std::string* FileOptions::_internal_mutable_objc_class_prefix() {
_has_bits_[0] |= 0x00000008u;
- return objc_class_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return objc_class_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_objc_class_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix)
@@ -11410,7 +11220,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000008u;
- return objc_class_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return objc_class_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_objc_class_prefix(std::string* objc_class_prefix) {
if (objc_class_prefix != nullptr) {
@@ -11419,26 +11229,26 @@
_has_bits_[0] &= ~0x00000008u;
}
objc_class_prefix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), objc_class_prefix,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.objc_class_prefix)
}
inline std::string* FileOptions::unsafe_arena_release_objc_class_prefix() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.objc_class_prefix)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000008u;
return objc_class_prefix_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_objc_class_prefix(
std::string* objc_class_prefix) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (objc_class_prefix != nullptr) {
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
objc_class_prefix_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- objc_class_prefix, GetArenaNoVirtual());
+ objc_class_prefix, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.objc_class_prefix)
}
@@ -11451,7 +11261,7 @@
return _internal_has_csharp_namespace();
}
inline void FileOptions::clear_csharp_namespace() {
- csharp_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ csharp_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000010u;
}
inline const std::string& FileOptions::csharp_namespace() const {
@@ -11471,31 +11281,31 @@
}
inline void FileOptions::_internal_set_csharp_namespace(const std::string& value) {
_has_bits_[0] |= 0x00000010u;
- csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_csharp_namespace(std::string&& value) {
_has_bits_[0] |= 0x00000010u;
csharp_namespace_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.csharp_namespace)
}
inline void FileOptions::set_csharp_namespace(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000010u;
csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.csharp_namespace)
}
inline void FileOptions::set_csharp_namespace(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000010u;
csharp_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.csharp_namespace)
}
inline std::string* FileOptions::_internal_mutable_csharp_namespace() {
_has_bits_[0] |= 0x00000010u;
- return csharp_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return csharp_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_csharp_namespace() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace)
@@ -11503,7 +11313,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000010u;
- return csharp_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return csharp_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_csharp_namespace(std::string* csharp_namespace) {
if (csharp_namespace != nullptr) {
@@ -11512,26 +11322,26 @@
_has_bits_[0] &= ~0x00000010u;
}
csharp_namespace_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), csharp_namespace,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.csharp_namespace)
}
inline std::string* FileOptions::unsafe_arena_release_csharp_namespace() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.csharp_namespace)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000010u;
return csharp_namespace_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_csharp_namespace(
std::string* csharp_namespace) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (csharp_namespace != nullptr) {
_has_bits_[0] |= 0x00000010u;
} else {
_has_bits_[0] &= ~0x00000010u;
}
csharp_namespace_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- csharp_namespace, GetArenaNoVirtual());
+ csharp_namespace, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.csharp_namespace)
}
@@ -11544,7 +11354,7 @@
return _internal_has_swift_prefix();
}
inline void FileOptions::clear_swift_prefix() {
- swift_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ swift_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000020u;
}
inline const std::string& FileOptions::swift_prefix() const {
@@ -11564,31 +11374,31 @@
}
inline void FileOptions::_internal_set_swift_prefix(const std::string& value) {
_has_bits_[0] |= 0x00000020u;
- swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_swift_prefix(std::string&& value) {
_has_bits_[0] |= 0x00000020u;
swift_prefix_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.swift_prefix)
}
inline void FileOptions::set_swift_prefix(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000020u;
swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.swift_prefix)
}
inline void FileOptions::set_swift_prefix(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000020u;
swift_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.swift_prefix)
}
inline std::string* FileOptions::_internal_mutable_swift_prefix() {
_has_bits_[0] |= 0x00000020u;
- return swift_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return swift_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_swift_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix)
@@ -11596,7 +11406,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000020u;
- return swift_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return swift_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_swift_prefix(std::string* swift_prefix) {
if (swift_prefix != nullptr) {
@@ -11605,26 +11415,26 @@
_has_bits_[0] &= ~0x00000020u;
}
swift_prefix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), swift_prefix,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.swift_prefix)
}
inline std::string* FileOptions::unsafe_arena_release_swift_prefix() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.swift_prefix)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000020u;
return swift_prefix_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_swift_prefix(
std::string* swift_prefix) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (swift_prefix != nullptr) {
_has_bits_[0] |= 0x00000020u;
} else {
_has_bits_[0] &= ~0x00000020u;
}
swift_prefix_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- swift_prefix, GetArenaNoVirtual());
+ swift_prefix, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.swift_prefix)
}
@@ -11637,7 +11447,7 @@
return _internal_has_php_class_prefix();
}
inline void FileOptions::clear_php_class_prefix() {
- php_class_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ php_class_prefix_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000040u;
}
inline const std::string& FileOptions::php_class_prefix() const {
@@ -11657,31 +11467,31 @@
}
inline void FileOptions::_internal_set_php_class_prefix(const std::string& value) {
_has_bits_[0] |= 0x00000040u;
- php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_php_class_prefix(std::string&& value) {
_has_bits_[0] |= 0x00000040u;
php_class_prefix_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_class_prefix)
}
inline void FileOptions::set_php_class_prefix(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000040u;
php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_class_prefix)
}
inline void FileOptions::set_php_class_prefix(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000040u;
php_class_prefix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_class_prefix)
}
inline std::string* FileOptions::_internal_mutable_php_class_prefix() {
_has_bits_[0] |= 0x00000040u;
- return php_class_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return php_class_prefix_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_php_class_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_class_prefix)
@@ -11689,7 +11499,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000040u;
- return php_class_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return php_class_prefix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_php_class_prefix(std::string* php_class_prefix) {
if (php_class_prefix != nullptr) {
@@ -11698,26 +11508,26 @@
_has_bits_[0] &= ~0x00000040u;
}
php_class_prefix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_class_prefix,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_class_prefix)
}
inline std::string* FileOptions::unsafe_arena_release_php_class_prefix() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_class_prefix)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000040u;
return php_class_prefix_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_php_class_prefix(
std::string* php_class_prefix) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (php_class_prefix != nullptr) {
_has_bits_[0] |= 0x00000040u;
} else {
_has_bits_[0] &= ~0x00000040u;
}
php_class_prefix_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- php_class_prefix, GetArenaNoVirtual());
+ php_class_prefix, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_class_prefix)
}
@@ -11730,7 +11540,7 @@
return _internal_has_php_namespace();
}
inline void FileOptions::clear_php_namespace() {
- php_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ php_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000080u;
}
inline const std::string& FileOptions::php_namespace() const {
@@ -11750,31 +11560,31 @@
}
inline void FileOptions::_internal_set_php_namespace(const std::string& value) {
_has_bits_[0] |= 0x00000080u;
- php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_php_namespace(std::string&& value) {
_has_bits_[0] |= 0x00000080u;
php_namespace_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_namespace)
}
inline void FileOptions::set_php_namespace(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000080u;
php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_namespace)
}
inline void FileOptions::set_php_namespace(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000080u;
php_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_namespace)
}
inline std::string* FileOptions::_internal_mutable_php_namespace() {
_has_bits_[0] |= 0x00000080u;
- return php_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return php_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_php_namespace() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_namespace)
@@ -11782,7 +11592,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000080u;
- return php_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return php_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_php_namespace(std::string* php_namespace) {
if (php_namespace != nullptr) {
@@ -11791,26 +11601,26 @@
_has_bits_[0] &= ~0x00000080u;
}
php_namespace_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_namespace,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_namespace)
}
inline std::string* FileOptions::unsafe_arena_release_php_namespace() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_namespace)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000080u;
return php_namespace_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_php_namespace(
std::string* php_namespace) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (php_namespace != nullptr) {
_has_bits_[0] |= 0x00000080u;
} else {
_has_bits_[0] &= ~0x00000080u;
}
php_namespace_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- php_namespace, GetArenaNoVirtual());
+ php_namespace, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_namespace)
}
@@ -11823,7 +11633,7 @@
return _internal_has_php_metadata_namespace();
}
inline void FileOptions::clear_php_metadata_namespace() {
- php_metadata_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ php_metadata_namespace_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000100u;
}
inline const std::string& FileOptions::php_metadata_namespace() const {
@@ -11843,31 +11653,31 @@
}
inline void FileOptions::_internal_set_php_metadata_namespace(const std::string& value) {
_has_bits_[0] |= 0x00000100u;
- php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_php_metadata_namespace(std::string&& value) {
_has_bits_[0] |= 0x00000100u;
php_metadata_namespace_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_metadata_namespace)
}
inline void FileOptions::set_php_metadata_namespace(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000100u;
php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_metadata_namespace)
}
inline void FileOptions::set_php_metadata_namespace(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000100u;
php_metadata_namespace_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.php_metadata_namespace)
}
inline std::string* FileOptions::_internal_mutable_php_metadata_namespace() {
_has_bits_[0] |= 0x00000100u;
- return php_metadata_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return php_metadata_namespace_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_php_metadata_namespace() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_metadata_namespace)
@@ -11875,7 +11685,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000100u;
- return php_metadata_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return php_metadata_namespace_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_php_metadata_namespace(std::string* php_metadata_namespace) {
if (php_metadata_namespace != nullptr) {
@@ -11884,26 +11694,26 @@
_has_bits_[0] &= ~0x00000100u;
}
php_metadata_namespace_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), php_metadata_namespace,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_metadata_namespace)
}
inline std::string* FileOptions::unsafe_arena_release_php_metadata_namespace() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_metadata_namespace)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000100u;
return php_metadata_namespace_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_php_metadata_namespace(
std::string* php_metadata_namespace) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (php_metadata_namespace != nullptr) {
_has_bits_[0] |= 0x00000100u;
} else {
_has_bits_[0] &= ~0x00000100u;
}
php_metadata_namespace_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- php_metadata_namespace, GetArenaNoVirtual());
+ php_metadata_namespace, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.php_metadata_namespace)
}
@@ -11916,7 +11726,7 @@
return _internal_has_ruby_package();
}
inline void FileOptions::clear_ruby_package() {
- ruby_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ ruby_package_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000200u;
}
inline const std::string& FileOptions::ruby_package() const {
@@ -11936,31 +11746,31 @@
}
inline void FileOptions::_internal_set_ruby_package(const std::string& value) {
_has_bits_[0] |= 0x00000200u;
- ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void FileOptions::set_ruby_package(std::string&& value) {
_has_bits_[0] |= 0x00000200u;
ruby_package_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.ruby_package)
}
inline void FileOptions::set_ruby_package(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000200u;
ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.ruby_package)
}
inline void FileOptions::set_ruby_package(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000200u;
ruby_package_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.ruby_package)
}
inline std::string* FileOptions::_internal_mutable_ruby_package() {
_has_bits_[0] |= 0x00000200u;
- return ruby_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return ruby_package_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* FileOptions::release_ruby_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.ruby_package)
@@ -11968,7 +11778,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000200u;
- return ruby_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return ruby_package_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void FileOptions::set_allocated_ruby_package(std::string* ruby_package) {
if (ruby_package != nullptr) {
@@ -11977,26 +11787,26 @@
_has_bits_[0] &= ~0x00000200u;
}
ruby_package_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ruby_package,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.ruby_package)
}
inline std::string* FileOptions::unsafe_arena_release_ruby_package() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.ruby_package)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000200u;
return ruby_package_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void FileOptions::unsafe_arena_set_allocated_ruby_package(
std::string* ruby_package) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (ruby_package != nullptr) {
_has_bits_[0] |= 0x00000200u;
} else {
_has_bits_[0] &= ~0x00000200u;
}
ruby_package_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ruby_package, GetArenaNoVirtual());
+ ruby_package, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileOptions.ruby_package)
}
@@ -12804,7 +12614,7 @@
return _internal_has_name_part();
}
inline void UninterpretedOption_NamePart::clear_name_part() {
- name_part_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_part_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& UninterpretedOption_NamePart::name_part() const {
@@ -12824,31 +12634,31 @@
}
inline void UninterpretedOption_NamePart::_internal_set_name_part(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void UninterpretedOption_NamePart::set_name_part(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_part_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.NamePart.name_part)
}
inline void UninterpretedOption_NamePart::set_name_part(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.NamePart.name_part)
}
inline void UninterpretedOption_NamePart::set_name_part(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_part_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.NamePart.name_part)
}
inline std::string* UninterpretedOption_NamePart::_internal_mutable_name_part() {
_has_bits_[0] |= 0x00000001u;
- return name_part_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_part_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* UninterpretedOption_NamePart::release_name_part() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part)
@@ -12856,7 +12666,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return name_part_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_part_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UninterpretedOption_NamePart::set_allocated_name_part(std::string* name_part) {
if (name_part != nullptr) {
@@ -12865,26 +12675,26 @@
_has_bits_[0] &= ~0x00000001u;
}
name_part_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name_part,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part)
}
inline std::string* UninterpretedOption_NamePart::unsafe_arena_release_name_part() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.NamePart.name_part)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return name_part_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void UninterpretedOption_NamePart::unsafe_arena_set_allocated_name_part(
std::string* name_part) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name_part != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_part_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name_part, GetArenaNoVirtual());
+ name_part, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part)
}
@@ -12968,7 +12778,7 @@
return _internal_has_identifier_value();
}
inline void UninterpretedOption::clear_identifier_value() {
- identifier_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ identifier_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& UninterpretedOption::identifier_value() const {
@@ -12988,31 +12798,31 @@
}
inline void UninterpretedOption::_internal_set_identifier_value(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void UninterpretedOption::set_identifier_value(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
identifier_value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.identifier_value)
}
inline void UninterpretedOption::set_identifier_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.identifier_value)
}
inline void UninterpretedOption::set_identifier_value(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
identifier_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.identifier_value)
}
inline std::string* UninterpretedOption::_internal_mutable_identifier_value() {
_has_bits_[0] |= 0x00000001u;
- return identifier_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return identifier_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* UninterpretedOption::release_identifier_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value)
@@ -13020,7 +12830,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return identifier_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return identifier_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UninterpretedOption::set_allocated_identifier_value(std::string* identifier_value) {
if (identifier_value != nullptr) {
@@ -13029,26 +12839,26 @@
_has_bits_[0] &= ~0x00000001u;
}
identifier_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), identifier_value,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.identifier_value)
}
inline std::string* UninterpretedOption::unsafe_arena_release_identifier_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.identifier_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return identifier_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void UninterpretedOption::unsafe_arena_set_allocated_identifier_value(
std::string* identifier_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (identifier_value != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
identifier_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- identifier_value, GetArenaNoVirtual());
+ identifier_value, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.identifier_value)
}
@@ -13145,7 +12955,7 @@
return _internal_has_string_value();
}
inline void UninterpretedOption::clear_string_value() {
- string_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ string_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& UninterpretedOption::string_value() const {
@@ -13165,31 +12975,31 @@
}
inline void UninterpretedOption::_internal_set_string_value(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
- string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void UninterpretedOption::set_string_value(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
string_value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.string_value)
}
inline void UninterpretedOption::set_string_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.string_value)
}
inline void UninterpretedOption::set_string_value(const void* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.string_value)
}
inline std::string* UninterpretedOption::_internal_mutable_string_value() {
_has_bits_[0] |= 0x00000002u;
- return string_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return string_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* UninterpretedOption::release_string_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value)
@@ -13197,7 +13007,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
- return string_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return string_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UninterpretedOption::set_allocated_string_value(std::string* string_value) {
if (string_value != nullptr) {
@@ -13206,26 +13016,26 @@
_has_bits_[0] &= ~0x00000002u;
}
string_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), string_value,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.string_value)
}
inline std::string* UninterpretedOption::unsafe_arena_release_string_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.string_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000002u;
return string_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void UninterpretedOption::unsafe_arena_set_allocated_string_value(
std::string* string_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (string_value != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
string_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- string_value, GetArenaNoVirtual());
+ string_value, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.string_value)
}
@@ -13238,7 +13048,7 @@
return _internal_has_aggregate_value();
}
inline void UninterpretedOption::clear_aggregate_value() {
- aggregate_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ aggregate_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& UninterpretedOption::aggregate_value() const {
@@ -13258,31 +13068,31 @@
}
inline void UninterpretedOption::_internal_set_aggregate_value(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
- aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void UninterpretedOption::set_aggregate_value(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
aggregate_value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.aggregate_value)
}
inline void UninterpretedOption::set_aggregate_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.aggregate_value)
}
inline void UninterpretedOption::set_aggregate_value(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
aggregate_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.aggregate_value)
}
inline std::string* UninterpretedOption::_internal_mutable_aggregate_value() {
_has_bits_[0] |= 0x00000004u;
- return aggregate_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return aggregate_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* UninterpretedOption::release_aggregate_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value)
@@ -13290,7 +13100,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
- return aggregate_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return aggregate_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void UninterpretedOption::set_allocated_aggregate_value(std::string* aggregate_value) {
if (aggregate_value != nullptr) {
@@ -13299,26 +13109,26 @@
_has_bits_[0] &= ~0x00000004u;
}
aggregate_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), aggregate_value,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.aggregate_value)
}
inline std::string* UninterpretedOption::unsafe_arena_release_aggregate_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.UninterpretedOption.aggregate_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000004u;
return aggregate_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void UninterpretedOption::unsafe_arena_set_allocated_aggregate_value(
std::string* aggregate_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (aggregate_value != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
aggregate_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- aggregate_value, GetArenaNoVirtual());
+ aggregate_value, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.UninterpretedOption.aggregate_value)
}
@@ -13429,7 +13239,7 @@
return _internal_has_leading_comments();
}
inline void SourceCodeInfo_Location::clear_leading_comments() {
- leading_comments_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ leading_comments_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& SourceCodeInfo_Location::leading_comments() const {
@@ -13449,31 +13259,31 @@
}
inline void SourceCodeInfo_Location::_internal_set_leading_comments(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void SourceCodeInfo_Location::set_leading_comments(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
leading_comments_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
inline void SourceCodeInfo_Location::set_leading_comments(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
inline void SourceCodeInfo_Location::set_leading_comments(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
leading_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
inline std::string* SourceCodeInfo_Location::_internal_mutable_leading_comments() {
_has_bits_[0] |= 0x00000001u;
- return leading_comments_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return leading_comments_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* SourceCodeInfo_Location::release_leading_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments)
@@ -13481,7 +13291,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return leading_comments_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return leading_comments_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void SourceCodeInfo_Location::set_allocated_leading_comments(std::string* leading_comments) {
if (leading_comments != nullptr) {
@@ -13490,26 +13300,26 @@
_has_bits_[0] &= ~0x00000001u;
}
leading_comments_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), leading_comments,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
inline std::string* SourceCodeInfo_Location::unsafe_arena_release_leading_comments() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.SourceCodeInfo.Location.leading_comments)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return leading_comments_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_leading_comments(
std::string* leading_comments) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (leading_comments != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
leading_comments_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- leading_comments, GetArenaNoVirtual());
+ leading_comments, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
@@ -13522,7 +13332,7 @@
return _internal_has_trailing_comments();
}
inline void SourceCodeInfo_Location::clear_trailing_comments() {
- trailing_comments_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ trailing_comments_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& SourceCodeInfo_Location::trailing_comments() const {
@@ -13542,31 +13352,31 @@
}
inline void SourceCodeInfo_Location::_internal_set_trailing_comments(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
- trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void SourceCodeInfo_Location::set_trailing_comments(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
trailing_comments_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
inline void SourceCodeInfo_Location::set_trailing_comments(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
inline void SourceCodeInfo_Location::set_trailing_comments(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
trailing_comments_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
inline std::string* SourceCodeInfo_Location::_internal_mutable_trailing_comments() {
_has_bits_[0] |= 0x00000002u;
- return trailing_comments_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return trailing_comments_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* SourceCodeInfo_Location::release_trailing_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments)
@@ -13574,7 +13384,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
- return trailing_comments_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return trailing_comments_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void SourceCodeInfo_Location::set_allocated_trailing_comments(std::string* trailing_comments) {
if (trailing_comments != nullptr) {
@@ -13583,26 +13393,26 @@
_has_bits_[0] &= ~0x00000002u;
}
trailing_comments_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), trailing_comments,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
inline std::string* SourceCodeInfo_Location::unsafe_arena_release_trailing_comments() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.SourceCodeInfo.Location.trailing_comments)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000002u;
return trailing_comments_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_trailing_comments(
std::string* trailing_comments) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (trailing_comments != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
trailing_comments_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- trailing_comments, GetArenaNoVirtual());
+ trailing_comments, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
@@ -13783,7 +13593,7 @@
return _internal_has_source_file();
}
inline void GeneratedCodeInfo_Annotation::clear_source_file() {
- source_file_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ source_file_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& GeneratedCodeInfo_Annotation::source_file() const {
@@ -13803,31 +13613,31 @@
}
inline void GeneratedCodeInfo_Annotation::_internal_set_source_file(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
- source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void GeneratedCodeInfo_Annotation::set_source_file(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
source_file_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
source_file_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
inline std::string* GeneratedCodeInfo_Annotation::_internal_mutable_source_file() {
_has_bits_[0] |= 0x00000001u;
- return source_file_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return source_file_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* GeneratedCodeInfo_Annotation::release_source_file() {
// @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
@@ -13835,7 +13645,7 @@
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
- return source_file_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return source_file_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(std::string* source_file) {
if (source_file != nullptr) {
@@ -13844,26 +13654,26 @@
_has_bits_[0] &= ~0x00000001u;
}
source_file_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), source_file,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
inline std::string* GeneratedCodeInfo_Annotation::unsafe_arena_release_source_file() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
_has_bits_[0] &= ~0x00000001u;
return source_file_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void GeneratedCodeInfo_Annotation::unsafe_arena_set_allocated_source_file(
std::string* source_file) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (source_file != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
source_file_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- source_file, GetArenaNoVirtual());
+ source_file, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto
index a2102d7..d29fdec 100644
--- a/src/google/protobuf/descriptor.proto
+++ b/src/google/protobuf/descriptor.proto
@@ -129,6 +129,7 @@
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
+
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
@@ -212,6 +213,29 @@
optional string json_name = 10;
optional FieldOptions options = 8;
+
+ // If true, this is a proto3 "optional". When a proto3 field is optional, it
+ // tracks presence regardless of field type.
+ //
+ // When proto3_optional is true, this field must be belong to a oneof to
+ // signal to old proto3 clients that presence is tracked for this field. This
+ // oneof is known as a "synthetic" oneof, and this field must be its sole
+ // member (each proto3 optional field gets its own synthetic oneof). Synthetic
+ // oneofs exist in the descriptor only, and do not generate any API. Synthetic
+ // oneofs must be ordered after all "real" oneofs.
+ //
+ // For message fields, proto3_optional doesn't create any semantic change,
+ // since non-repeated message fields always track presence. However it still
+ // indicates the semantic detail of whether the user wrote "optional" or not.
+ // This can be useful for round-tripping the .proto file. For consistency we
+ // give message fields a synthetic oneof also, even though it is not required
+ // to track presence. This is especially important because the parser can't
+ // tell if a field is a message or an enum, so it must always create a
+ // synthetic oneof.
+ //
+ // Proto2 optional fields do not set this flag, because they already indicate
+ // optional with `LABEL_OPTIONAL`.
+ optional bool proto3_optional = 17;
}
// Describes a oneof.
@@ -393,7 +417,7 @@
// Enables the use of arenas for the proto messages in this file. This applies
// only to generated classes for C++.
- optional bool cc_enable_arenas = 31 [default = false];
+ optional bool cc_enable_arenas = 31 [default = true];
// Sets the objective c class prefix which is prepended to all objective c
diff --git a/src/google/protobuf/descriptor_database.cc b/src/google/protobuf/descriptor_database.cc
index b613148..256ae48 100644
--- a/src/google/protobuf/descriptor_database.cc
+++ b/src/google/protobuf/descriptor_database.cc
@@ -146,6 +146,53 @@
return true;
}
+namespace {
+
+// Returns true if and only if all characters in the name are alphanumerics,
+// underscores, or periods.
+bool ValidateSymbolName(StringPiece name) {
+ for (char c : name) {
+ // I don't trust ctype.h due to locales. :(
+ if (c != '.' && c != '_' && (c < '0' || c > '9') && (c < 'A' || c > 'Z') &&
+ (c < 'a' || c > 'z')) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// Find the last key in the container which sorts less than or equal to the
+// symbol name. Since upper_bound() returns the *first* key that sorts
+// *greater* than the input, we want the element immediately before that.
+template <typename Container, typename Key>
+typename Container::const_iterator FindLastLessOrEqual(Container* container,
+ const Key& key) {
+ auto iter = container->upper_bound(key);
+ if (iter != container->begin()) --iter;
+ return iter;
+}
+
+// As above, but using std::upper_bound instead.
+template <typename Container, typename Key, typename Cmp>
+typename Container::const_iterator FindLastLessOrEqual(Container* container,
+ const Key& key,
+ const Cmp& cmp) {
+ auto iter = std::upper_bound(container->begin(), container->end(), key, cmp);
+ if (iter != container->begin()) --iter;
+ return iter;
+}
+
+// True if either the arguments are equal or super_symbol identifies a
+// parent symbol of sub_symbol (e.g. "foo.bar" is a parent of
+// "foo.bar.baz", but not a parent of "foo.barbaz").
+bool IsSubSymbol(StringPiece sub_symbol, StringPiece super_symbol) {
+ return sub_symbol == super_symbol ||
+ (HasPrefixString(super_symbol, sub_symbol) &&
+ super_symbol[sub_symbol.size()] == '.');
+}
+
+} // namespace
+
template <typename Value>
bool SimpleDescriptorDatabase::DescriptorIndex<Value>::AddSymbol(
const std::string& name, Value value) {
@@ -161,8 +208,7 @@
// Try to look up the symbol to make sure a super-symbol doesn't already
// exist.
- typename std::map<std::string, Value>::iterator iter =
- FindLastLessOrEqual(name);
+ auto iter = FindLastLessOrEqual(&by_symbol_, name);
if (iter == by_symbol_.end()) {
// Apparently the map is currently empty. Just insert and be done with it.
@@ -252,8 +298,7 @@
template <typename Value>
Value SimpleDescriptorDatabase::DescriptorIndex<Value>::FindSymbol(
const std::string& name) {
- typename std::map<std::string, Value>::iterator iter =
- FindLastLessOrEqual(name);
+ auto iter = FindLastLessOrEqual(&by_symbol_, name);
return (iter != by_symbol_.end() && IsSubSymbol(iter->first, name))
? iter->second
@@ -294,40 +339,6 @@
}
}
-template <typename Value>
-typename std::map<std::string, Value>::iterator
-SimpleDescriptorDatabase::DescriptorIndex<Value>::FindLastLessOrEqual(
- const std::string& name) {
- // Find the last key in the map which sorts less than or equal to the
- // symbol name. Since upper_bound() returns the *first* key that sorts
- // *greater* than the input, we want the element immediately before that.
- typename std::map<std::string, Value>::iterator iter =
- by_symbol_.upper_bound(name);
- if (iter != by_symbol_.begin()) --iter;
- return iter;
-}
-
-template <typename Value>
-bool SimpleDescriptorDatabase::DescriptorIndex<Value>::IsSubSymbol(
- const std::string& sub_symbol, const std::string& super_symbol) {
- return sub_symbol == super_symbol ||
- (HasPrefixString(super_symbol, sub_symbol) &&
- super_symbol[sub_symbol.size()] == '.');
-}
-
-template <typename Value>
-bool SimpleDescriptorDatabase::DescriptorIndex<Value>::ValidateSymbolName(
- const std::string& name) {
- for (int i = 0; i < name.size(); i++) {
- // I don't trust ctype.h due to locales. :(
- if (name[i] != '.' && name[i] != '_' && (name[i] < '0' || name[i] > '9') &&
- (name[i] < 'A' || name[i] > 'Z') && (name[i] < 'a' || name[i] > 'z')) {
- return false;
- }
- }
- return true;
-}
-
// -------------------------------------------------------------------
bool SimpleDescriptorDatabase::Add(const FileDescriptorProto& file) {
@@ -378,18 +389,88 @@
// -------------------------------------------------------------------
-EncodedDescriptorDatabase::EncodedDescriptorDatabase() {}
-EncodedDescriptorDatabase::~EncodedDescriptorDatabase() {
- for (int i = 0; i < files_to_delete_.size(); i++) {
- operator delete(files_to_delete_[i]);
- }
-}
+class EncodedDescriptorDatabase::DescriptorIndex {
+ public:
+ using Value = std::pair<const void*, int>;
+ // Helpers to recursively add particular descriptors and all their contents
+ // to the index.
+ bool AddFile(const FileDescriptorProto& file, Value value);
+
+ Value FindFile(StringPiece filename);
+ Value FindSymbol(StringPiece name);
+ Value FindSymbolOnlyFlat(StringPiece name) const;
+ Value FindExtension(StringPiece containing_type, int field_number);
+ bool FindAllExtensionNumbers(StringPiece containing_type,
+ std::vector<int>* output);
+ void FindAllFileNames(std::vector<std::string>* output) const;
+
+ private:
+ friend class EncodedDescriptorDatabase;
+
+ bool AddSymbol(StringPiece name, Value value);
+ bool AddNestedExtensions(StringPiece filename,
+ const DescriptorProto& message_type, Value value);
+ bool AddExtension(StringPiece filename,
+ const FieldDescriptorProto& field, Value value);
+
+ // All the maps below have two representations:
+ // - a std::set<> where we insert initially.
+ // - a std::vector<> where we flatten the structure on demand.
+ // The initial tree helps avoid O(N) behavior of inserting into a sorted
+ // vector, while the vector reduces the heap requirements of the data
+ // structure.
+
+ void EnsureFlat();
+
+ struct Entry {
+ std::string name;
+ Value data;
+ };
+ struct Compare {
+ bool operator()(const Entry& a, const Entry& b) const {
+ return a.name < b.name;
+ }
+ bool operator()(const Entry& a, StringPiece b) const {
+ return a.name < b;
+ }
+ bool operator()(StringPiece a, const Entry& b) const {
+ return a < b.name;
+ }
+ };
+ std::set<Entry, Compare> by_name_;
+ std::vector<Entry> by_name_flat_;
+ std::set<Entry, Compare> by_symbol_;
+ std::vector<Entry> by_symbol_flat_;
+ struct ExtensionEntry {
+ std::string extendee;
+ int extension_number;
+ Value data;
+ };
+ struct ExtensionCompare {
+ bool operator()(const ExtensionEntry& a, const ExtensionEntry& b) const {
+ return std::tie(a.extendee, a.extension_number) <
+ std::tie(b.extendee, b.extension_number);
+ }
+ bool operator()(const ExtensionEntry& a,
+ std::tuple<StringPiece, int> b) const {
+ return std::tie(a.extendee, a.extension_number) < b;
+ }
+ bool operator()(std::tuple<StringPiece, int> a,
+ const ExtensionEntry& b) const {
+ return a < std::tie(b.extendee, b.extension_number);
+ }
+ };
+ std::set<ExtensionEntry, ExtensionCompare> by_extension_;
+ std::vector<ExtensionEntry> by_extension_flat_;
+};
bool EncodedDescriptorDatabase::Add(const void* encoded_file_descriptor,
int size) {
- FileDescriptorProto file;
- if (file.ParseFromArray(encoded_file_descriptor, size)) {
- return index_.AddFile(file, std::make_pair(encoded_file_descriptor, size));
+ google::protobuf::Arena arena;
+ auto* file = google::protobuf::Arena::CreateMessage<FileDescriptorProto>(&arena);
+ if (file->ParseFromArray(encoded_file_descriptor, size)) {
+ return index_->AddFile(*file,
+ std::make_pair(encoded_file_descriptor, size));
} else {
GOOGLE_LOG(ERROR) << "Invalid file descriptor data passed to "
"EncodedDescriptorDatabase::Add().";
@@ -407,22 +488,22 @@
bool EncodedDescriptorDatabase::FindFileByName(const std::string& filename,
FileDescriptorProto* output) {
- return MaybeParse(index_.FindFile(filename), output);
+ return MaybeParse(index_->FindFile(filename), output);
}
bool EncodedDescriptorDatabase::FindFileContainingSymbol(
const std::string& symbol_name, FileDescriptorProto* output) {
- return MaybeParse(index_.FindSymbol(symbol_name), output);
+ return MaybeParse(index_->FindSymbol(symbol_name), output);
}
bool EncodedDescriptorDatabase::FindNameOfFileContainingSymbol(
const std::string& symbol_name, std::string* output) {
- std::pair<const void*, int> encoded_file = index_.FindSymbol(symbol_name);
+ auto encoded_file = index_->FindSymbol(symbol_name);
if (encoded_file.first == NULL) return false;
// Optimization: The name should be the first field in the encoded message.
// Try to just read it directly.
- io::CodedInputStream input(reinterpret_cast<const uint8*>(encoded_file.first),
+ io::CodedInputStream input(static_cast<const uint8*>(encoded_file.first),
encoded_file.second);
const uint32 kNameTag = internal::WireFormatLite::MakeTag(
@@ -446,18 +527,245 @@
bool EncodedDescriptorDatabase::FindFileContainingExtension(
const std::string& containing_type, int field_number,
FileDescriptorProto* output) {
- return MaybeParse(index_.FindExtension(containing_type, field_number),
+ return MaybeParse(index_->FindExtension(containing_type, field_number),
output);
}
bool EncodedDescriptorDatabase::FindAllExtensionNumbers(
const std::string& extendee_type, std::vector<int>* output) {
- return index_.FindAllExtensionNumbers(extendee_type, output);
+ return index_->FindAllExtensionNumbers(extendee_type, output);
}
+bool EncodedDescriptorDatabase::DescriptorIndex::AddFile(
+ const FileDescriptorProto& file, Value value) {
+ if (!InsertIfNotPresent(&by_name_, Entry{file.name(), value}) ||
+ std::binary_search(by_name_flat_.begin(), by_name_flat_.end(),
+ file.name(), by_name_.key_comp())) {
+ GOOGLE_LOG(ERROR) << "File already exists in database: " << file.name();
+ return false;
+ }
+
+ // We must be careful here -- calling file.package() if file.has_package() is
+ // false could access an uninitialized static-storage variable if we are being
+ // run at startup time.
+ std::string path = file.has_package() ? file.package() : std::string();
+ if (!path.empty()) path += '.';
+
+ for (const auto& message_type : file.message_type()) {
+ if (!AddSymbol(path + message_type.name(), value)) return false;
+ if (!AddNestedExtensions(file.name(), message_type, value)) return false;
+ }
+ for (const auto& enum_type : file.enum_type()) {
+ if (!AddSymbol(path + enum_type.name(), value)) return false;
+ }
+ for (const auto& extension : file.extension()) {
+ if (!AddSymbol(path + extension.name(), value)) return false;
+ if (!AddExtension(file.name(), extension, value)) return false;
+ }
+ for (const auto& service : file.service()) {
+ if (!AddSymbol(path + service.name(), value)) return false;
+ }
+
+ return true;
+}
+
+template <typename Iter, typename Iter2>
+static bool CheckForMutualSubsymbols(StringPiece symbol_name, Iter* iter,
+ Iter2 end) {
+ if (*iter != end) {
+ if (IsSubSymbol((*iter)->name, symbol_name)) {
+ GOOGLE_LOG(ERROR) << "Symbol name \"" << symbol_name
+ << "\" conflicts with the existing symbol \"" << (*iter)->name
+ << "\".";
+ return false;
+ }
+
+ // OK, that worked. Now we have to make sure that no symbol in the map is
+ // a sub-symbol of the one we are inserting. The only symbol which could
+ // be so is the first symbol that is greater than the new symbol. Since
+ // |iter| points at the last symbol that is less than or equal, we just have
+ // to increment it.
+ ++*iter;
+
+ if (*iter != end && IsSubSymbol(symbol_name, (*iter)->name)) {
+ GOOGLE_LOG(ERROR) << "Symbol name \"" << symbol_name
+ << "\" conflicts with the existing symbol \"" << (*iter)->name
+ << "\".";
+ return false;
+ }
+ }
+ return true;
+}
+
+bool EncodedDescriptorDatabase::DescriptorIndex::AddSymbol(
+ StringPiece name, Value value) {
+ // We need to make sure not to violate our map invariant.
+
+ // If the symbol name is invalid it could break our lookup algorithm (which
+ // relies on the fact that '.' sorts before all other characters that are
+ // valid in symbol names).
+ if (!ValidateSymbolName(name)) {
+ GOOGLE_LOG(ERROR) << "Invalid symbol name: " << name;
+ return false;
+ }
+
+ Entry entry = {std::string(name), value};
+
+ auto iter = FindLastLessOrEqual(&by_symbol_, entry);
+ if (!CheckForMutualSubsymbols(name, &iter, by_symbol_.end())) {
+ return false;
+ }
+
+ // Same, but on by_symbol_flat_
+ auto flat_iter =
+ FindLastLessOrEqual(&by_symbol_flat_, name, by_symbol_.key_comp());
+ if (!CheckForMutualSubsymbols(name, &flat_iter, by_symbol_flat_.end())) {
+ return false;
+ }
+
+ // OK, no conflicts.
+
+ // Insert the new symbol using the iterator as a hint, the new entry will
+ // appear immediately before the one the iterator is pointing at.
+ by_symbol_.insert(iter, std::move(entry));
+
+ return true;
+}
+
+bool EncodedDescriptorDatabase::DescriptorIndex::AddNestedExtensions(
+ StringPiece filename, const DescriptorProto& message_type,
+ Value value) {
+ for (const auto& nested_type : message_type.nested_type()) {
+ if (!AddNestedExtensions(filename, nested_type, value)) return false;
+ }
+ for (const auto& extension : message_type.extension()) {
+ if (!AddExtension(filename, extension, value)) return false;
+ }
+ return true;
+}
+
+bool EncodedDescriptorDatabase::DescriptorIndex::AddExtension(
+ StringPiece filename, const FieldDescriptorProto& field,
+ Value value) {
+ if (!field.extendee().empty() && field.extendee()[0] == '.') {
+ // The extension is fully-qualified. We can use it as a lookup key in
+ // the by_symbol_ table.
+ if (!InsertIfNotPresent(&by_extension_,
+ ExtensionEntry{field.extendee().substr(1),
+ field.number(), value}) ||
+ std::binary_search(
+ by_extension_flat_.begin(), by_extension_flat_.end(),
+ std::make_pair(field.extendee().substr(1), field.number()),
+ by_extension_.key_comp())) {
+ GOOGLE_LOG(ERROR) << "Extension conflicts with extension already in database: "
+ "extend "
+ << field.extendee() << " { " << field.name() << " = "
+ << field.number() << " } from:" << filename;
+ return false;
+ }
+ } else {
+ // Not fully-qualified. We can't really do anything here, unfortunately.
+ // We don't consider this an error, though, because the descriptor is
+ // valid.
+ }
+ return true;
+}
+
+std::pair<const void*, int>
+EncodedDescriptorDatabase::DescriptorIndex::FindSymbol(StringPiece name) {
+ EnsureFlat();
+ return FindSymbolOnlyFlat(name);
+}
+
+std::pair<const void*, int>
+EncodedDescriptorDatabase::DescriptorIndex::FindSymbolOnlyFlat(
+ StringPiece name) const {
+ auto iter =
+ FindLastLessOrEqual(&by_symbol_flat_, name, by_symbol_.key_comp());
+
+ return iter != by_symbol_flat_.end() && IsSubSymbol(iter->name, name)
+ ? iter->data
+ : Value();
+}
+
+std::pair<const void*, int>
+EncodedDescriptorDatabase::DescriptorIndex::FindExtension(
+ StringPiece containing_type, int field_number) {
+ EnsureFlat();
+
+ auto it = std::lower_bound(
+ by_extension_flat_.begin(), by_extension_flat_.end(),
+ std::make_tuple(containing_type, field_number), by_extension_.key_comp());
+ return it == by_extension_flat_.end() || it->extendee != containing_type ||
+ it->extension_number != field_number
+ ? std::make_pair(nullptr, 0)
+ : it->data;
+}
+
+template <typename T, typename Less>
+static void MergeIntoFlat(std::set<T, Less>* s, std::vector<T>* flat) {
+ if (s->empty()) return;
+ std::vector<T> new_flat(s->size() + flat->size());
+ std::merge(s->begin(), s->end(), flat->begin(), flat->end(), &new_flat[0],
+ s->key_comp());
+ *flat = std::move(new_flat);
+ s->clear();
+}
+
+void EncodedDescriptorDatabase::DescriptorIndex::EnsureFlat() {
+ // Merge each of the sets into their flat counterpart.
+ MergeIntoFlat(&by_name_, &by_name_flat_);
+ MergeIntoFlat(&by_symbol_, &by_symbol_flat_);
+ MergeIntoFlat(&by_extension_, &by_extension_flat_);
+}
+
+bool EncodedDescriptorDatabase::DescriptorIndex::FindAllExtensionNumbers(
+ StringPiece containing_type, std::vector<int>* output) {
+ EnsureFlat();
+
+ bool success = false;
+ auto it = std::lower_bound(
+ by_extension_flat_.begin(), by_extension_flat_.end(),
+ std::make_tuple(containing_type, 0), by_extension_.key_comp());
+ for (; it != by_extension_flat_.end() && it->extendee == containing_type;
+ ++it) {
+ output->push_back(it->extension_number);
+ success = true;
+ }
+
+ return success;
+}
+
+void EncodedDescriptorDatabase::DescriptorIndex::FindAllFileNames(
+ std::vector<std::string>* output) const {
+ output->resize(by_name_.size() + by_name_flat_.size());
+ int i = 0;
+ for (const auto& entry : by_name_) {
+ (*output)[i] = entry.name;
+ i++;
+ }
+ for (const auto& entry : by_name_flat_) {
+ (*output)[i] = entry.name;
+ i++;
+ }
+}
+
+std::pair<const void*, int>
+EncodedDescriptorDatabase::DescriptorIndex::FindFile(
+ StringPiece filename) {
+ EnsureFlat();
+
+ auto it = std::lower_bound(by_name_flat_.begin(), by_name_flat_.end(),
+ filename, by_name_.key_comp());
+ return it == by_name_flat_.end() || it->name != filename
+ ? std::make_pair(nullptr, 0)
+ : it->data;
+}
+
+
bool EncodedDescriptorDatabase::FindAllFileNames(
std::vector<std::string>* output) {
- index_.FindAllFileNames(output);
+ index_->FindAllFileNames(output);
return true;
}
@@ -467,6 +775,15 @@
return output->ParseFromArray(encoded_file.first, encoded_file.second);
}
+EncodedDescriptorDatabase::EncodedDescriptorDatabase()
+ : index_(new DescriptorIndex()) {}
+
+EncodedDescriptorDatabase::~EncodedDescriptorDatabase() {
+ for (void* p : files_to_delete_) {
+ operator delete(p);
+ }
+}
+
// ===================================================================
DescriptorPoolDatabase::DescriptorPoolDatabase(const DescriptorPool& pool)
diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h
index 4009f33..10e60fc 100644
--- a/src/google/protobuf/descriptor_database.h
+++ b/src/google/protobuf/descriptor_database.h
@@ -266,21 +266,6 @@
// That symbol cannot be a super-symbol of the search key since if it were,
// then it would be a match, and we're assuming the match key doesn't exist.
// Therefore, step 2 will correctly return no match.
-
- // Find the last entry in the by_symbol_ map whose key is less than or
- // equal to the given name.
- typename std::map<std::string, Value>::iterator FindLastLessOrEqual(
- const std::string& name);
-
- // True if either the arguments are equal or super_symbol identifies a
- // parent symbol of sub_symbol (e.g. "foo.bar" is a parent of
- // "foo.bar.baz", but not a parent of "foo.barbaz").
- bool IsSubSymbol(const std::string& sub_symbol,
- const std::string& super_symbol);
-
- // Returns true if and only if all characters in the name are alphanumerics,
- // underscores, or periods.
- bool ValidateSymbolName(const std::string& name);
};
DescriptorIndex<const FileDescriptorProto*> index_;
@@ -332,8 +317,10 @@
bool FindAllFileNames(std::vector<std::string>* output) override;
private:
- SimpleDescriptorDatabase::DescriptorIndex<std::pair<const void*, int> >
- index_;
+ class DescriptorIndex;
+ // Keep DescriptorIndex by pointer to hide the implementation to keep a
+ // cleaner header.
+ std::unique_ptr<DescriptorIndex> index_;
std::vector<void*> files_to_delete_;
// If encoded_file.first is non-NULL, parse the data into *output and return
diff --git a/src/google/protobuf/descriptor_database_unittest.cc b/src/google/protobuf/descriptor_database_unittest.cc
index 8653193..6815283 100644
--- a/src/google/protobuf/descriptor_database_unittest.cc
+++ b/src/google/protobuf/descriptor_database_unittest.cc
@@ -34,20 +34,21 @@
//
// This file makes extensive use of RFC 3092. :)
+#include <google/protobuf/descriptor_database.h>
+
#include <algorithm>
#include <memory>
-#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/descriptor.h>
-#include <google/protobuf/descriptor_database.h>
-#include <google/protobuf/text_format.h>
-
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/text_format.h>
#include <gmock/gmock.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+
namespace google {
namespace protobuf {
namespace {
@@ -798,6 +799,7 @@
}
}
+
} // anonymous namespace
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc
index 898c1da..6085a12 100644
--- a/src/google/protobuf/descriptor_unittest.cc
+++ b/src/google/protobuf/descriptor_unittest.cc
@@ -243,7 +243,7 @@
}
strings::SubstituteAndAppend(&text_, "$0: $1: $2: $3\n", filename,
- element_name, location_name, message);
+ element_name, location_name, message);
}
// implements ErrorCollector ---------------------------------------
@@ -287,8 +287,9 @@
break;
}
- strings::SubstituteAndAppend(&warning_text_, "$0: $1: $2: $3\n", filename,
- element_name, location_name, message);
+ strings::SubstituteAndAppend(&warning_text_, "$0: $1: $2: $3\n",
+ filename, element_name, location_name,
+ message);
}
};
@@ -490,7 +491,7 @@
}
TEST_F(FileDescriptorTest, BuildAgainWithSyntax) {
- // Test that if te call BuildFile again on the same input we get the same
+ // Test that if we call BuildFile again on the same input we get the same
// FileDescriptor back even if syntax param is specified.
FileDescriptorProto proto_syntax2;
proto_syntax2.set_name("foo_syntax2");
@@ -998,6 +999,22 @@
EXPECT_TRUE(map_->message_type()->options().map_entry());
}
+TEST_F(DescriptorTest, GetMap) {
+ const Descriptor* map_desc = map_->message_type();
+ const FieldDescriptor* map_key = map_desc->map_key();
+ ASSERT_TRUE(map_key != nullptr);
+ EXPECT_EQ(map_key->name(), "key");
+ EXPECT_EQ(map_key->number(), 1);
+
+ const FieldDescriptor* map_value = map_desc->map_value();
+ ASSERT_TRUE(map_value != nullptr);
+ EXPECT_EQ(map_value->name(), "value");
+ EXPECT_EQ(map_value->number(), 2);
+
+ EXPECT_EQ(message_->map_key(), nullptr);
+ EXPECT_EQ(message_->map_value(), nullptr);
+}
+
TEST_F(DescriptorTest, FieldHasDefault) {
EXPECT_FALSE(foo_->has_default_value());
EXPECT_FALSE(bar_->has_default_value());
@@ -2532,7 +2549,7 @@
AddField(message_proto, "empty_string", 11, label, FD::TYPE_STRING)
->set_default_value("");
- // Add a second set of fields with implicit defalut values.
+ // Add a second set of fields with implicit default values.
AddField(message_proto, "implicit_int32", 21, label, FD::TYPE_INT32);
AddField(message_proto, "implicit_int64", 22, label, FD::TYPE_INT64);
AddField(message_proto, "implicit_uint32", 23, label, FD::TYPE_UINT32);
@@ -2575,11 +2592,9 @@
ASSERT_TRUE(message->field(10)->has_default_value());
EXPECT_EQ(-1, message->field(0)->default_value_int32());
- EXPECT_EQ(-PROTOBUF_ULONGLONG(1000000000000),
- message->field(1)->default_value_int64());
+ EXPECT_EQ(int64{-1000000000000}, message->field(1)->default_value_int64());
EXPECT_EQ(42, message->field(2)->default_value_uint32());
- EXPECT_EQ(PROTOBUF_ULONGLONG(2000000000000),
- message->field(3)->default_value_uint64());
+ EXPECT_EQ(uint64{2000000000000}, message->field(3)->default_value_uint64());
EXPECT_EQ(4.5, message->field(4)->default_value_float());
EXPECT_EQ(10e100, message->field(5)->default_value_double());
EXPECT_TRUE(message->field(6)->default_value_bool());
@@ -2652,9 +2667,11 @@
enum DescriptorPoolMode { NO_DATABASE, FALLBACK_DATABASE };
class AllowUnknownDependenciesTest
- : public testing::TestWithParam<DescriptorPoolMode> {
+ : public testing::TestWithParam<
+ std::tuple<DescriptorPoolMode, const char*>> {
protected:
- DescriptorPoolMode mode() { return GetParam(); }
+ DescriptorPoolMode mode() { return std::get<0>(GetParam()); }
+ const char* syntax() { return std::get<1>(GetParam()); }
virtual void SetUp() {
FileDescriptorProto foo_proto, bar_proto;
@@ -2693,10 +2710,13 @@
" }"
"}",
&foo_proto));
+ foo_proto.set_syntax(syntax());
+
ASSERT_TRUE(
TextFormat::ParseFromString("name: 'bar.proto'"
"message_type { name: 'Bar' }",
&bar_proto));
+ bar_proto.set_syntax(syntax());
// Collect pointers to stuff.
bar_file_ = BuildFile(bar_proto);
@@ -2969,7 +2989,9 @@
}
INSTANTIATE_TEST_SUITE_P(DatabaseSource, AllowUnknownDependenciesTest,
- testing::Values(NO_DATABASE, FALLBACK_DATABASE));
+ testing::Combine(testing::Values(NO_DATABASE,
+ FALLBACK_DATABASE),
+ testing::Values("proto2", "proto3")));
// ===================================================================
@@ -2985,11 +3007,11 @@
file->FindServiceByName("TestServiceWithCustomOptions");
const MethodDescriptor* method = service->FindMethodByName("Foo");
- EXPECT_EQ(PROTOBUF_LONGLONG(9876543210),
+ EXPECT_EQ(int64{9876543210},
file->options().GetExtension(protobuf_unittest::file_opt1));
EXPECT_EQ(-56,
message->options().GetExtension(protobuf_unittest::message_opt1));
- EXPECT_EQ(PROTOBUF_LONGLONG(8765432109),
+ EXPECT_EQ(int64{8765432109},
field->options().GetExtension(protobuf_unittest::field_opt1));
EXPECT_EQ(42, // Check that we get the default for an option we don't set.
field->options().GetExtension(protobuf_unittest::field_opt2));
@@ -2997,7 +3019,7 @@
EXPECT_EQ(-789, enm->options().GetExtension(protobuf_unittest::enum_opt1));
EXPECT_EQ(123, enm->value(1)->options().GetExtension(
protobuf_unittest::enum_value_opt1));
- EXPECT_EQ(PROTOBUF_LONGLONG(-9876543210),
+ EXPECT_EQ(int64{-9876543210},
service->options().GetExtension(protobuf_unittest::service_opt1));
EXPECT_EQ(protobuf_unittest::METHODOPT1_VAL2,
method->options().GetExtension(protobuf_unittest::method_opt1));
@@ -3456,7 +3478,7 @@
method->options().GetExtension(protobuf_unittest::methodopt).s());
}
-TEST(CustomOptions, UnusedImportWarning) {
+TEST(CustomOptions, UnusedImportError) {
DescriptorPool pool;
FileDescriptorProto file_proto;
@@ -3467,7 +3489,7 @@
&file_proto);
ASSERT_TRUE(pool.BuildFile(file_proto) != nullptr);
- pool.AddUnusedImportTrackFile("custom_options_import.proto");
+ pool.AddUnusedImportTrackFile("custom_options_import.proto", true);
ASSERT_TRUE(TextFormat::ParseFromString(
"name: \"custom_options_import.proto\" "
"package: \"protobuf_unittest\" "
@@ -3475,13 +3497,12 @@
&file_proto));
MockErrorCollector error_collector;
- EXPECT_TRUE(pool.BuildFileCollectingErrors(file_proto, &error_collector));
+ EXPECT_FALSE(pool.BuildFileCollectingErrors(file_proto, &error_collector));
EXPECT_EQ(
"custom_options_import.proto: "
"google/protobuf/unittest_custom_options.proto: IMPORT: Import "
"google/protobuf/unittest_custom_options.proto is unused.\n",
- error_collector.warning_text_);
- EXPECT_EQ("", error_collector.text_);
+ error_collector.text_);
}
// Verifies that proto files can correctly be parsed, even if the
@@ -5177,7 +5198,7 @@
}
TEST_F(ValidationErrorTest, ResolveUndefinedOption) {
- // The following should produce an eror that baz.bar is resolved but not
+ // The following should produce an error that baz.bar is resolved but not
// defined.
// foo.proto:
// package baz
@@ -6502,6 +6523,28 @@
}
+TEST_F(ValidationErrorTest, UnusedImportWithOtherError) {
+ BuildFile(
+ "name: 'bar.proto' "
+ "message_type {"
+ " name: 'Bar'"
+ "}");
+
+ pool_.AddUnusedImportTrackFile("foo.proto", true);
+ BuildFileWithErrors(
+ "name: 'foo.proto' "
+ "dependency: 'bar.proto' "
+ "message_type {"
+ " name: 'Foo'"
+ " extension { name:'foo' number:1 label:LABEL_OPTIONAL type:TYPE_INT32"
+ " extendee: 'Baz' }"
+ "}",
+
+ // Should not also contain unused import error.
+ "foo.proto: Foo.foo: EXTENDEE: \"Baz\" is not defined.\n");
+}
+
+
// ===================================================================
// DescriptorDatabase
@@ -6950,22 +6993,21 @@
}
bool PopulateFile(int file_num, FileDescriptorProto* output) {
- using strings::Substitute;
GOOGLE_CHECK_GE(file_num, 0);
output->Clear();
- output->set_name(Substitute("file$0.proto", file_num));
+ output->set_name(strings::Substitute("file$0.proto", file_num));
// file0.proto doesn't define Message0
if (file_num > 0) {
DescriptorProto* message = output->add_message_type();
- message->set_name(Substitute("Message$0", file_num));
+ message->set_name(strings::Substitute("Message$0", file_num));
for (int i = 0; i < file_num; ++i) {
- output->add_dependency(Substitute("file$0.proto", i));
+ output->add_dependency(strings::Substitute("file$0.proto", i));
FieldDescriptorProto* field = message->add_field();
- field->set_name(Substitute("field$0", i));
+ field->set_name(strings::Substitute("field$0", i));
field->set_number(i);
field->set_label(FieldDescriptorProto::LABEL_OPTIONAL);
field->set_type(FieldDescriptorProto::TYPE_MESSAGE);
- field->set_type_name(Substitute("Message$0", i));
+ field->set_type_name(strings::Substitute("Message$0", i));
}
}
return true;
@@ -7140,8 +7182,8 @@
static std::string PrintSourceLocation(const SourceLocation& loc) {
return strings::Substitute("$0:$1-$2:$3", 1 + loc.start_line,
- 1 + loc.start_column, 1 + loc.end_line,
- 1 + loc.end_column);
+ 1 + loc.start_column, 1 + loc.end_line,
+ 1 + loc.end_column);
}
private:
@@ -7156,9 +7198,9 @@
DescriptorPool pool_;
// tag number of all custom options in above test file
- static const int kCustomOptionFieldNumber = 10101;
+ static constexpr int kCustomOptionFieldNumber = 10101;
// tag number of field "a" in message type "A" in above test file
- static const int kAFieldNumber = 1;
+ static constexpr int kAFieldNumber = 1;
};
// TODO(adonovan): implement support for option fields and for
@@ -7773,7 +7815,7 @@
EXPECT_FALSE(pool_.InternalIsFileLoaded("bar.proto"));
// Finally, verify that if we call message_type() on the field, we will
- // buid the file where the message is defined, and get a valid descriptor
+ // build the file where the message is defined, and get a valid descriptor
EXPECT_TRUE(field->message_type() != nullptr);
EXPECT_TRUE(pool_.InternalIsFileLoaded("bar.proto"));
}
diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc
index 5677506..2682662 100644
--- a/src/google/protobuf/duration.pb.cc
+++ b/src/google/protobuf/duration.pb.cc
@@ -69,16 +69,15 @@
&scc_info_Duration_google_2fprotobuf_2fduration_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fduration_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fduration_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fduration_2eproto = {
- &descriptor_table_google_2fprotobuf_2fduration_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto, "google/protobuf/duration.proto", 227,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto, "google/protobuf/duration.proto", 227,
&descriptor_table_google_2fprotobuf_2fduration_2eproto_once, descriptor_table_google_2fprotobuf_2fduration_2eproto_sccs, descriptor_table_google_2fprotobuf_2fduration_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fduration_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fduration_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto, file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fduration_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fduration_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fduration_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fduration_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -89,22 +88,15 @@
public:
};
-Duration::Duration()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Duration)
-}
Duration::Duration(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Duration)
}
Duration::Duration(const Duration& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&seconds_, &from.seconds_,
static_cast<size_t>(reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
@@ -120,10 +112,11 @@
Duration::~Duration() {
// @@protoc_insertion_point(destructor:google.protobuf.Duration)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Duration::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void Duration::ArenaDtor(void* object) {
@@ -150,12 +143,12 @@
::memset(&seconds_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Duration::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -164,14 +157,14 @@
// int64 seconds = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// int32 nanos = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
- nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -181,7 +174,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -215,7 +210,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Duration)
return target;
@@ -270,7 +265,7 @@
void Duration::MergeFrom(const Duration& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Duration)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -302,9 +297,13 @@
void Duration::InternalSwap(Duration* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- swap(seconds_, other->seconds_);
- swap(nanos_, other->nanos_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Duration, nanos_)
+ + sizeof(Duration::nanos_)
+ - PROTOBUF_FIELD_OFFSET(Duration, seconds_)>(
+ reinterpret_cast<char*>(&seconds_),
+ reinterpret_cast<char*>(&other->seconds_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Duration::GetMetadata() const {
diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h
index 804361d..5b5da9e 100644
--- a/src/google/protobuf/duration.pb.h
+++ b/src/google/protobuf/duration.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -66,10 +66,10 @@
// ===================================================================
-class PROTOBUF_EXPORT Duration :
+class PROTOBUF_EXPORT Duration PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ {
public:
- Duration();
+ inline Duration() : Duration(nullptr) {};
virtual ~Duration();
Duration(const Duration& from);
@@ -83,7 +83,7 @@
return *this;
}
inline Duration& operator=(Duration&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -91,12 +91,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -121,7 +115,7 @@
}
inline void Swap(Duration* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -129,7 +123,7 @@
}
void UnsafeArenaSwap(Duration* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -169,13 +163,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -217,7 +204,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc
index 0ef5dd9..fd52371 100644
--- a/src/google/protobuf/dynamic_message.cc
+++ b/src/google/protobuf/dynamic_message.cc
@@ -62,17 +62,19 @@
// Item 8 of "More Effective C++" discusses this in more detail, though
// I don't have the book on me right now so I'm not sure.
+#include <google/protobuf/dynamic_message.h>
+
#include <algorithm>
+#include <cstddef>
#include <memory>
#include <unordered_map>
-#include <google/protobuf/stubs/hash.h>
-
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
-#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/unknown_field_set.h>
+#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/map_field.h>
@@ -82,12 +84,13 @@
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format.h>
+#include <google/protobuf/port_def.inc> // NOLINT
+
namespace google {
namespace protobuf {
using internal::DynamicMapField;
using internal::ExtensionSet;
-using internal::InternalMetadataWithArena;
using internal::MapField;
@@ -100,6 +103,28 @@
bool IsMapFieldInApi(const FieldDescriptor* field) { return field->is_map(); }
+// Sync with helpers.h.
+inline bool HasHasbit(const FieldDescriptor* field) {
+ // This predicate includes proto3 message fields only if they have "optional".
+ // Foo submsg1 = 1; // HasHasbit() == false
+ // optional Foo submsg2 = 2; // HasHasbit() == true
+ // This is slightly odd, as adding "optional" to a singular proto3 field does
+ // not change the semantics or API. However whenever any field in a message
+ // has a hasbit, it forces reflection to include hasbit offsets for *all*
+ // fields, even if almost all of them are set to -1 (no hasbit). So to avoid
+ // causing a sudden size regression for ~all proto3 messages, we give proto3
+ // message fields a hasbit only if "optional" is present. If the user is
+ // explicitly writing "optional", it is likely they are writing it on
+ // primitive fields also.
+ return (field->has_optional_keyword() || field->is_required()) &&
+ !field->options().weak();
+}
+
+inline bool InRealOneof(const FieldDescriptor* field) {
+ return field->containing_oneof() &&
+ !field->containing_oneof()->is_synthetic();
+}
+
// Compute the byte size of the in-memory representation of the field.
int FieldSpaceUsed(const FieldDescriptor* field) {
typedef FieldDescriptor FD; // avoid line wrapping
@@ -235,7 +260,6 @@
int size;
int has_bits_offset;
int oneof_case_offset;
- int internal_metadata_offset;
int extensions_offset;
// Not owned by the TypeInfo.
@@ -274,7 +298,6 @@
Message* New() const override;
Message* New(Arena* arena) const override;
- Arena* GetArena() const override { return arena_; }
int GetCachedSize() const override;
void SetCachedSize(int size) const override;
@@ -295,6 +318,9 @@
void SharedCtor(bool lock_factory);
+ // Needed to get the offset of the internal metadata member.
+ friend class DynamicMessageFactory;
+
inline bool is_prototype() const {
return type_info_->prototype == this ||
// If type_info_->prototype is NULL, then we must be constructing
@@ -321,7 +347,10 @@
}
DynamicMessage::DynamicMessage(const TypeInfo* type_info, Arena* arena)
- : type_info_(type_info), arena_(arena), cached_byte_size_(0) {
+ : Message(arena),
+ type_info_(type_info),
+ arena_(arena),
+ cached_byte_size_(0) {
SharedCtor(true);
}
@@ -349,21 +378,20 @@
const Descriptor* descriptor = type_info_->type;
// Initialize oneof cases.
+ int oneof_count = 0;
for (int i = 0; i < descriptor->oneof_decl_count(); ++i) {
- new (OffsetToPointer(type_info_->oneof_case_offset + sizeof(uint32) * i))
- uint32(0);
+ if (descriptor->oneof_decl(i)->is_synthetic()) continue;
+ new (OffsetToPointer(type_info_->oneof_case_offset +
+ sizeof(uint32) * oneof_count++)) uint32(0);
}
- new (OffsetToPointer(type_info_->internal_metadata_offset))
- InternalMetadataWithArena(arena_);
-
if (type_info_->extensions_offset != -1) {
new (OffsetToPointer(type_info_->extensions_offset)) ExtensionSet(arena_);
}
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
void* field_ptr = OffsetToPointer(type_info_->offsets[i]);
- if (field->containing_oneof()) {
+ if (InRealOneof(field)) {
continue;
}
switch (field->cpp_type()) {
@@ -458,9 +486,7 @@
DynamicMessage::~DynamicMessage() {
const Descriptor* descriptor = type_info_->type;
- reinterpret_cast<InternalMetadataWithArena*>(
- OffsetToPointer(type_info_->internal_metadata_offset))
- ->~InternalMetadataWithArena();
+ _internal_metadata_.Delete<UnknownFieldSet>();
if (type_info_->extensions_offset != -1) {
reinterpret_cast<ExtensionSet*>(
@@ -478,7 +504,7 @@
// be touched.
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
- if (field->containing_oneof()) {
+ if (InRealOneof(field)) {
void* field_ptr =
OffsetToPointer(type_info_->oneof_case_offset +
sizeof(uint32) * field->containing_oneof()->index());
@@ -682,9 +708,15 @@
// this block.
// - A big bitfield containing a bit for each field indicating whether
// or not that field is set.
+ int real_oneof_count = 0;
+ for (int i = 0; i < type->oneof_decl_count(); i++) {
+ if (!type->oneof_decl(i)->is_synthetic()) {
+ real_oneof_count++;
+ }
+ }
// Compute size and offsets.
- uint32* offsets = new uint32[type->field_count() + type->oneof_decl_count()];
+ uint32* offsets = new uint32[type->field_count() + real_oneof_count];
type_info->offsets.reset(offsets);
// Decide all field offsets by packing in order.
@@ -694,26 +726,35 @@
size = AlignOffset(size);
// Next the has_bits, which is an array of uint32s.
- if (type->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
- type_info->has_bits_offset = -1;
- } else {
- type_info->has_bits_offset = size;
- int has_bits_array_size =
- DivideRoundingUp(type->field_count(), bitsizeof(uint32));
+ type_info->has_bits_offset = -1;
+ int max_hasbit = 0;
+ for (int i = 0; i < type->field_count(); i++) {
+ if (HasHasbit(type->field(i))) {
+ if (type_info->has_bits_offset == -1) {
+ // At least one field in the message requires a hasbit, so allocate
+ // hasbits.
+ type_info->has_bits_offset = size;
+ uint32* has_bits_indices = new uint32[type->field_count()];
+ for (int i = 0; i < type->field_count(); i++) {
+ // Initialize to -1, fields that need a hasbit will overwrite.
+ has_bits_indices[i] = static_cast<uint32>(-1);
+ }
+ type_info->has_bits_indices.reset(has_bits_indices);
+ }
+ type_info->has_bits_indices[i] = max_hasbit++;
+ }
+ }
+
+ if (max_hasbit > 0) {
+ int has_bits_array_size = DivideRoundingUp(max_hasbit, bitsizeof(uint32));
size += has_bits_array_size * sizeof(uint32);
size = AlignOffset(size);
-
- uint32* has_bits_indices = new uint32[type->field_count()];
- for (int i = 0; i < type->field_count(); i++) {
- has_bits_indices[i] = i;
- }
- type_info->has_bits_indices.reset(has_bits_indices);
}
// The oneof_case, if any. It is an array of uint32s.
- if (type->oneof_decl_count() > 0) {
+ if (real_oneof_count > 0) {
type_info->oneof_case_offset = size;
- size += type->oneof_decl_count() * sizeof(uint32);
+ size += real_oneof_count * sizeof(uint32);
size = AlignOffset(size);
}
@@ -734,7 +775,7 @@
for (int i = 0; i < type->field_count(); i++) {
// Make sure field is aligned to avoid bus errors.
// Oneof fields do not use any space.
- if (!type->field(i)->containing_oneof()) {
+ if (!InRealOneof(type->field(i))) {
int field_size = FieldSpaceUsed(type->field(i));
size = AlignTo(size, std::min(kSafeAlignment, field_size));
offsets[i] = size;
@@ -744,16 +785,13 @@
// The oneofs.
for (int i = 0; i < type->oneof_decl_count(); i++) {
- size = AlignTo(size, kSafeAlignment);
- offsets[type->field_count() + i] = size;
- size += kMaxOneofUnionSize;
+ if (!type->oneof_decl(i)->is_synthetic()) {
+ size = AlignTo(size, kSafeAlignment);
+ offsets[type->field_count() + i] = size;
+ size += kMaxOneofUnionSize;
+ }
}
- // Add the InternalMetadataWithArena to the end.
- size = AlignOffset(size);
- type_info->internal_metadata_offset = size;
- size += sizeof(InternalMetadataWithArena);
-
type_info->weak_field_map_offset = -1;
// Align the final size to make sure no clever allocators think that
@@ -762,17 +800,16 @@
// Construct the reflection object.
- if (type->oneof_decl_count() > 0) {
- // Compute the size of default oneof instance and offsets of default
- // oneof fields.
- for (int i = 0; i < type->oneof_decl_count(); i++) {
- for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = type->oneof_decl(i)->field(j);
- int field_size = OneofFieldSpaceUsed(field);
- size = AlignTo(size, std::min(kSafeAlignment, field_size));
- offsets[field->index()] = size;
- size += field_size;
- }
+ // Compute the size of default oneof instance and offsets of default
+ // oneof fields.
+ for (int i = 0; i < type->oneof_decl_count(); i++) {
+ if (type->oneof_decl(i)->is_synthetic()) continue;
+ for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
+ const FieldDescriptor* field = type->oneof_decl(i)->field(j);
+ int field_size = OneofFieldSpaceUsed(field);
+ size = AlignTo(size, std::min(kSafeAlignment, field_size));
+ offsets[field->index()] = size;
+ size += field_size;
}
}
size = AlignOffset(size);
@@ -784,21 +821,22 @@
// of dynamic message to avoid dead lock.
DynamicMessage* prototype = new (base) DynamicMessage(type_info, false);
- if (type->oneof_decl_count() > 0 || num_weak_fields > 0) {
+ if (real_oneof_count > 0 || num_weak_fields > 0) {
// Construct default oneof instance.
ConstructDefaultOneofInstance(type_info->type, type_info->offsets.get(),
prototype);
}
- internal::ReflectionSchema schema = {type_info->prototype,
- type_info->offsets.get(),
- type_info->has_bits_indices.get(),
- type_info->has_bits_offset,
- type_info->internal_metadata_offset,
- type_info->extensions_offset,
- type_info->oneof_case_offset,
- type_info->size,
- type_info->weak_field_map_offset};
+ internal::ReflectionSchema schema = {
+ type_info->prototype,
+ type_info->offsets.get(),
+ type_info->has_bits_indices.get(),
+ type_info->has_bits_offset,
+ PROTOBUF_FIELD_OFFSET(DynamicMessage, _internal_metadata_),
+ type_info->extensions_offset,
+ type_info->oneof_case_offset,
+ type_info->size,
+ type_info->weak_field_map_offset};
type_info->reflection.reset(
new Reflection(type_info->type, schema, type_info->pool, this));
@@ -813,6 +851,7 @@
const Descriptor* type, const uint32 offsets[],
void* default_oneof_or_weak_instance) {
for (int i = 0; i < type->oneof_decl_count(); i++) {
+ if (type->oneof_decl(i)->is_synthetic()) continue;
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
void* field_ptr =
@@ -859,6 +898,7 @@
const Descriptor* type, const uint32 offsets[],
const void* default_oneof_instance) {
for (int i = 0; i < type->oneof_decl_count(); i++) {
+ if (type->oneof_decl(i)->is_synthetic()) continue;
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
@@ -874,3 +914,5 @@
} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc> // NOLINT
diff --git a/src/google/protobuf/dynamic_message_unittest.cc b/src/google/protobuf/dynamic_message_unittest.cc
index 42759de..6db6f5c 100644
--- a/src/google/protobuf/dynamic_message_unittest.cc
+++ b/src/google/protobuf/dynamic_message_unittest.cc
@@ -291,7 +291,7 @@
const Reflection* refl = message->GetReflection();
const Descriptor* desc = message->GetDescriptor();
- // Just test a single primtive and single message field here to make sure we
+ // Just test a single primitive and single message field here to make sure we
// are getting the no-field-presence semantics elsewhere. DynamicMessage uses
// GeneratedMessageReflection under the hood, so the rest should be fine as
// long as GMR recognizes that we're using a proto3 message.
diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc
index 5fb1993..855db18 100644
--- a/src/google/protobuf/empty.pb.cc
+++ b/src/google/protobuf/empty.pb.cc
@@ -66,16 +66,15 @@
&scc_info_Empty_google_2fprotobuf_2fempty_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fempty_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fempty_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fempty_2eproto = {
- &descriptor_table_google_2fprotobuf_2fempty_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto, "google/protobuf/empty.proto", 183,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto, "google/protobuf/empty.proto", 183,
&descriptor_table_google_2fprotobuf_2fempty_2eproto_once, descriptor_table_google_2fprotobuf_2fempty_2eproto_sccs, descriptor_table_google_2fprotobuf_2fempty_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fempty_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fempty_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto, file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fempty_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fempty_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fempty_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fempty_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -86,22 +85,15 @@
public:
};
-Empty::Empty()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Empty)
-}
Empty::Empty(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Empty)
}
Empty::Empty(const Empty& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Empty)
}
@@ -111,10 +103,11 @@
Empty::~Empty() {
// @@protoc_insertion_point(destructor:google.protobuf.Empty)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Empty::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void Empty::ArenaDtor(void* object) {
@@ -138,12 +131,12 @@
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Empty::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -152,7 +145,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
} // while
@@ -172,7 +167,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Empty)
return target;
@@ -213,7 +208,7 @@
void Empty::MergeFrom(const Empty& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Empty)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -239,7 +234,7 @@
void Empty::InternalSwap(Empty* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
}
::PROTOBUF_NAMESPACE_ID::Metadata Empty::GetMetadata() const {
diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h
index 71d3d20..be58106 100644
--- a/src/google/protobuf/empty.pb.h
+++ b/src/google/protobuf/empty.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -66,10 +66,10 @@
// ===================================================================
-class PROTOBUF_EXPORT Empty :
+class PROTOBUF_EXPORT Empty PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ {
public:
- Empty();
+ inline Empty() : Empty(nullptr) {};
virtual ~Empty();
Empty(const Empty& from);
@@ -83,7 +83,7 @@
return *this;
}
inline Empty& operator=(Empty&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -91,12 +91,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -121,7 +115,7 @@
}
inline void Swap(Empty* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -129,7 +123,7 @@
}
void UnsafeArenaSwap(Empty* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -169,13 +163,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -195,7 +182,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc
index b4eb6e1..3b1441e 100644
--- a/src/google/protobuf/extension_set.cc
+++ b/src/google/protobuf/extension_set.cc
@@ -1063,7 +1063,7 @@
}
void ExtensionSet::Swap(ExtensionSet* x) {
- if (GetArenaNoVirtual() == x->GetArenaNoVirtual()) {
+ if (GetArena() == x->GetArena()) {
using std::swap;
swap(flat_capacity_, x->flat_capacity_);
swap(flat_size_, x->flat_size_);
@@ -1091,7 +1091,7 @@
}
if (this_ext != NULL && other_ext != NULL) {
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
using std::swap;
swap(*this_ext, *other_ext);
} else {
@@ -1112,7 +1112,7 @@
}
if (this_ext == NULL) {
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
*Insert(number).first = *other_ext;
} else {
InternalExtensionMergeFrom(number, *other_ext);
@@ -1122,7 +1122,7 @@
}
if (other_ext == NULL) {
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
*other->Insert(number).first = *this_ext;
} else {
other->InternalExtensionMergeFrom(number, *this_ext);
@@ -1196,27 +1196,28 @@
}
}
-const char* ExtensionSet::ParseField(
- uint64 tag, const char* ptr, const MessageLite* containing_type,
- internal::InternalMetadataWithArenaLite* metadata,
- internal::ParseContext* ctx) {
+const char* ExtensionSet::ParseField(uint64 tag, const char* ptr,
+ const MessageLite* containing_type,
+ internal::InternalMetadata* metadata,
+ internal::ParseContext* ctx) {
GeneratedExtensionFinder finder(containing_type);
int number = tag >> 3;
bool was_packed_on_wire;
ExtensionInfo extension;
if (!FindExtensionInfoFromFieldNumber(tag & 7, number, &finder, &extension,
&was_packed_on_wire)) {
- return UnknownFieldParse(tag, metadata->mutable_unknown_fields(), ptr, ctx);
+ return UnknownFieldParse(
+ tag, metadata->mutable_unknown_fields<std::string>(), ptr, ctx);
}
- return ParseFieldWithExtensionInfo(number, was_packed_on_wire, extension,
- metadata, ptr, ctx);
+ return ParseFieldWithExtensionInfo<std::string>(
+ number, was_packed_on_wire, extension, metadata, ptr, ctx);
}
const char* ExtensionSet::ParseMessageSetItem(
const char* ptr, const MessageLite* containing_type,
- internal::InternalMetadataWithArenaLite* metadata,
- internal::ParseContext* ctx) {
- return ParseMessageSetItemTmpl(ptr, containing_type, metadata, ctx);
+ internal::InternalMetadata* metadata, internal::ParseContext* ctx) {
+ return ParseMessageSetItemTmpl<MessageLite, std::string>(ptr, containing_type,
+ metadata, ctx);
}
bool ExtensionSet::ParseFieldWithExtensionInfo(int number,
diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h
index 222f6db..b30a960 100644
--- a/src/google/protobuf/extension_set.h
+++ b/src/google/protobuf/extension_set.h
@@ -79,8 +79,7 @@
namespace protobuf {
namespace internal {
-class InternalMetadataWithArenaLite;
-class InternalMetadataWithArena;
+class InternalMetadata;
// Used to store values of type WireFormatLite::FieldType without having to
// #include wire_format_lite.h. Also, ensures that we use only one byte to
@@ -272,7 +271,7 @@
std::string* MutableString(int number, FieldType type, desc);
MessageLite* MutableMessage(int number, FieldType type,
const MessageLite& prototype, desc);
- MessageLite* MutableMessage(const FieldDescriptor* decsriptor,
+ MessageLite* MutableMessage(const FieldDescriptor* descriptor,
MessageFactory* factory);
// Adds the given message to the ExtensionSet, taking ownership of the
// message object. Existing message with the same number will be deleted.
@@ -292,7 +291,7 @@
MessageLite* UnsafeArenaReleaseMessage(const FieldDescriptor* descriptor,
MessageFactory* factory);
#undef desc
- Arena* GetArenaNoVirtual() const { return arena_; }
+ Arena* GetArena() const { return arena_; }
// repeated fields -------------------------------------------------
@@ -397,23 +396,24 @@
// Lite parser
const char* ParseField(uint64 tag, const char* ptr,
const MessageLite* containing_type,
- internal::InternalMetadataWithArenaLite* metadata,
+ internal::InternalMetadata* metadata,
internal::ParseContext* ctx);
// Full parser
const char* ParseField(uint64 tag, const char* ptr,
const Message* containing_type,
- internal::InternalMetadataWithArena* metadata,
+ internal::InternalMetadata* metadata,
internal::ParseContext* ctx);
- template <typename Msg, typename Metadata>
+ template <typename Msg>
const char* ParseMessageSet(const char* ptr, const Msg* containing_type,
- Metadata* metadata, internal::ParseContext* ctx) {
+ InternalMetadata* metadata,
+ internal::ParseContext* ctx) {
struct MessageSetItem {
const char* _InternalParse(const char* ptr, ParseContext* ctx) {
return me->ParseMessageSetItem(ptr, containing_type, metadata, ctx);
}
ExtensionSet* me;
const Msg* containing_type;
- Metadata* metadata;
+ InternalMetadata* metadata;
} item{this, containing_type, metadata};
while (!ctx->Done(&ptr)) {
uint32 tag;
@@ -770,36 +770,37 @@
const internal::ParseContext* ctx,
ExtensionInfo* extension, bool* was_packed_on_wire);
// Used for MessageSet only
- const char* ParseFieldMaybeLazily(
- uint64 tag, const char* ptr, const MessageLite* containing_type,
- internal::InternalMetadataWithArenaLite* metadata,
- internal::ParseContext* ctx) {
+ const char* ParseFieldMaybeLazily(uint64 tag, const char* ptr,
+ const MessageLite* containing_type,
+ internal::InternalMetadata* metadata,
+ internal::ParseContext* ctx) {
// Lite MessageSet doesn't implement lazy.
return ParseField(tag, ptr, containing_type, metadata, ctx);
}
- const char* ParseFieldMaybeLazily(
- uint64 tag, const char* ptr, const Message* containing_type,
- internal::InternalMetadataWithArena* metadata,
- internal::ParseContext* ctx);
- const char* ParseMessageSetItem(
- const char* ptr, const MessageLite* containing_type,
- internal::InternalMetadataWithArenaLite* metadata,
- internal::ParseContext* ctx);
+ const char* ParseFieldMaybeLazily(uint64 tag, const char* ptr,
+ const Message* containing_type,
+ internal::InternalMetadata* metadata,
+ internal::ParseContext* ctx);
+ const char* ParseMessageSetItem(const char* ptr,
+ const MessageLite* containing_type,
+ internal::InternalMetadata* metadata,
+ internal::ParseContext* ctx);
const char* ParseMessageSetItem(const char* ptr,
const Message* containing_type,
- internal::InternalMetadataWithArena* metadata,
+ internal::InternalMetadata* metadata,
internal::ParseContext* ctx);
// Implemented in extension_set_inl.h to keep code out of the header file.
template <typename T>
const char* ParseFieldWithExtensionInfo(int number, bool was_packed_on_wire,
const ExtensionInfo& info,
- T* metadata, const char* ptr,
+ internal::InternalMetadata* metadata,
+ const char* ptr,
internal::ParseContext* ctx);
- template <typename Msg, typename Metadata>
+ template <typename Msg, typename T>
const char* ParseMessageSetItemTmpl(const char* ptr,
const Msg* containing_type,
- Metadata* metadata,
+ internal::InternalMetadata* metadata,
internal::ParseContext* ctx);
// Hack: RepeatedPtrFieldBase declares ExtensionSet as a friend. This
diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc
index 9b7ee4d..86e710c 100644
--- a/src/google/protobuf/extension_set_heavy.cc
+++ b/src/google/protobuf/extension_set_heavy.cc
@@ -340,33 +340,33 @@
return true;
}
-const char* ExtensionSet::ParseField(
- uint64 tag, const char* ptr, const Message* containing_type,
- internal::InternalMetadataWithArena* metadata,
- internal::ParseContext* ctx) {
+const char* ExtensionSet::ParseField(uint64 tag, const char* ptr,
+ const Message* containing_type,
+ internal::InternalMetadata* metadata,
+ internal::ParseContext* ctx) {
int number = tag >> 3;
bool was_packed_on_wire;
ExtensionInfo extension;
if (!FindExtension(tag & 7, number, containing_type, ctx, &extension,
&was_packed_on_wire)) {
- return UnknownFieldParse(tag, metadata->mutable_unknown_fields(), ptr, ctx);
+ return UnknownFieldParse(
+ tag, metadata->mutable_unknown_fields<UnknownFieldSet>(), ptr, ctx);
}
- return ParseFieldWithExtensionInfo(number, was_packed_on_wire, extension,
- metadata, ptr, ctx);
+ return ParseFieldWithExtensionInfo<UnknownFieldSet>(
+ number, was_packed_on_wire, extension, metadata, ptr, ctx);
}
const char* ExtensionSet::ParseFieldMaybeLazily(
uint64 tag, const char* ptr, const Message* containing_type,
- internal::InternalMetadataWithArena* metadata,
- internal::ParseContext* ctx) {
+ internal::InternalMetadata* metadata, internal::ParseContext* ctx) {
return ParseField(tag, ptr, containing_type, metadata, ctx);
}
const char* ExtensionSet::ParseMessageSetItem(
const char* ptr, const Message* containing_type,
- internal::InternalMetadataWithArena* metadata,
- internal::ParseContext* ctx) {
- return ParseMessageSetItemTmpl(ptr, containing_type, metadata, ctx);
+ internal::InternalMetadata* metadata, internal::ParseContext* ctx) {
+ return ParseMessageSetItemTmpl<Message, UnknownFieldSet>(ptr, containing_type,
+ metadata, ctx);
}
bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input,
diff --git a/src/google/protobuf/extension_set_inl.h b/src/google/protobuf/extension_set_inl.h
index 087a3a4..9957f8b 100644
--- a/src/google/protobuf/extension_set_inl.h
+++ b/src/google/protobuf/extension_set_inl.h
@@ -33,6 +33,7 @@
#include <google/protobuf/parse_context.h>
#include <google/protobuf/extension_set.h>
+#include <google/protobuf/metadata_lite.h>
namespace google {
namespace protobuf {
@@ -41,7 +42,7 @@
template <typename T>
const char* ExtensionSet::ParseFieldWithExtensionInfo(
int number, bool was_packed_on_wire, const ExtensionInfo& extension,
- T* metadata, const char* ptr, internal::ParseContext* ctx) {
+ InternalMetadata* metadata, const char* ptr, internal::ParseContext* ctx) {
if (was_packed_on_wire) {
switch (extension.type) {
#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE) \
@@ -66,7 +67,7 @@
#undef HANDLE_TYPE
case WireFormatLite::TYPE_ENUM:
- return internal::PackedEnumParserArg(
+ return internal::PackedEnumParserArg<T>(
MutableRawRepeatedField(number, extension.type, extension.is_packed,
extension.descriptor),
ptr, ctx, extension.enum_validity_check.func,
@@ -98,6 +99,7 @@
HANDLE_VARINT_TYPE(INT64, Int64);
HANDLE_VARINT_TYPE(UINT32, UInt32);
HANDLE_VARINT_TYPE(UINT64, UInt64);
+ HANDLE_VARINT_TYPE(BOOL, Bool);
#undef HANDLE_VARINT_TYPE
#define HANDLE_SVARINT_TYPE(UPPERCASE, CPP_CAMELCASE, SIZE) \
case WireFormatLite::TYPE_##UPPERCASE: { \
@@ -136,7 +138,6 @@
HANDLE_FIXED_TYPE(SFIXED64, Int64, int64);
HANDLE_FIXED_TYPE(FLOAT, Float, float);
HANDLE_FIXED_TYPE(DOUBLE, Double, double);
- HANDLE_FIXED_TYPE(BOOL, Bool, bool);
#undef HANDLE_FIXED_TYPE
case WireFormatLite::TYPE_ENUM: {
@@ -147,7 +148,7 @@
if (!extension.enum_validity_check.func(
extension.enum_validity_check.arg, value)) {
- WriteVarint(number, val, metadata->mutable_unknown_fields());
+ WriteVarint(number, val, metadata->mutable_unknown_fields<T>());
} else if (extension.is_repeated) {
AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, value,
extension.descriptor);
@@ -200,11 +201,10 @@
return ptr;
}
-template <typename Msg, typename Metadata>
-const char* ExtensionSet::ParseMessageSetItemTmpl(const char* ptr,
- const Msg* containing_type,
- Metadata* metadata,
- internal::ParseContext* ctx) {
+template <typename Msg, typename T>
+const char* ExtensionSet::ParseMessageSetItemTmpl(
+ const char* ptr, const Msg* containing_type,
+ internal::InternalMetadata* metadata, internal::ParseContext* ctx) {
std::string payload;
uint32 type_id = 0;
while (!ctx->Done(&ptr)) {
@@ -220,7 +220,7 @@
if (!FindExtension(2, type_id, containing_type, ctx, &extension,
&was_packed_on_wire)) {
WriteLengthDelimited(type_id, payload,
- metadata->mutable_unknown_fields());
+ metadata->mutable_unknown_fields<T>());
} else {
MessageLite* value =
extension.is_repeated
diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc
index c08782b..ccda993 100644
--- a/src/google/protobuf/extension_set_unittest.cc
+++ b/src/google/protobuf/extension_set_unittest.cc
@@ -821,7 +821,7 @@
const int old_capacity = \
message.GetRepeatedExtension(unittest::repeated_##type##_extension) \
.Capacity(); \
- EXPECT_GE(old_capacity, kMinRepeatedFieldAllocationSize); \
+ EXPECT_GE(old_capacity, kRepeatedFieldLowerClampLimit); \
for (int i = 0; i < 16; ++i) { \
message.AddExtension(unittest::repeated_##type##_extension, value); \
} \
@@ -864,7 +864,7 @@
message.AddExtension(unittest::repeated_string_extension, value);
}
min_expected_size +=
- (sizeof(value) + value.size()) * (16 - kMinRepeatedFieldAllocationSize);
+ (sizeof(value) + value.size()) * (16 - kRepeatedFieldLowerClampLimit);
EXPECT_LE(min_expected_size, message.SpaceUsed());
}
// Repeated messages
@@ -880,7 +880,7 @@
->CopyFrom(prototype);
}
min_expected_size +=
- (16 - kMinRepeatedFieldAllocationSize) * prototype.SpaceUsed();
+ (16 - kRepeatedFieldLowerClampLimit) * prototype.SpaceUsed();
EXPECT_LE(min_expected_size, message.SpaceUsed());
}
}
@@ -1319,6 +1319,13 @@
}
}
+TEST(ExtensionSetTest, BoolExtension) {
+ unittest::TestAllExtensions msg;
+ uint8 wire_bytes[2] = {13 * 8, 42 /* out of bounds payload for bool */};
+ EXPECT_TRUE(msg.ParseFromArray(wire_bytes, 2));
+ EXPECT_TRUE(msg.GetExtension(protobuf_unittest::optional_bool_extension));
+}
+
} // namespace
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc
index 78c343f..42e077f 100644
--- a/src/google/protobuf/field_mask.pb.cc
+++ b/src/google/protobuf/field_mask.pb.cc
@@ -68,16 +68,15 @@
&scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto = {
- &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto, "google/protobuf/field_mask.proto", 230,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto, "google/protobuf/field_mask.proto", 230,
&descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once, descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_sccs, descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto, file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2ffield_5fmask_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2ffield_5fmask_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -88,14 +87,8 @@
public:
};
-FieldMask::FieldMask()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.FieldMask)
-}
FieldMask::FieldMask(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
paths_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -103,9 +96,8 @@
}
FieldMask::FieldMask(const FieldMask& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
paths_(from.paths_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask)
}
@@ -116,10 +108,11 @@
FieldMask::~FieldMask() {
// @@protoc_insertion_point(destructor:google.protobuf.FieldMask)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void FieldMask::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void FieldMask::ArenaDtor(void* object) {
@@ -144,12 +137,12 @@
(void) cached_has_bits;
paths_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* FieldMask::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -175,7 +168,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -207,7 +202,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldMask)
return target;
@@ -256,7 +251,7 @@
void FieldMask::MergeFrom(const FieldMask& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldMask)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -283,7 +278,7 @@
void FieldMask::InternalSwap(FieldMask* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
paths_.InternalSwap(&other->paths_);
}
diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h
index cce1e1b..b3070f3 100644
--- a/src/google/protobuf/field_mask.pb.h
+++ b/src/google/protobuf/field_mask.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -66,10 +66,10 @@
// ===================================================================
-class PROTOBUF_EXPORT FieldMask :
+class PROTOBUF_EXPORT FieldMask PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ {
public:
- FieldMask();
+ inline FieldMask() : FieldMask(nullptr) {};
virtual ~FieldMask();
FieldMask(const FieldMask& from);
@@ -83,7 +83,7 @@
return *this;
}
inline FieldMask& operator=(FieldMask&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -91,12 +91,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -121,7 +115,7 @@
}
inline void Swap(FieldMask* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -129,7 +123,7 @@
}
void UnsafeArenaSwap(FieldMask* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -169,13 +163,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -222,7 +209,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
diff --git a/src/google/protobuf/generated_enum_util.cc b/src/google/protobuf/generated_enum_util.cc
old mode 100755
new mode 100644
diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc
index 9641ebd..da6ba40 100644
--- a/src/google/protobuf/generated_message_reflection.cc
+++ b/src/google/protobuf/generated_message_reflection.cc
@@ -32,6 +32,8 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <google/protobuf/generated_message_reflection.h>
+
#include <algorithm>
#include <set>
@@ -40,13 +42,13 @@
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/extension_set.h>
-#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/wire_format.h>
@@ -60,7 +62,7 @@
using google::protobuf::internal::GenericTypeHandler;
using google::protobuf::internal::GetEmptyString;
using google::protobuf::internal::InlinedStringField;
-using google::protobuf::internal::InternalMetadataWithArena;
+using google::protobuf::internal::InternalMetadata;
using google::protobuf::internal::LazyField;
using google::protobuf::internal::MapFieldBase;
using google::protobuf::internal::MigrationSchema;
@@ -100,21 +102,9 @@
namespace {
-template <class To>
-To* GetPointerAtOffset(Message* message, uint32 offset) {
- return reinterpret_cast<To*>(reinterpret_cast<char*>(message) + offset);
-}
-
-template <class To>
-const To* GetConstPointerAtOffset(const Message* message, uint32 offset) {
- return reinterpret_cast<const To*>(reinterpret_cast<const char*>(message) +
- offset);
-}
-
-template <class To>
-const To& GetConstRefAtOffset(const Message& message, uint32 offset) {
- return *GetConstPointerAtOffset<To>(&message, offset);
-}
+using internal::GetConstPointerAtOffset;
+using internal::GetConstRefAtOffset;
+using internal::GetPointerAtOffset;
void ReportReflectionUsageError(const Descriptor* descriptor,
const FieldDescriptor* field,
@@ -231,11 +221,13 @@
const UnknownFieldSet& Reflection::GetUnknownFields(
const Message& message) const {
- return GetInternalMetadataWithArena(message).unknown_fields();
+ return GetInternalMetadata(message).unknown_fields<UnknownFieldSet>(
+ UnknownFieldSet::default_instance);
}
UnknownFieldSet* Reflection::MutableUnknownFields(Message* message) const {
- return MutableInternalMetadataWithArena(message)->mutable_unknown_fields();
+ return MutableInternalMetadata(message)
+ ->mutable_unknown_fields<UnknownFieldSet>();
}
size_t Reflection::SpaceUsedLong(const Message& message) const {
@@ -295,7 +287,7 @@
break;
}
} else {
- if (field->containing_oneof() && !HasOneofField(message, field)) {
+ if (schema_.InRealOneof(field) && !HasOneofField(message, field)) {
continue;
}
switch (field->cpp_type()) {
@@ -484,6 +476,7 @@
void Reflection::SwapOneofField(Message* message1, Message* message2,
const OneofDescriptor* oneof_descriptor) const {
+ GOOGLE_DCHECK(!oneof_descriptor->is_synthetic());
uint32 oneof_case1 = GetOneofCase(*message1, oneof_descriptor);
uint32 oneof_case2 = GetOneofCase(*message2, oneof_descriptor);
@@ -640,7 +633,7 @@
int fields_with_has_bits = 0;
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
- if (field->is_repeated() || field->containing_oneof()) {
+ if (field->is_repeated() || schema_.InRealOneof(field)) {
continue;
}
fields_with_has_bits++;
@@ -655,12 +648,15 @@
for (int i = 0; i <= last_non_weak_field_index_; i++) {
const FieldDescriptor* field = descriptor_->field(i);
- if (field->containing_oneof()) continue;
+ if (schema_.InRealOneof(field)) continue;
SwapField(message1, message2, field);
}
const int oneof_decl_count = descriptor_->oneof_decl_count();
for (int i = 0; i < oneof_decl_count; i++) {
- SwapOneofField(message1, message2, descriptor_->oneof_decl(i));
+ const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
+ if (!oneof->is_synthetic()) {
+ SwapOneofField(message1, message2, oneof);
+ }
}
if (schema_.HasExtensionSet()) {
@@ -702,7 +698,7 @@
MutableExtensionSet(message1)->SwapExtension(
MutableExtensionSet(message2), field->number());
} else {
- if (field->containing_oneof()) {
+ if (schema_.InRealOneof(field)) {
int oneof_index = field->containing_oneof()->index();
// Only swap the oneof field once.
if (swapped_oneof.find(oneof_index) != swapped_oneof.end()) {
@@ -733,7 +729,7 @@
if (field->is_extension()) {
return GetExtensionSet(message).Has(field->number());
} else {
- if (field->containing_oneof()) {
+ if (schema_.InRealOneof(field)) {
return HasOneofField(message, field);
} else {
return HasBit(message, field);
@@ -793,7 +789,7 @@
if (field->is_extension()) {
MutableExtensionSet(message)->ClearExtension(field->number());
} else if (!field->is_repeated()) {
- if (field->containing_oneof()) {
+ if (schema_.InRealOneof(field)) {
ClearOneofField(message, field);
return;
}
@@ -1026,6 +1022,14 @@
}
} // namespace
+namespace internal {
+bool CreateUnknownEnumValues(const FieldDescriptor* field) {
+ bool open_enum = false;
+ return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 || open_enum;
+}
+} // namespace internal
+using internal::CreateUnknownEnumValues;
+
void Reflection::ListFields(const Message& message,
std::vector<const FieldDescriptor*>* output) const {
output->clear();
@@ -1035,7 +1039,7 @@
// Optimization: Avoid calling GetHasBits() and HasOneofField() many times
// within the field loop. We allow this violation of ReflectionSchema
- // encapsulation because this function takes a noticable about of CPU
+ // encapsulation because this function takes a noticeable about of CPU
// fleetwide and properly allowing this optimization through public interfaces
// seems more trouble than it is worth.
const uint32* const has_bits =
@@ -1050,14 +1054,14 @@
}
} else {
const OneofDescriptor* containing_oneof = field->containing_oneof();
- if (containing_oneof) {
+ if (schema_.InRealOneof(field)) {
const uint32* const oneof_case_array = GetConstPointerAtOffset<uint32>(
&message, schema_.oneof_case_offset_);
// Equivalent to: HasOneofField(message, field)
if (oneof_case_array[containing_oneof->index()] == field->number()) {
output->push_back(field);
}
- } else if (has_bits) {
+ } else if (has_bits && has_bits_indices[i] != -1) {
// Equivalent to: HasBit(message, field)
if (IsIndexInHasBitSet(has_bits, has_bits_indices[i])) {
output->push_back(field);
@@ -1208,7 +1212,7 @@
const std::string* default_ptr =
&DefaultRaw<ArenaStringPtr>(field).Get();
- if (field->containing_oneof() && !HasOneofField(*message, field)) {
+ if (schema_.InRealOneof(field) && !HasOneofField(*message, field)) {
ClearOneof(message, field->containing_oneof());
MutableField<ArenaStringPtr>(message, field)
->UnsafeSetDefault(default_ptr);
@@ -1323,7 +1327,7 @@
void Reflection::SetEnumValue(Message* message, const FieldDescriptor* field,
int value) const {
USAGE_CHECK_ALL(SetEnumValue, SINGULAR, ENUM);
- if (!CreateUnknownEnumValues(descriptor_->file())) {
+ if (!CreateUnknownEnumValues(field)) {
// Check that the value is valid if we don't support direct storage of
// unknown enum values.
const EnumValueDescriptor* value_desc =
@@ -1380,7 +1384,7 @@
const FieldDescriptor* field, int index,
int value) const {
USAGE_CHECK_ALL(SetRepeatedEnum, REPEATED, ENUM);
- if (!CreateUnknownEnumValues(descriptor_->file())) {
+ if (!CreateUnknownEnumValues(field)) {
// Check that the value is valid if we don't support direct storage of
// unknown enum values.
const EnumValueDescriptor* value_desc =
@@ -1414,7 +1418,7 @@
void Reflection::AddEnumValue(Message* message, const FieldDescriptor* field,
int value) const {
USAGE_CHECK_ALL(AddEnum, REPEATED, ENUM);
- if (!CreateUnknownEnumValues(descriptor_->file())) {
+ if (!CreateUnknownEnumValues(field)) {
// Check that the value is valid if we don't support direct storage of
// unknown enum values.
const EnumValueDescriptor* value_desc =
@@ -1475,7 +1479,7 @@
Message** result_holder = MutableRaw<Message*>(message, field);
- if (field->containing_oneof()) {
+ if (schema_.InRealOneof(field)) {
if (!HasOneofField(*message, field)) {
ClearOneof(message, field->containing_oneof());
result_holder = MutableField<Message*>(message, field);
@@ -1504,7 +1508,7 @@
MutableExtensionSet(message)->UnsafeArenaSetAllocatedMessage(
field->number(), field->type(), field, sub_message);
} else {
- if (field->containing_oneof()) {
+ if (schema_.InRealOneof(field)) {
if (sub_message == nullptr) {
ClearOneof(message, field->containing_oneof());
return;
@@ -1566,10 +1570,10 @@
MutableExtensionSet(message)->UnsafeArenaReleaseMessage(field,
factory));
} else {
- if (!(field->is_repeated() || field->containing_oneof())) {
+ if (!(field->is_repeated() || schema_.InRealOneof(field))) {
ClearBit(message, field);
}
- if (field->containing_oneof()) {
+ if (schema_.InRealOneof(field)) {
if (HasOneofField(*message, field)) {
*MutableOneofCase(message, field->containing_oneof()) = 0;
} else {
@@ -1754,6 +1758,10 @@
const FieldDescriptor* Reflection::GetOneofFieldDescriptor(
const Message& message, const OneofDescriptor* oneof_descriptor) const {
+ if (oneof_descriptor->is_synthetic()) {
+ const FieldDescriptor* field = oneof_descriptor->field(0);
+ return HasField(message, field) ? field : nullptr;
+ }
uint32 field_number = GetOneofCase(message, oneof_descriptor);
if (field_number == 0) {
return nullptr;
@@ -1850,7 +1858,7 @@
template <typename Type>
const Type& Reflection::GetRaw(const Message& message,
const FieldDescriptor* field) const {
- if (field->containing_oneof() && !HasOneofField(message, field)) {
+ if (schema_.InRealOneof(field) && !HasOneofField(message, field)) {
return DefaultRaw<Type>(field);
}
return GetConstRefAtOffset<Type>(message, schema_.GetFieldOffset(field));
@@ -1878,12 +1886,14 @@
uint32 Reflection::GetOneofCase(const Message& message,
const OneofDescriptor* oneof_descriptor) const {
+ GOOGLE_DCHECK(!oneof_descriptor->is_synthetic());
return GetConstRefAtOffset<uint32>(
message, schema_.GetOneofCaseOffset(oneof_descriptor));
}
uint32* Reflection::MutableOneofCase(
Message* message, const OneofDescriptor* oneof_descriptor) const {
+ GOOGLE_DCHECK(!oneof_descriptor->is_synthetic());
return GetPointerAtOffset<uint32>(
message, schema_.GetOneofCaseOffset(oneof_descriptor));
}
@@ -1899,31 +1909,25 @@
}
Arena* Reflection::GetArena(Message* message) const {
- return GetInternalMetadataWithArena(*message).arena();
+ return GetInternalMetadata(*message).arena();
}
-const InternalMetadataWithArena& Reflection::GetInternalMetadataWithArena(
+const InternalMetadata& Reflection::GetInternalMetadata(
const Message& message) const {
- return GetConstRefAtOffset<InternalMetadataWithArena>(
- message, schema_.GetMetadataOffset());
+ return GetConstRefAtOffset<InternalMetadata>(message,
+ schema_.GetMetadataOffset());
}
-InternalMetadataWithArena* Reflection::MutableInternalMetadataWithArena(
- Message* message) const {
- return GetPointerAtOffset<InternalMetadataWithArena>(
- message, schema_.GetMetadataOffset());
-}
-
-template <typename Type>
-const Type& Reflection::DefaultRaw(const FieldDescriptor* field) const {
- return *reinterpret_cast<const Type*>(schema_.GetFieldDefault(field));
+InternalMetadata* Reflection::MutableInternalMetadata(Message* message) const {
+ return GetPointerAtOffset<InternalMetadata>(message,
+ schema_.GetMetadataOffset());
}
// Simple accessors for manipulating has_bits_.
bool Reflection::HasBit(const Message& message,
const FieldDescriptor* field) const {
GOOGLE_DCHECK(!field->options().weak());
- if (schema_.HasHasbits()) {
+ if (schema_.HasBitIndex(field) != -1) {
return IsIndexInHasBitSet(GetHasBits(message), schema_.HasBitIndex(field));
}
@@ -1983,10 +1987,8 @@
void Reflection::SetBit(Message* message, const FieldDescriptor* field) const {
GOOGLE_DCHECK(!field->options().weak());
- if (!schema_.HasHasbits()) {
- return;
- }
const uint32 index = schema_.HasBitIndex(field);
+ if (index == -1) return;
MutableHasBits(message)[index / 32] |=
(static_cast<uint32>(1) << (index % 32));
}
@@ -2023,6 +2025,9 @@
bool Reflection::HasOneof(const Message& message,
const OneofDescriptor* oneof_descriptor) const {
+ if (oneof_descriptor->is_synthetic()) {
+ return HasField(message, oneof_descriptor->field(0));
+ }
return (GetOneofCase(message, oneof_descriptor) > 0);
}
@@ -2045,6 +2050,10 @@
void Reflection::ClearOneof(Message* message,
const OneofDescriptor* oneof_descriptor) const {
+ if (oneof_descriptor->is_synthetic()) {
+ ClearField(message, oneof_descriptor->field(0));
+ return;
+ }
// TODO(jieluo): Consider to cache the unused object instead of deleting
// it. It will be much faster if an application switches a lot from
// a few oneof fields. Time/space tradeoff
@@ -2125,19 +2134,19 @@
template <typename Type>
void Reflection::SetField(Message* message, const FieldDescriptor* field,
const Type& value) const {
- if (field->containing_oneof() && !HasOneofField(*message, field)) {
+ bool real_oneof = schema_.InRealOneof(field);
+ if (real_oneof && !HasOneofField(*message, field)) {
ClearOneof(message, field->containing_oneof());
}
*MutableRaw<Type>(message, field) = value;
- field->containing_oneof() ? SetOneofCase(message, field)
- : SetBit(message, field);
+ real_oneof ? SetOneofCase(message, field) : SetBit(message, field);
}
template <typename Type>
Type* Reflection::MutableField(Message* message,
const FieldDescriptor* field) const {
- field->containing_oneof() ? SetOneofCase(message, field)
- : SetBit(message, field);
+ schema_.InRealOneof(field) ? SetOneofCase(message, field)
+ : SetBit(message, field);
return MutableRaw<Type>(message, field);
}
@@ -2331,7 +2340,7 @@
std::vector<std::pair<const Metadata*, const Metadata*> > metadata_arrays_;
};
-void AssignDescriptorsImpl(const DescriptorTable* table) {
+void AssignDescriptorsImpl(const DescriptorTable* table, bool eager) {
// Ensure the file descriptor is added to the pool.
{
// This only happens once per proto file. So a global mutex to serialize
@@ -2341,6 +2350,25 @@
AddDescriptors(table);
mu.Unlock();
}
+ if (eager) {
+ // Normally we do not want to eagerly build descriptors of our deps.
+ // However if this proto is optimized for code size (ie using reflection)
+ // and it has a message extending a custom option of a descriptor with that
+ // message being optimized for code size as well. Building the descriptors
+ // in this file requires parsing the serialized file descriptor, which now
+ // requires parsing the message extension, which potentially requires
+ // building the descriptor of the message extending one of the options.
+ // However we are already updating descriptor pool under a lock. To prevent
+ // this the compiler statically looks for this case and we just make sure we
+ // first build the descriptors of all our dependencies, preventing the
+ // deadlock.
+ int num_deps = table->num_deps;
+ for (int i = 0; i < num_deps; i++) {
+ // In case of weak fields deps[i] could be null.
+ if (table->deps[i]) AssignDescriptors(table->deps[i], true);
+ }
+ }
+
// Fill the arrays with pointers to descriptors and reflection classes.
const FileDescriptor* file =
DescriptorPool::internal_generated_pool()->FindFileByName(
@@ -2378,7 +2406,8 @@
// Ensure all dependent descriptors are registered to the generated descriptor
// pool and message factory.
- for (int i = 0; i < table->num_deps; i++) {
+ int num_deps = table->num_deps;
+ for (int i = 0; i < num_deps; i++) {
// In case of weak fields deps[i] could be null.
if (table->deps[i]) AddDescriptors(table->deps[i]);
}
@@ -2403,8 +2432,9 @@
namespace internal {
-void AssignDescriptors(const DescriptorTable* table) {
- call_once(*table->once, AssignDescriptorsImpl, table);
+void AssignDescriptors(const DescriptorTable* table, bool eager) {
+ if (!eager) eager = table->is_eager;
+ call_once(*table->once, AssignDescriptorsImpl, table, eager);
}
void AddDescriptors(const DescriptorTable* table) {
@@ -2412,8 +2442,8 @@
// properly serialized. This function is only called pre-main by global
// descriptors and we can assume single threaded access or it's called
// by AssignDescriptorImpl which uses a mutex to sequence calls.
- if (*table->is_initialized) return;
- *table->is_initialized = true;
+ if (table->is_initialized) return;
+ table->is_initialized = true;
AddDescriptorsImpl(table);
}
@@ -2426,11 +2456,12 @@
uint32 has_offset,
io::CodedOutputStream* output) {
const void* ptr = base + offset;
- const InternalMetadataWithArena* metadata =
- static_cast<const InternalMetadataWithArena*>(ptr);
+ const InternalMetadata* metadata = static_cast<const InternalMetadata*>(ptr);
if (metadata->have_unknown_fields()) {
- internal::WireFormat::SerializeUnknownFields(metadata->unknown_fields(),
- output);
+ internal::WireFormat::SerializeUnknownFields(
+ metadata->unknown_fields<UnknownFieldSet>(
+ UnknownFieldSet::default_instance),
+ output);
}
}
diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h
index cbfab5e..e2eae77 100644
--- a/src/google/protobuf/generated_message_reflection.h
+++ b/src/google/protobuf/generated_message_reflection.h
@@ -46,7 +46,6 @@
// is released to components.
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_enum_reflection.h>
-#include <google/protobuf/metadata.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/port.h>
#include <google/protobuf/unknown_field_set.h>
@@ -73,8 +72,6 @@
namespace protobuf {
namespace internal {
class DefaultEmptyOneof;
-class ReflectionAccessor;
-
// Defined in other files.
class ExtensionSet; // extension_set.h
class WeakFieldMap; // weak_field_map.h
@@ -127,16 +124,21 @@
// Size of a google::protobuf::Message object of this type.
uint32 GetObjectSize() const { return static_cast<uint32>(object_size_); }
+ bool InRealOneof(const FieldDescriptor* field) const {
+ return field->containing_oneof() &&
+ !field->containing_oneof()->is_synthetic();
+ }
+
// Offset of a non-oneof field. Getting a field offset is slightly more
// efficient when we know statically that it is not a oneof field.
uint32 GetFieldOffsetNonOneof(const FieldDescriptor* field) const {
- GOOGLE_DCHECK(!field->containing_oneof());
+ GOOGLE_DCHECK(!InRealOneof(field));
return OffsetValue(offsets_[field->index()], field->type());
}
// Offset of any field.
uint32 GetFieldOffset(const FieldDescriptor* field) const {
- if (field->containing_oneof()) {
+ if (InRealOneof(field)) {
size_t offset =
static_cast<size_t>(field->containing_type()->field_count() +
field->containing_oneof()->index());
@@ -147,7 +149,7 @@
}
bool IsFieldInlined(const FieldDescriptor* field) const {
- if (field->containing_oneof()) {
+ if (InRealOneof(field)) {
size_t offset =
static_cast<size_t>(field->containing_type()->field_count() +
field->containing_oneof()->index());
@@ -167,6 +169,7 @@
// Bit index within the bit array of hasbits. Bit order is low-to-high.
uint32 HasBitIndex(const FieldDescriptor* field) const {
+ if (has_bits_offset_ == -1) return static_cast<uint32>(-1);
GOOGLE_DCHECK(HasHasbits());
return has_bit_indices_[field->index()];
}
@@ -262,8 +265,11 @@
int object_size;
};
+struct SCCInfoBase;
+
struct PROTOBUF_EXPORT DescriptorTable {
- bool* is_initialized;
+ mutable bool is_initialized;
+ bool is_eager;
const char* descriptor;
const char* filename;
int size; // of serialized descriptor
@@ -287,7 +293,8 @@
// the descriptor objects. It also constructs the reflection objects. It is
// called the first time anyone calls descriptor() or GetReflection() on one of
// the types defined in the file. AssignDescriptors() is thread-safe.
-void PROTOBUF_EXPORT AssignDescriptors(const DescriptorTable* table);
+void PROTOBUF_EXPORT AssignDescriptors(const DescriptorTable* table,
+ bool eager = false);
// AddDescriptors() is a file-level procedure which adds the encoded
// FileDescriptorProto for this .proto file to the global DescriptorPool for
diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc
index eea5da5..1c9d408 100644
--- a/src/google/protobuf/generated_message_reflection_unittest.cc
+++ b/src/google/protobuf/generated_message_reflection_unittest.cc
@@ -43,15 +43,15 @@
// rather than generated accessors.
#include <google/protobuf/generated_message_reflection.h>
+
#include <memory>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/descriptor.h>
-
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/common.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
diff --git a/src/google/protobuf/generated_message_table_driven.cc b/src/google/protobuf/generated_message_table_driven.cc
index fb82a8e..56f1a6a 100644
--- a/src/google/protobuf/generated_message_table_driven.cc
+++ b/src/google/protobuf/generated_message_table_driven.cc
@@ -35,7 +35,6 @@
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/generated_message_table_driven_lite.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
-#include <google/protobuf/metadata.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite.h>
@@ -47,8 +46,8 @@
namespace {
UnknownFieldSet* MutableUnknownFields(MessageLite* msg, int64 arena_offset) {
- return Raw<InternalMetadataWithArena>(msg, arena_offset)
- ->mutable_unknown_fields();
+ return Raw<InternalMetadata>(msg, arena_offset)
+ ->mutable_unknown_fields<UnknownFieldSet>();
}
struct UnknownFieldHandler {
@@ -95,9 +94,8 @@
bool MergePartialFromCodedStream(MessageLite* msg, const ParseTable& table,
io::CodedInputStream* input) {
- return MergePartialFromCodedStreamImpl<UnknownFieldHandler,
- InternalMetadataWithArena>(msg, table,
- input);
+ return MergePartialFromCodedStreamImpl<UnknownFieldHandler>(msg, table,
+ input);
}
} // namespace internal
diff --git a/src/google/protobuf/generated_message_table_driven_lite.cc b/src/google/protobuf/generated_message_table_driven_lite.cc
index 82de6bc..02e6dac 100644
--- a/src/google/protobuf/generated_message_table_driven_lite.cc
+++ b/src/google/protobuf/generated_message_table_driven_lite.cc
@@ -44,8 +44,8 @@
namespace {
std::string* MutableUnknownFields(MessageLite* msg, int64 arena_offset) {
- return Raw<InternalMetadataWithArenaLite>(msg, arena_offset)
- ->mutable_unknown_fields();
+ return Raw<InternalMetadata>(msg, arena_offset)
+ ->mutable_unknown_fields<std::string>();
}
struct UnknownFieldHandlerLite {
@@ -97,9 +97,8 @@
bool MergePartialFromCodedStreamLite(MessageLite* msg, const ParseTable& table,
io::CodedInputStream* input) {
- return MergePartialFromCodedStreamImpl<UnknownFieldHandlerLite,
- InternalMetadataWithArenaLite>(
- msg, table, input);
+ return MergePartialFromCodedStreamImpl<UnknownFieldHandlerLite>(msg, table,
+ input);
}
} // namespace internal
diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h
index 8cf177b..ae13b36 100644
--- a/src/google/protobuf/generated_message_table_driven_lite.h
+++ b/src/google/protobuf/generated_message_table_driven_lite.h
@@ -37,7 +37,6 @@
#include <google/protobuf/extension_set.h>
#include <google/protobuf/implicit_weak_message.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format_lite.h>
#include <type_traits>
@@ -82,15 +81,6 @@
offset);
}
-template <typename InternalMetadata>
-inline Arena* GetArena(MessageLite* msg, int64 arena_offset) {
- if (PROTOBUF_PREDICT_FALSE(arena_offset == -1)) {
- return NULL;
- }
-
- return Raw<InternalMetadata>(msg, arena_offset)->arena();
-}
-
inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64 extension_offset) {
if (extension_offset == -1) {
return NULL;
@@ -290,9 +280,13 @@
}
utf8_string_data = field->Get();
} break;
+ default:
+ PROTOBUF_ASSUME(false);
}
break;
}
+ default:
+ PROTOBUF_ASSUME(false);
}
if (kValidateUtf8) {
@@ -304,8 +298,7 @@
return true;
}
-template <typename UnknownFieldHandler, typename InternalMetadata,
- Cardinality cardinality>
+template <typename UnknownFieldHandler, Cardinality cardinality>
inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input,
MessageLite* msg, uint32* presence,
uint32 presence_index, int64 offset, uint32 tag,
@@ -328,12 +321,13 @@
AddField(msg, offset, value);
break;
case Cardinality_ONEOF:
- ClearOneofField(table.fields[presence[presence_index]],
- GetArena<InternalMetadata>(msg, table.arena_offset),
+ ClearOneofField(table.fields[presence[presence_index]], msg->GetArena(),
msg);
SetOneofField(msg, presence, presence_index, offset, field_number,
value);
break;
+ default:
+ PROTOBUF_ASSUME(false);
}
} else {
UnknownFieldHandler::Varint(msg, table, tag, value);
@@ -372,8 +366,7 @@
}
};
-template <typename UnknownFieldHandler, typename InternalMetadata,
- uint32 kMaxTag>
+template <typename UnknownFieldHandler, uint32 kMaxTag>
bool MergePartialFromCodedStreamInlined(MessageLite* msg,
const ParseTable& table,
io::CodedInputStream* input) {
@@ -419,9 +412,6 @@
const unsigned char processing_type = data->processing_type;
if (data->normal_wiretype == static_cast<unsigned char>(wire_type)) {
- // TODO(ckennelly): Use a computed goto on GCC/LLVM or otherwise eliminate
- // the bounds check on processing_type.
-
switch (processing_type) {
#define HANDLE_TYPE(TYPE, CPPTYPE) \
case (WireFormatLite::TYPE_##TYPE): { \
@@ -451,8 +441,8 @@
CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \
return false; \
} \
- ClearOneofField(table.fields[oneof_case[presence_index]], \
- GetArena<InternalMetadata>(msg, table.arena_offset), msg); \
+ ClearOneofField(table.fields[oneof_case[presence_index]], msg->GetArena(), \
+ msg); \
SetOneofField(msg, oneof_case, presence_index, offset, field_number, \
value); \
break; \
@@ -480,8 +470,7 @@
case WireFormatLite::TYPE_STRING:
#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
{
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const void* default_ptr = table.aux[field_number].strings.default_ptr;
if (PROTOBUF_PREDICT_FALSE(
@@ -498,8 +487,7 @@
case TYPE_STRING_INLINED:
#endif // !GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
{
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const void* default_ptr = table.aux[field_number].strings.default_ptr;
if (PROTOBUF_PREDICT_FALSE(
@@ -516,8 +504,7 @@
case WireFormatLite::TYPE_STRING | kOneofMask:
#endif // !GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
{
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
const void* default_ptr = table.aux[field_number].strings.default_ptr;
@@ -541,8 +528,7 @@
case TYPE_STRING_INLINED | kRepeatedMask:
#endif // !GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
{
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const void* default_ptr = table.aux[field_number].strings.default_ptr;
if (PROTOBUF_PREDICT_FALSE(
@@ -556,8 +542,7 @@
}
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
case (WireFormatLite::TYPE_STRING): {
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const void* default_ptr = table.aux[field_number].strings.default_ptr;
const char* field_name = table.aux[field_number].strings.field_name;
@@ -572,8 +557,7 @@
}
case TYPE_STRING_INLINED | kRepeatedMask:
case (WireFormatLite::TYPE_STRING) | kRepeatedMask: {
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const void* default_ptr = table.aux[field_number].strings.default_ptr;
const char* field_name = table.aux[field_number].strings.field_name;
@@ -587,8 +571,7 @@
break;
}
case (WireFormatLite::TYPE_STRING) | kOneofMask: {
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
const void* default_ptr = table.aux[field_number].strings.default_ptr;
const char* field_name = table.aux[field_number].strings.field_name;
@@ -609,8 +592,7 @@
#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
case WireFormatLite::TYPE_ENUM: {
if (PROTOBUF_PREDICT_FALSE(
- (!HandleEnum<UnknownFieldHandler, InternalMetadata,
- Cardinality_SINGULAR>(
+ (!HandleEnum<UnknownFieldHandler, Cardinality_SINGULAR>(
table, input, msg, has_bits, presence_index, offset, tag,
field_number)))) {
return false;
@@ -619,8 +601,7 @@
}
case WireFormatLite::TYPE_ENUM | kRepeatedMask: {
if (PROTOBUF_PREDICT_FALSE(
- (!HandleEnum<UnknownFieldHandler, InternalMetadata,
- Cardinality_REPEATED>(
+ (!HandleEnum<UnknownFieldHandler, Cardinality_REPEATED>(
table, input, msg, has_bits, presence_index, offset, tag,
field_number)))) {
return false;
@@ -630,10 +611,9 @@
case WireFormatLite::TYPE_ENUM | kOneofMask: {
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
if (PROTOBUF_PREDICT_FALSE(
- (!HandleEnum<UnknownFieldHandler, InternalMetadata,
- Cardinality_ONEOF>(table, input, msg, oneof_case,
- presence_index, offset, tag,
- field_number)))) {
+ (!HandleEnum<UnknownFieldHandler, Cardinality_ONEOF>(
+ table, input, msg, oneof_case, presence_index, offset,
+ tag, field_number)))) {
return false;
}
break;
@@ -644,8 +624,7 @@
MessageLite* submsg = *submsg_holder;
if (submsg == NULL) {
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const MessageLite* prototype =
table.aux[field_number].messages.default_message();
submsg = prototype->New(arena);
@@ -681,8 +660,7 @@
MessageLite* submsg = *submsg_holder;
if (submsg == NULL) {
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const MessageLite* prototype =
table.aux[field_number].messages.default_message();
if (prototype == NULL) {
@@ -720,8 +698,7 @@
break;
}
case WireFormatLite::TYPE_MESSAGE | kOneofMask: {
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
MessageLite** submsg_holder = Raw<MessageLite*>(msg, offset);
ResetOneofField<ProcessingType_MESSAGE>(
@@ -738,8 +715,7 @@
}
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
case TYPE_STRING_INLINED: {
- Arena* const arena =
- GetArena<InternalMetadata>(msg, table.arena_offset);
+ Arena* const arena = msg->GetArena();
const void* default_ptr = table.aux[field_number].strings.default_ptr;
const char* field_name = table.aux[field_number].strings.field_name;
@@ -766,7 +742,7 @@
return true;
}
default:
- break;
+ PROTOBUF_ASSUME(false);
}
} else if (data->packed_wiretype == static_cast<unsigned char>(wire_type)) {
// Non-packable fields have their packed_wiretype masked with
@@ -778,8 +754,6 @@
GOOGLE_DCHECK_NE(TYPE_BYTES_INLINED | kRepeatedMask, processing_type);
GOOGLE_DCHECK_NE(TYPE_STRING_INLINED | kRepeatedMask, processing_type);
- // TODO(ckennelly): Use a computed goto on GCC/LLVM.
- //
// Mask out kRepeatedMask bit, allowing the jump table to be smaller.
switch (static_cast<WireFormatLite::FieldType>(processing_type ^
kRepeatedMask)) {
@@ -813,7 +787,7 @@
#undef HANDLE_PACKED_TYPE
case WireFormatLite::TYPE_ENUM: {
// To avoid unnecessarily calling MutableUnknownFields (which mutates
- // InternalMetadataWithArena) when all inputs in the repeated series
+ // InternalMetadata) when all inputs in the repeated series
// are valid, we implement our own parser rather than call
// WireFormat::ReadPackedEnumPreserveUnknowns.
uint32 length;
@@ -852,7 +826,7 @@
GOOGLE_DCHECK(false);
return false;
default:
- break;
+ PROTOBUF_ASSUME(false);
}
} else {
if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) {
@@ -876,23 +850,21 @@
}
}
-template <typename UnknownFieldHandler, typename InternalMetadata>
+template <typename UnknownFieldHandler>
bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
io::CodedInputStream* input) {
// The main beneficial cutoff values are 1 and 2 byte tags.
// Instantiate calls with the appropriate upper tag range
if (table.max_field_number <= (0x7F >> 3)) {
- return MergePartialFromCodedStreamInlined<UnknownFieldHandler,
- InternalMetadata, 0x7F>(
+ return MergePartialFromCodedStreamInlined<UnknownFieldHandler, 0x7F>(
msg, table, input);
} else if (table.max_field_number <= (0x3FFF >> 3)) {
- return MergePartialFromCodedStreamInlined<UnknownFieldHandler,
- InternalMetadata, 0x3FFF>(
+ return MergePartialFromCodedStreamInlined<UnknownFieldHandler, 0x3FFF>(
msg, table, input);
} else {
return MergePartialFromCodedStreamInlined<
- UnknownFieldHandler, InternalMetadata,
- std::numeric_limits<uint32>::max()>(msg, table, input);
+ UnknownFieldHandler, std::numeric_limits<uint32>::max()>(msg, table,
+ input);
}
}
diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc
index bdeabdd..15eb9d6 100644
--- a/src/google/protobuf/generated_message_util.cc
+++ b/src/google/protobuf/generated_message_util.cc
@@ -718,8 +718,8 @@
uint32 has_offset,
io::CodedOutputStream* output) {
output->WriteString(
- reinterpret_cast<const InternalMetadataWithArenaLite*>(ptr + offset)
- ->unknown_fields());
+ reinterpret_cast<const InternalMetadata*>(ptr + offset)
+ ->unknown_fields<std::string>(&internal::GetEmptyString));
}
MessageLite* DuplicateIfNonNullInternal(MessageLite* message) {
diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h
index 9754675..7cae4e1 100644
--- a/src/google/protobuf/generated_message_util.h
+++ b/src/google/protobuf/generated_message_util.h
@@ -67,6 +67,7 @@
namespace protobuf {
class Arena;
+class Message;
namespace io {
class CodedInputStream;
@@ -149,6 +150,8 @@
MessageLite* submessage,
Arena* submessage_arena);
PROTOBUF_EXPORT void GenericSwap(MessageLite* m1, MessageLite* m2);
+// We specialize GenericSwap for non-lite messages to benefit from reflection.
+PROTOBUF_EXPORT void GenericSwap(Message* m1, Message* m2);
template <typename T>
T* DuplicateIfNonNull(T* message) {
@@ -190,7 +193,7 @@
kUninitialized = -1, // initial state
};
#if defined(_MSC_VER) && !defined(__clang__)
- // MSVC doesnt make std::atomic constant initialized. This union trick
+ // MSVC doesn't make std::atomic constant initialized. This union trick
// makes it so.
union {
int visit_status_to_make_linker_init;
diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h
index a3348da..ec028eb 100644
--- a/src/google/protobuf/implicit_weak_message.h
+++ b/src/google/protobuf/implicit_weak_message.h
@@ -56,8 +56,8 @@
// message type does not get linked into the binary.
class PROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
public:
- ImplicitWeakMessage() : arena_(NULL) {}
- explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {}
+ ImplicitWeakMessage() {}
+ explicit ImplicitWeakMessage(Arena* arena) : MessageLite(arena) {}
static const ImplicitWeakMessage* default_instance();
@@ -68,8 +68,6 @@
return Arena::CreateMessage<ImplicitWeakMessage>(arena);
}
- Arena* GetArena() const override { return arena_; }
-
void Clear() override { data_.clear(); }
bool IsInitialized() const override { return true; }
@@ -93,7 +91,6 @@
typedef void InternalArenaConstructable_;
private:
- Arena* const arena_;
std::string data_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImplicitWeakMessage);
};
@@ -103,7 +100,7 @@
class ImplicitWeakTypeHandler {
public:
typedef MessageLite Type;
- static const bool Moveable = false;
+ static constexpr bool Moveable = false;
static inline MessageLite* NewFromPrototype(const MessageLite* prototype,
Arena* arena = NULL) {
diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h
old mode 100755
new mode 100644
index 256eaf9..5f9feb8
--- a/src/google/protobuf/io/coded_stream.h
+++ b/src/google/protobuf/io/coded_stream.h
@@ -817,7 +817,7 @@
return is_serialization_deterministic_;
}
- // The number of bytes writen to the stream at position ptr, relative to the
+ // The number of bytes written to the stream at position ptr, relative to the
// stream's overall position.
int64 ByteCount(uint8* ptr) const;
@@ -1171,7 +1171,7 @@
// Returns the number of bytes needed to encode the given value as a varint.
static size_t VarintSize64(uint64 value);
- // If negative, 10 bytes. Otheriwse, same as VarintSize32().
+ // If negative, 10 bytes. Otherwise, same as VarintSize32().
static size_t VarintSize32SignExtended(int32 value);
// Compile-time equivalent of VarintSize32().
diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc
index 7a80aed..266b902 100644
--- a/src/google/protobuf/io/coded_stream_unittest.cc
+++ b/src/google/protobuf/io/coded_stream_unittest.cc
@@ -132,7 +132,7 @@
class CodedStreamTest : public testing::Test {
protected:
// Buffer used during most of the tests. This assumes tests run sequentially.
- static const int kBufferSize = 1024 * 64;
+ static constexpr int kBufferSize = 1024 * 64;
static uint8 buffer_[kBufferSize];
};
diff --git a/src/google/protobuf/io/io_win32.cc b/src/google/protobuf/io/io_win32.cc
old mode 100755
new mode 100644
diff --git a/src/google/protobuf/io/io_win32.h b/src/google/protobuf/io/io_win32.h
old mode 100755
new mode 100644
diff --git a/src/google/protobuf/io/io_win32_unittest.cc b/src/google/protobuf/io/io_win32_unittest.cc
old mode 100755
new mode 100644
index f0ca47c..c50f68d
--- a/src/google/protobuf/io/io_win32_unittest.cc
+++ b/src/google/protobuf/io/io_win32_unittest.cc
@@ -372,7 +372,7 @@
EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1").c_str(), nullptr));
EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1\\" + kUtf16Text).c_str(), nullptr));
// Ensure that we can create a very similarly named directory using mkdir.
- // We don't attemp to delete and recreate the same directory, because on
+ // We don't attempt to delete and recreate the same directory, because on
// Windows, deleting files and directories seems to be asynchronous.
EXPECT_EQ(mkdir((test_tmpdir + "\\2").c_str(), 0644), 0);
EXPECT_EQ(mkdir((test_tmpdir + "\\2\\" + kUtf8Text).c_str(), 0644), 0);
diff --git a/src/google/protobuf/io/printer.cc b/src/google/protobuf/io/printer.cc
index f8d4d2b..95b03f4 100644
--- a/src/google/protobuf/io/printer.cc
+++ b/src/google/protobuf/io/printer.cc
@@ -305,7 +305,7 @@
}
const char* Printer::WriteVariable(
- const std::vector<string>& args,
+ const std::vector<std::string>& args,
const std::map<std::string, std::string>& vars, const char* format,
int* arg_index, std::vector<AnnotationCollector::Annotation>* annotations) {
auto start = format;
diff --git a/src/google/protobuf/io/printer.h b/src/google/protobuf/io/printer.h
old mode 100755
new mode 100644
index c00fa29..64336eb
--- a/src/google/protobuf/io/printer.h
+++ b/src/google/protobuf/io/printer.h
@@ -194,8 +194,8 @@
~Printer();
- // Link a subsitution variable emitted by the last call to Print to the object
- // described by descriptor.
+ // Link a substitution variable emitted by the last call to Print to the
+ // object described by descriptor.
template <typename SomeDescriptor>
void Annotate(const char* varname, const SomeDescriptor* descriptor) {
Annotate(varname, varname, descriptor);
@@ -218,7 +218,7 @@
Annotate(begin_varname, end_varname, descriptor->file()->name(), path);
}
- // Link a subsitution variable emitted by the last call to Print to the file
+ // Link a substitution variable emitted by the last call to Print to the file
// with path file_name.
void Annotate(const char* varname, const std::string& file_name) {
Annotate(varname, varname, file_name);
diff --git a/src/google/protobuf/io/printer_unittest.cc b/src/google/protobuf/io/printer_unittest.cc
index ca45d67..ed54d1d 100644
--- a/src/google/protobuf/io/printer_unittest.cc
+++ b/src/google/protobuf/io/printer_unittest.cc
@@ -573,7 +573,7 @@
EXPECT_TRUE(printer.failed());
// Buffer should contain the first 17 bytes written.
- EXPECT_EQ("0123456789abcdef<", string(buffer, sizeof(buffer)));
+ EXPECT_EQ("0123456789abcdef<", std::string(buffer, sizeof(buffer)));
}
TEST(Printer, WriteFailureExact) {
@@ -595,7 +595,7 @@
EXPECT_TRUE(printer.failed());
// Buffer should contain the first 16 bytes written.
- EXPECT_EQ("0123456789abcdef", string(buffer, sizeof(buffer)));
+ EXPECT_EQ("0123456789abcdef", std::string(buffer, sizeof(buffer)));
}
TEST(Printer, FormatInternal) {
diff --git a/src/google/protobuf/io/tokenizer_unittest.cc b/src/google/protobuf/io/tokenizer_unittest.cc
index 8ee9ab5..b14eddf 100644
--- a/src/google/protobuf/io/tokenizer_unittest.cc
+++ b/src/google/protobuf/io/tokenizer_unittest.cc
@@ -56,7 +56,7 @@
// Data-Driven Test Infrastructure
// TODO(kenton): This is copied from coded_stream_unittest. This is
-// temporary until these fetaures are integrated into gTest itself.
+// temporary until these features are integrated into gTest itself.
// TEST_1D and TEST_2D are macros I'd eventually like to see added to
// gTest. These macros can be used to declare tests which should be
diff --git a/src/google/protobuf/io/zero_copy_stream_impl_lite.h b/src/google/protobuf/io/zero_copy_stream_impl_lite.h
index 138b2d3..26572cc 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl_lite.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.h
@@ -231,7 +231,7 @@
CopyingInputStream* copying_stream_;
bool owns_copying_stream_;
- // True if we have seen a permenant error from the underlying stream.
+ // True if we have seen a permanent error from the underlying stream.
bool failed_;
// The current position of copying_stream_, relative to the point where
@@ -320,7 +320,7 @@
CopyingOutputStream* copying_stream_;
bool owns_copying_stream_;
- // True if we have seen a permenant error from the underlying stream.
+ // True if we have seen a permanent error from the underlying stream.
bool failed_;
// The current position of copying_stream_, relative to the point where
diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h
index bc97701..8710164 100644
--- a/src/google/protobuf/map.h
+++ b/src/google/protobuf/map.h
@@ -37,10 +37,12 @@
#ifndef GOOGLE_PROTOBUF_MAP_H__
#define GOOGLE_PROTOBUF_MAP_H__
+#include <functional>
#include <initializer_list>
#include <iterator>
#include <limits> // To support Visual Studio 2008
#include <set>
+#include <type_traits>
#include <utility>
#include <google/protobuf/stubs/common.h>
@@ -83,16 +85,145 @@
class DynamicMapField;
class GeneratedMessageReflection;
+
+// re-implement std::allocator to use arena allocator for memory allocation.
+// Used for Map implementation. Users should not use this class
+// directly.
+template <typename U>
+class MapAllocator {
+ public:
+ using value_type = U;
+ using pointer = value_type*;
+ using const_pointer = const value_type*;
+ using reference = value_type&;
+ using const_reference = const value_type&;
+ using size_type = size_t;
+ using difference_type = ptrdiff_t;
+
+ MapAllocator() : arena_(nullptr) {}
+ explicit MapAllocator(Arena* arena) : arena_(arena) {}
+ template <typename X>
+ MapAllocator(const MapAllocator<X>& allocator) // NOLINT(runtime/explicit)
+ : arena_(allocator.arena()) {}
+
+ pointer allocate(size_type n, const void* /* hint */ = nullptr) {
+ // If arena is not given, malloc needs to be called which doesn't
+ // construct element object.
+ if (arena_ == nullptr) {
+ return static_cast<pointer>(::operator new(n * sizeof(value_type)));
+ } else {
+ return reinterpret_cast<pointer>(
+ Arena::CreateArray<uint8>(arena_, n * sizeof(value_type)));
+ }
+ }
+
+ void deallocate(pointer p, size_type n) {
+ if (arena_ == nullptr) {
+#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
+ ::operator delete(p, n * sizeof(value_type));
+#else
+ (void)n;
+ ::operator delete(p);
+#endif
+ }
+ }
+
+#if __cplusplus >= 201103L && !defined(GOOGLE_PROTOBUF_OS_APPLE) && \
+ !defined(GOOGLE_PROTOBUF_OS_NACL) && \
+ !defined(GOOGLE_PROTOBUF_OS_EMSCRIPTEN)
+ template <class NodeType, class... Args>
+ void construct(NodeType* p, Args&&... args) {
+ // Clang 3.6 doesn't compile static casting to void* directly. (Issue
+ // #1266) According C++ standard 5.2.9/1: "The static_cast operator shall
+ // not cast away constness". So first the maybe const pointer is casted to
+ // const void* and after the const void* is const casted.
+ new (const_cast<void*>(static_cast<const void*>(p)))
+ NodeType(std::forward<Args>(args)...);
+ }
+
+ template <class NodeType>
+ void destroy(NodeType* p) {
+ p->~NodeType();
+ }
+#else
+ void construct(pointer p, const_reference t) { new (p) value_type(t); }
+
+ void destroy(pointer p) { p->~value_type(); }
+#endif
+
+ template <typename X>
+ struct rebind {
+ using other = MapAllocator<X>;
+ };
+
+ template <typename X>
+ bool operator==(const MapAllocator<X>& other) const {
+ return arena_ == other.arena_;
+ }
+
+ template <typename X>
+ bool operator!=(const MapAllocator<X>& other) const {
+ return arena_ != other.arena_;
+ }
+
+ // To support Visual Studio 2008
+ size_type max_size() const {
+ // parentheses around (std::...:max) prevents macro warning of max()
+ return (std::numeric_limits<size_type>::max)();
+ }
+
+ // To support gcc-4.4, which does not properly
+ // support templated friend classes
+ Arena* arena() const { return arena_; }
+
+ private:
+ using DestructorSkippable_ = void;
+ Arena* const arena_;
+};
+
+template <typename Key>
+struct DerefCompare {
+ bool operator()(const Key* n0, const Key* n1) const { return *n0 < *n1; }
+};
+
+// This class is used to get trivially destructible views of std::string and
+// MapKey, which are the only non-trivially destructible allowed key types.
+template <typename Key>
+class KeyView {
+ public:
+ KeyView(const Key& key) : key_(&key) {} // NOLINT(runtime/explicit)
+
+ const Key& get() const { return *key_; }
+ // Allows implicit conversions to `const Key&`, which allows us to use the
+ // hasher defined for Key.
+ operator const Key&() const { return get(); } // NOLINT(runtime/explicit)
+
+ bool operator==(const KeyView& other) const { return get() == other.get(); }
+ bool operator==(const Key& other) const { return get() == other; }
+ bool operator<(const KeyView& other) const { return get() < other.get(); }
+ bool operator<(const Key& other) const { return get() < other; }
+
+ private:
+ const Key* key_;
+};
+
+// Allows the InnerMap type to support skippable destruction.
+template <typename Key>
+struct GetTrivialKey {
+ using type =
+ typename std::conditional<std::is_trivially_destructible<Key>::value, Key,
+ KeyView<Key>>::type;
+};
+
} // namespace internal
// This is the class for Map's internal value_type. Instead of using
// std::pair as value_type, we use this class which provides us more control of
// its process of construction and destruction.
template <typename Key, typename T>
-class MapPair {
- public:
- typedef const Key first_type;
- typedef T second_type;
+struct MapPair {
+ using first_type = const Key;
+ using second_type = T;
MapPair(const Key& other_first, const T& other_second)
: first(other_first), second(other_second) {}
@@ -103,7 +234,7 @@
// Implicitly convertible to std::pair of compatible types.
template <typename T1, typename T2>
- operator std::pair<T1, T2>() const {
+ operator std::pair<T1, T2>() const { // NOLINT(runtime/explicit)
return std::pair<T1, T2>(first, second);
}
@@ -128,23 +259,23 @@
template <typename Key, typename T>
class Map {
public:
- typedef Key key_type;
- typedef T mapped_type;
- typedef MapPair<Key, T> value_type;
+ using key_type = Key;
+ using mapped_type = T;
+ using value_type = MapPair<Key, T>;
- typedef value_type* pointer;
- typedef const value_type* const_pointer;
- typedef value_type& reference;
- typedef const value_type& const_reference;
+ using pointer = value_type*;
+ using const_pointer = const value_type*;
+ using reference = value_type&;
+ using const_reference = const value_type&;
- typedef size_t size_type;
- typedef hash<Key> hasher;
+ using size_type = size_t;
+ using hasher = std::hash<Key>;
- Map() : arena_(NULL), default_enum_value_(0) { Init(); }
+ Map() : arena_(nullptr), default_enum_value_(0) { Init(); }
explicit Map(Arena* arena) : arena_(arena), default_enum_value_(0) { Init(); }
Map(const Map& other)
- : arena_(NULL), default_enum_value_(other.default_enum_value_) {
+ : arena_(nullptr), default_enum_value_(other.default_enum_value_) {
Init();
insert(other.begin(), other.end());
}
@@ -169,138 +300,44 @@
template <class InputIt>
Map(const InputIt& first, const InputIt& last)
- : arena_(NULL), default_enum_value_(0) {
+ : arena_(nullptr), default_enum_value_(0) {
Init();
insert(first, last);
}
~Map() {
clear();
- if (arena_ == NULL) {
+ if (arena_ == nullptr) {
delete elements_;
}
}
private:
- void Init() {
- elements_ =
- Arena::Create<InnerMap>(arena_, 0u, hasher(), Allocator(arena_));
- }
+ void Init() { elements_ = Arena::CreateMessage<InnerMap>(arena_, 0u); }
- // re-implement std::allocator to use arena allocator for memory allocation.
- // Used for Map implementation. Users should not use this class
- // directly.
- template <typename U>
- class MapAllocator {
- public:
- typedef U value_type;
- typedef value_type* pointer;
- typedef const value_type* const_pointer;
- typedef value_type& reference;
- typedef const value_type& const_reference;
- typedef size_t size_type;
- typedef ptrdiff_t difference_type;
-
- MapAllocator() : arena_(NULL) {}
- explicit MapAllocator(Arena* arena) : arena_(arena) {}
- template <typename X>
- MapAllocator(const MapAllocator<X>& allocator)
- : arena_(allocator.arena()) {}
-
- pointer allocate(size_type n, const void* /* hint */ = 0) {
- // If arena is not given, malloc needs to be called which doesn't
- // construct element object.
- if (arena_ == NULL) {
- return static_cast<pointer>(::operator new(n * sizeof(value_type)));
- } else {
- return reinterpret_cast<pointer>(
- Arena::CreateArray<uint8>(arena_, n * sizeof(value_type)));
- }
- }
-
- void deallocate(pointer p, size_type n) {
- if (arena_ == NULL) {
-#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
- ::operator delete(p, n * sizeof(value_type));
-#else
- (void)n;
- ::operator delete(p);
-#endif
- }
- }
-
-#if __cplusplus >= 201103L && !defined(GOOGLE_PROTOBUF_OS_APPLE) && \
- !defined(GOOGLE_PROTOBUF_OS_NACL) && \
- !defined(GOOGLE_PROTOBUF_OS_EMSCRIPTEN)
- template <class NodeType, class... Args>
- void construct(NodeType* p, Args&&... args) {
- // Clang 3.6 doesn't compile static casting to void* directly. (Issue
- // #1266) According C++ standard 5.2.9/1: "The static_cast operator shall
- // not cast away constness". So first the maybe const pointer is casted to
- // const void* and after the const void* is const casted.
- new (const_cast<void*>(static_cast<const void*>(p)))
- NodeType(std::forward<Args>(args)...);
- }
-
- template <class NodeType>
- void destroy(NodeType* p) {
- p->~NodeType();
- }
-#else
- void construct(pointer p, const_reference t) { new (p) value_type(t); }
-
- void destroy(pointer p) { p->~value_type(); }
-#endif
-
- template <typename X>
- struct rebind {
- typedef MapAllocator<X> other;
- };
-
- template <typename X>
- bool operator==(const MapAllocator<X>& other) const {
- return arena_ == other.arena_;
- }
-
- template <typename X>
- bool operator!=(const MapAllocator<X>& other) const {
- return arena_ != other.arena_;
- }
-
- // To support Visual Studio 2008
- size_type max_size() const {
- // parentheses around (std::...:max) prevents macro warning of max()
- return (std::numeric_limits<size_type>::max)();
- }
-
- // To support gcc-4.4, which does not properly
- // support templated friend classes
- Arena* arena() const { return arena_; }
-
- private:
- typedef void DestructorSkippable_;
- Arena* const arena_;
- };
-
- // InnerMap's key type is Key and its value type is value_type*. We use a
- // custom class here and for Node, below, to ensure that k_ is at offset 0,
- // allowing safe conversion from pointer to Node to pointer to Key, and vice
- // versa when appropriate.
+ // InnerMap's key type is TrivialKey and its value type is value_type*. We
+ // use a custom class here and for Node, below, to ensure that k_ is at offset
+ // 0, allowing safe conversion from pointer to Node to pointer to TrivialKey,
+ // and vice versa when appropriate. We use GetTrivialKey to adapt Key to
+ // be a trivially destructible view if Key is not already trivially
+ // destructible. This view points into the Key inside v_ once it's
+ // initialized.
+ using TrivialKey = typename internal::GetTrivialKey<Key>::type;
class KeyValuePair {
public:
- KeyValuePair(const Key& k, value_type* v) : k_(k), v_(v) {}
+ KeyValuePair(const TrivialKey& k, value_type* v) : k_(k), v_(v) {}
- const Key& key() const { return k_; }
- Key& key() { return k_; }
+ const TrivialKey& key() const { return k_; }
+ TrivialKey& key() { return k_; }
value_type* value() const { return v_; }
value_type*& value() { return v_; }
private:
- Key k_;
+ TrivialKey k_;
value_type* v_;
};
- typedef MapAllocator<KeyValuePair> Allocator;
+ using Allocator = internal::MapAllocator<KeyValuePair>;
// InnerMap is a generic hash-based map. It doesn't contain any
// protocol-buffer-specific logic. It is a chaining hash map with the
@@ -317,7 +354,7 @@
// 2. The number of buckets is a power of two.
// 3. Buckets are converted to trees in pairs: if we convert bucket b then
// buckets b and b^1 will share a tree. Invariant: buckets b and b^1 have
- // the same non-NULL value iff they are sharing a tree. (An alternative
+ // the same non-null value iff they are sharing a tree. (An alternative
// implementation strategy would be to have a tag bit per bucket.)
// 4. As is typical for hash_map and such, the Keys and Values are always
// stored in linked list nodes. Pointers to elements are never invalidated
@@ -327,27 +364,36 @@
// 6. Once we've tree-converted a bucket, it is never converted back. However,
// the items a tree contains may wind up assigned to trees or lists upon a
// rehash.
- // 7. The code requires no C++ features from C++11 or later.
+ // 7. The code requires no C++ features from C++14 or later.
// 8. Mutations to a map do not invalidate the map's iterators, pointers to
// elements, or references to elements.
// 9. Except for erase(iterator), any non-const method can reorder iterators.
+ // 10. InnerMap's key is TrivialKey, which is either Key, if Key is trivially
+ // destructible, or a trivially destructible view of Key otherwise. This
+ // allows InnerMap's destructor to be skipped when InnerMap is
+ // arena-allocated.
class InnerMap : private hasher {
public:
- typedef value_type* Value;
+ using Value = value_type*;
- InnerMap(size_type n, hasher h, Allocator alloc)
- : hasher(h),
+ explicit InnerMap(size_type n) : InnerMap(nullptr, n) {}
+ InnerMap(Arena* arena, size_type n)
+ : hasher(),
num_elements_(0),
seed_(Seed()),
- table_(NULL),
- alloc_(alloc) {
+ table_(nullptr),
+ alloc_(arena) {
n = TableSize(n);
table_ = CreateEmptyTable(n);
num_buckets_ = index_of_first_non_null_ = n;
+ static_assert(
+ std::is_trivially_destructible<KeyValuePair>::value,
+ "We require KeyValuePair to be trivially destructible so that we can "
+ "skip InnerMap's destructor when it's arena allocated.");
}
~InnerMap() {
- if (table_ != NULL) {
+ if (table_ != nullptr) {
clear();
Dealloc<void*>(table_, num_buckets_);
}
@@ -364,36 +410,36 @@
// This is safe only if the given pointer is known to point to a Key that is
// part of a Node.
- static Node* NodePtrFromKeyPtr(Key* k) {
+ static Node* NodePtrFromKeyPtr(TrivialKey* k) {
return reinterpret_cast<Node*>(k);
}
- static Key* KeyPtrFromNodePtr(Node* node) { return &node->kv.key(); }
+ static TrivialKey* KeyPtrFromNodePtr(Node* node) { return &node->kv.key(); }
// Trees. The payload type is pointer to Key, so that we can query the tree
// with Keys that are not in any particular data structure. When we insert,
// though, the pointer is always pointing to a Key that is inside a Node.
- struct KeyCompare {
- bool operator()(const Key* n0, const Key* n1) const { return *n0 < *n1; }
- };
- typedef typename Allocator::template rebind<Key*>::other KeyPtrAllocator;
- typedef std::set<Key*, KeyCompare, KeyPtrAllocator> Tree;
- typedef typename Tree::iterator TreeIterator;
+ using KeyPtrAllocator =
+ typename Allocator::template rebind<TrivialKey*>::other;
+ using Tree = std::set<TrivialKey*, internal::DerefCompare<TrivialKey>,
+ KeyPtrAllocator>;
+ using TreeIterator = typename Tree::iterator;
// iterator and const_iterator are instantiations of iterator_base.
template <typename KeyValueType>
- struct iterator_base {
- typedef KeyValueType& reference;
- typedef KeyValueType* pointer;
+ class iterator_base {
+ public:
+ using reference = KeyValueType&;
+ using pointer = KeyValueType*;
// Invariants:
// node_ is always correct. This is handy because the most common
// operations are operator* and operator-> and they only use node_.
- // When node_ is set to a non-NULL value, all the other non-const fields
+ // When node_ is set to a non-null value, all the other non-const fields
// are updated to be correct also, but those fields can become stale
// if the underlying map is modified. When those fields are needed they
// are rechecked, and updated if necessary.
- iterator_base() : node_(NULL), m_(NULL), bucket_index_(0) {}
+ iterator_base() : node_(nullptr), m_(nullptr), bucket_index_(0) {}
explicit iterator_base(const InnerMap* m) : m_(m) {
SearchFrom(m->index_of_first_non_null_);
@@ -417,11 +463,11 @@
}
// Advance through buckets, looking for the first that isn't empty.
- // If nothing non-empty is found then leave node_ == NULL.
+ // If nothing non-empty is found then leave node_ == nullptr.
void SearchFrom(size_type start_bucket) {
GOOGLE_DCHECK(m_->index_of_first_non_null_ == m_->num_buckets_ ||
- m_->table_[m_->index_of_first_non_null_] != NULL);
- node_ = NULL;
+ m_->table_[m_->index_of_first_non_null_] != nullptr);
+ node_ = nullptr;
for (bucket_index_ = start_bucket; bucket_index_ < m_->num_buckets_;
bucket_index_++) {
if (m_->TableEntryIsNonEmptyList(bucket_index_)) {
@@ -447,7 +493,7 @@
}
iterator_base& operator++() {
- if (node_->next == NULL) {
+ if (node_->next == nullptr) {
TreeIterator tree_it;
const bool is_list = revalidate_if_necessary(&tree_it);
if (is_list) {
@@ -473,12 +519,12 @@
return tmp;
}
- // Assumes node_ and m_ are correct and non-NULL, but other fields may be
+ // Assumes node_ and m_ are correct and non-null, but other fields may be
// stale. Fix them as needed. Then return true iff node_ points to a
// Node in a list. If false is returned then *it is modified to be
// a valid iterator for node_.
bool revalidate_if_necessary(TreeIterator* it) {
- GOOGLE_DCHECK(node_ != NULL && m_ != NULL);
+ GOOGLE_DCHECK(node_ != nullptr && m_ != nullptr);
// Force bucket_index_ to be in range.
bucket_index_ &= (m_->num_buckets_ - 1);
// Common case: the bucket we think is relevant points to node_.
@@ -487,7 +533,7 @@
// but not at the head.
if (m_->TableEntryIsNonEmptyList(bucket_index_)) {
Node* l = static_cast<Node*>(m_->table_[bucket_index_]);
- while ((l = l->next) != NULL) {
+ while ((l = l->next) != nullptr) {
if (l == node_) {
return true;
}
@@ -496,7 +542,7 @@
// Well, bucket_index_ still might be correct, but probably
// not. Revalidate just to be sure. This case is rare enough that we
// don't worry about potential optimizations, such as having a custom
- // find-like method that compares Node* instead of const Key&.
+ // find-like method that compares Node* instead of TrivialKey.
iterator_base i(m_->find(*KeyPtrFromNodePtr(node_), it));
bucket_index_ = i.bucket_index_;
return m_->TableEntryIsList(bucket_index_);
@@ -508,8 +554,8 @@
};
public:
- typedef iterator_base<KeyValuePair> iterator;
- typedef iterator_base<const KeyValuePair> const_iterator;
+ using iterator = iterator_base<KeyValuePair>;
+ using const_iterator = iterator_base<const KeyValuePair>;
iterator begin() { return iterator(this); }
iterator end() { return iterator(); }
@@ -520,16 +566,16 @@
for (size_type b = 0; b < num_buckets_; b++) {
if (TableEntryIsNonEmptyList(b)) {
Node* node = static_cast<Node*>(table_[b]);
- table_[b] = NULL;
+ table_[b] = nullptr;
do {
Node* next = node->next;
DestroyNode(node);
node = next;
- } while (node != NULL);
+ } while (node != nullptr);
} else if (TableEntryIsTree(b)) {
Tree* tree = static_cast<Tree*>(table_[b]);
GOOGLE_DCHECK(table_[b] == table_[b + 1] && (b & 1) == 0);
- table_[b] = table_[b + 1] = NULL;
+ table_[b] = table_[b + 1] = nullptr;
typename Tree::iterator tree_it = tree->begin();
do {
Node* node = NodePtrFromKeyPtr(*tree_it);
@@ -555,15 +601,15 @@
size_type size() const { return num_elements_; }
bool empty() const { return size() == 0; }
- iterator find(const Key& k) { return iterator(FindHelper(k).first); }
- const_iterator find(const Key& k) const { return find(k, NULL); }
- bool contains(const Key& k) const { return find(k) != end(); }
+ iterator find(const TrivialKey& k) { return iterator(FindHelper(k).first); }
+ const_iterator find(const TrivialKey& k) const { return find(k, nullptr); }
+ bool contains(const TrivialKey& k) const { return find(k) != end(); }
// In traditional C++ style, this performs "insert if not present."
std::pair<iterator, bool> insert(const KeyValuePair& kv) {
std::pair<const_iterator, size_type> p = FindHelper(kv.key());
// Case 1: key was already present.
- if (p.first.node_ != NULL)
+ if (p.first.node_ != nullptr)
return std::make_pair(iterator(p.first), false);
// Case 2: insert.
if (ResizeIfLoadIsOutOfRange(num_elements_ + 1)) {
@@ -579,10 +625,10 @@
// The same, but if an insertion is necessary then the value portion of the
// inserted key-value pair is left uninitialized.
- std::pair<iterator, bool> insert(const Key& k) {
+ std::pair<iterator, bool> insert(const TrivialKey& k) {
std::pair<const_iterator, size_type> p = FindHelper(k);
// Case 1: key was already present.
- if (p.first.node_ != NULL)
+ if (p.first.node_ != nullptr)
return std::make_pair(iterator(p.first), false);
// Case 2: insert.
if (ResizeIfLoadIsOutOfRange(num_elements_ + 1)) {
@@ -590,16 +636,19 @@
}
const size_type b = p.second; // bucket number
Node* node = Alloc<Node>(1);
- typedef typename Allocator::template rebind<Key>::other KeyAllocator;
+ using KeyAllocator =
+ typename Allocator::template rebind<TrivialKey>::other;
KeyAllocator(alloc_).construct(&node->kv.key(), k);
iterator result = InsertUnique(b, node);
++num_elements_;
return std::make_pair(result, true);
}
- Value& operator[](const Key& k) {
+ // Returns iterator so that outer map can update the TrivialKey to point to
+ // the Key inside value_type in case TrivialKey is a view type.
+ iterator operator[](const TrivialKey& k) {
KeyValuePair kv(k, Value());
- return insert(kv).first->value();
+ return insert(kv).first;
}
void erase(iterator it) {
@@ -622,27 +671,27 @@
// only because we want index_of_first_non_null_ to be correct.
b &= ~static_cast<size_type>(1);
DestroyTree(tree);
- table_[b] = table_[b + 1] = NULL;
+ table_[b] = table_[b + 1] = nullptr;
}
}
DestroyNode(item);
--num_elements_;
if (PROTOBUF_PREDICT_FALSE(b == index_of_first_non_null_)) {
while (index_of_first_non_null_ < num_buckets_ &&
- table_[index_of_first_non_null_] == NULL) {
+ table_[index_of_first_non_null_] == nullptr) {
++index_of_first_non_null_;
}
}
}
private:
- const_iterator find(const Key& k, TreeIterator* it) const {
+ const_iterator find(const TrivialKey& k, TreeIterator* it) const {
return FindHelper(k, it).first;
}
- std::pair<const_iterator, size_type> FindHelper(const Key& k) const {
- return FindHelper(k, NULL);
+ std::pair<const_iterator, size_type> FindHelper(const TrivialKey& k) const {
+ return FindHelper(k, nullptr);
}
- std::pair<const_iterator, size_type> FindHelper(const Key& k,
+ std::pair<const_iterator, size_type> FindHelper(const TrivialKey& k,
TreeIterator* it) const {
size_type b = BucketNumber(k);
if (TableEntryIsNonEmptyList(b)) {
@@ -653,15 +702,15 @@
} else {
node = node->next;
}
- } while (node != NULL);
+ } while (node != nullptr);
} else if (TableEntryIsTree(b)) {
GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]);
b &= ~static_cast<size_t>(1);
Tree* tree = static_cast<Tree*>(table_[b]);
- Key* key = const_cast<Key*>(&k);
+ TrivialKey* key = const_cast<TrivialKey*>(&k);
typename Tree::iterator tree_it = tree->find(key);
if (tree_it != tree->end()) {
- if (it != NULL) *it = tree_it;
+ if (it != nullptr) *it = tree_it;
return std::make_pair(const_iterator(tree_it, this, b), b);
}
}
@@ -674,7 +723,7 @@
// bucket. num_elements_ is not modified.
iterator InsertUnique(size_type b, Node* node) {
GOOGLE_DCHECK(index_of_first_non_null_ == num_buckets_ ||
- table_[index_of_first_non_null_] != NULL);
+ table_[index_of_first_non_null_] != nullptr);
// In practice, the code that led to this point may have already
// determined whether we are inserting into an empty list, a short list,
// or whatever. But it's probably cheap enough to recompute that here;
@@ -716,8 +765,8 @@
// Tree.
iterator InsertUniqueInTree(size_type b, Node* node) {
GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]);
- // Maintain the invariant that node->next is NULL for all Nodes in Trees.
- node->next = NULL;
+ // Maintain the invariant that node->next is null for all Nodes in Trees.
+ node->next = nullptr;
return iterator(
static_cast<Tree*>(table_[b])->insert(KeyPtrFromNodePtr(node)).first,
this, b & ~static_cast<size_t>(1));
@@ -789,7 +838,7 @@
Node* next = node->next;
InsertUnique(BucketNumber(*KeyPtrFromNodePtr(node)), node);
node = next;
- } while (node != NULL);
+ } while (node != nullptr);
}
void TransferTree(void* const* table, size_type index) {
@@ -824,10 +873,10 @@
return TableEntryIsList(table_, b);
}
static bool TableEntryIsEmpty(void* const* table, size_type b) {
- return table[b] == NULL;
+ return table[b] == nullptr;
}
static bool TableEntryIsNonEmptyList(void* const* table, size_type b) {
- return table[b] != NULL && table[b] != table[b ^ 1];
+ return table[b] != nullptr && table[b] != table[b ^ 1];
}
static bool TableEntryIsTree(void* const* table, size_type b) {
return !TableEntryIsEmpty(table, b) &&
@@ -845,8 +894,8 @@
// create a temporary and use the two-arg construct that's known to exist.
// It's clunky, but the compiler should be able to generate more-or-less
// the same code.
- tree_allocator.construct(tree,
- Tree(KeyCompare(), KeyPtrAllocator(alloc_)));
+ tree_allocator.construct(
+ tree, Tree(typename Tree::key_compare(), KeyPtrAllocator(alloc_)));
// Now the tree is ready to use.
size_type count = CopyListToTree(b, tree) + CopyListToTree(b ^ 1, tree);
GOOGLE_DCHECK_EQ(count, tree->size());
@@ -858,11 +907,11 @@
size_type CopyListToTree(size_type b, Tree* tree) {
size_type count = 0;
Node* node = static_cast<Node*>(table_[b]);
- while (node != NULL) {
+ while (node != nullptr) {
tree->insert(KeyPtrFromNodePtr(node));
++count;
Node* next = node->next;
- node->next = NULL;
+ node->next = nullptr;
node = next;
}
return count;
@@ -877,20 +926,19 @@
do {
++count;
node = node->next;
- } while (node != NULL);
+ } while (node != nullptr);
// Invariant: no linked list ever is more than kMaxLength in length.
GOOGLE_DCHECK_LE(count, kMaxLength);
return count >= kMaxLength;
}
- size_type BucketNumber(const Key& k) const {
- // We inherit from hasher, so one-arg operator() provides a hash function.
- size_type h = (*const_cast<InnerMap*>(this))(k);
+ size_type BucketNumber(const TrivialKey& k) const {
+ size_type h = hash_function()(k);
return (h + seed_) & (num_buckets_ - 1);
}
- bool IsMatch(const Key& k0, const Key& k1) const {
- return std::equal_to<Key>()(k0, k1);
+ bool IsMatch(const TrivialKey& k0, const TrivialKey& k1) const {
+ return k0 == k1;
}
// Return a power of two no less than max(kMinTableSize, n).
@@ -904,14 +952,14 @@
// Use alloc_ to allocate an array of n objects of type U.
template <typename U>
U* Alloc(size_type n) {
- typedef typename Allocator::template rebind<U>::other alloc_type;
+ using alloc_type = typename Allocator::template rebind<U>::other;
return alloc_type(alloc_).allocate(n);
}
// Use alloc_ to deallocate an array of n objects of type U.
template <typename U>
void Dealloc(U* t, size_type n) {
- typedef typename Allocator::template rebind<U>::other alloc_type;
+ using alloc_type = typename Allocator::template rebind<U>::other;
alloc_type(alloc_).deallocate(t, n);
}
@@ -946,6 +994,10 @@
return s;
}
+ friend class Arena;
+ using InternalArenaConstructable_ = void;
+ using DestructorSkippable_ = void;
+
size_type num_elements_;
size_type num_buckets_;
size_type seed_;
@@ -958,14 +1010,14 @@
public:
// Iterators
class const_iterator {
- typedef typename InnerMap::const_iterator InnerIt;
+ using InnerIt = typename InnerMap::const_iterator;
public:
- typedef std::forward_iterator_tag iterator_category;
- typedef typename Map::value_type value_type;
- typedef ptrdiff_t difference_type;
- typedef const value_type* pointer;
- typedef const value_type& reference;
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = typename Map::value_type;
+ using difference_type = ptrdiff_t;
+ using pointer = const value_type*;
+ using reference = const value_type&;
const_iterator() {}
explicit const_iterator(const InnerIt& it) : it_(it) {}
@@ -991,14 +1043,14 @@
};
class iterator {
- typedef typename InnerMap::iterator InnerIt;
+ using InnerIt = typename InnerMap::iterator;
public:
- typedef std::forward_iterator_tag iterator_category;
- typedef typename Map::value_type value_type;
- typedef ptrdiff_t difference_type;
- typedef value_type* pointer;
- typedef value_type& reference;
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = typename Map::value_type;
+ using difference_type = ptrdiff_t;
+ using pointer = value_type*;
+ using reference = value_type&;
iterator() {}
explicit iterator(const InnerIt& it) : it_(it) {}
@@ -1013,7 +1065,7 @@
iterator operator++(int) { return iterator(it_++); }
// Allow implicit conversion to const_iterator.
- operator const_iterator() const {
+ operator const_iterator() const { // NOLINT(runtime/explicit)
return const_iterator(typename InnerMap::const_iterator(it_));
}
@@ -1047,9 +1099,12 @@
// Element access
T& operator[](const key_type& key) {
- value_type** value = &(*elements_)[key];
- if (*value == NULL) {
+ typename InnerMap::iterator it = (*elements_)[key];
+ value_type** value = &it->value();
+ if (*value == nullptr) {
*value = CreateValueTypeInternal(key);
+ // We need to update the key in case it's a view type.
+ it->key() = (*value)->first;
internal::MapValueInitializer<is_proto_enum<T>::value, T>::Initialize(
(*value)->second, default_enum_value_);
}
@@ -1103,6 +1158,8 @@
elements_->insert(value.first);
if (p.second) {
p.first->value() = CreateValueTypeInternal(value);
+ // We need to update the key in case it's a view type.
+ p.first->key() = p.first->value()->first;
}
return std::pair<iterator, bool>(iterator(p.first), p.second);
}
@@ -1130,9 +1187,12 @@
}
}
iterator erase(iterator pos) {
- if (arena_ == NULL) delete pos.operator->();
+ value_type* value = pos.operator->();
iterator i = pos++;
elements_->erase(i.it_);
+ // Note: we need to delete the value after erasing from the inner map
+ // because the inner map's key may be a view of the value's key.
+ if (arena_ == nullptr) delete value;
return pos;
}
void erase(iterator first, iterator last) {
@@ -1176,27 +1236,26 @@
}
value_type* CreateValueTypeInternal(const Key& key) {
- if (arena_ == NULL) {
+ if (arena_ == nullptr) {
return new value_type(key);
} else {
value_type* value = reinterpret_cast<value_type*>(
Arena::CreateArray<uint8>(arena_, sizeof(value_type)));
- Arena::CreateInArenaStorage(const_cast<Key*>(&value->first), arena_);
+ Arena::CreateInArenaStorage(const_cast<Key*>(&value->first), arena_, key);
Arena::CreateInArenaStorage(&value->second, arena_);
- const_cast<Key&>(value->first) = key;
return value;
}
}
value_type* CreateValueTypeInternal(const value_type& value) {
- if (arena_ == NULL) {
+ if (arena_ == nullptr) {
return new value_type(value);
} else {
value_type* p = reinterpret_cast<value_type*>(
Arena::CreateArray<uint8>(arena_, sizeof(value_type)));
- Arena::CreateInArenaStorage(const_cast<Key*>(&p->first), arena_);
+ Arena::CreateInArenaStorage(const_cast<Key*>(&p->first), arena_,
+ value.first);
Arena::CreateInArenaStorage(&p->second, arena_);
- const_cast<Key&>(p->first) = value.first;
p->second = value.second;
return p;
}
@@ -1207,8 +1266,8 @@
InnerMap* elements_;
friend class Arena;
- typedef void InternalArenaConstructable_;
- typedef void DestructorSkippable_;
+ using InternalArenaConstructable_ = void;
+ using DestructorSkippable_ = void;
template <typename Derived, typename K, typename V,
internal::WireFormatLite::FieldType key_wire_type,
internal::WireFormatLite::FieldType value_wire_type,
diff --git a/src/google/protobuf/map_entry.h b/src/google/protobuf/map_entry.h
index a650c87..4e6a3e3 100644
--- a/src/google/protobuf/map_entry.h
+++ b/src/google/protobuf/map_entry.h
@@ -34,7 +34,6 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/map_entry_lite.h>
#include <google/protobuf/map_type_handler.h>
-#include <google/protobuf/metadata.h>
#include <google/protobuf/port.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/unknown_field_set.h>
@@ -101,6 +100,10 @@
: MapEntryImpl<Derived, Message, Key, Value, kKeyFieldType,
kValueFieldType, default_enum_value>(arena),
_internal_metadata_(arena) {}
+ ~MapEntry() {
+ Message::_internal_metadata_.Delete<UnknownFieldSet>();
+ _internal_metadata_.Delete<UnknownFieldSet>();
+ }
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -118,7 +121,7 @@
return size;
}
- InternalMetadataWithArena _internal_metadata_;
+ InternalMetadata _internal_metadata_;
private:
friend class ::PROTOBUF_NAMESPACE_ID::Arena;
@@ -150,9 +153,9 @@
struct DeconstructMapEntry<MapEntry<Derived, K, V, key, value, default_enum> > {
typedef K Key;
typedef V Value;
- static const WireFormatLite::FieldType kKeyFieldType = key;
- static const WireFormatLite::FieldType kValueFieldType = value;
- static const int default_enum_value = default_enum;
+ static constexpr WireFormatLite::FieldType kKeyFieldType = key;
+ static constexpr WireFormatLite::FieldType kValueFieldType = value;
+ static constexpr int default_enum_value = default_enum;
};
} // namespace internal
diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h
index d35b98c..7125ba1 100644
--- a/src/google/protobuf/map_entry_lite.h
+++ b/src/google/protobuf/map_entry_lite.h
@@ -187,14 +187,14 @@
static const WireFormatLite::FieldType kEntryValueFieldType = kValueFieldType;
static const int kEntryDefaultEnumValue = default_enum_value;
- MapEntryImpl() : arena_(NULL) {
+ MapEntryImpl() {
KeyTypeHandler::Initialize(&key_, NULL);
ValueTypeHandler::InitializeMaybeByDefaultEnum(&value_, default_enum_value,
NULL);
_has_bits_[0] = 0;
}
- explicit MapEntryImpl(Arena* arena) : arena_(arena) {
+ explicit MapEntryImpl(Arena* arena) : Base(arena) {
KeyTypeHandler::Initialize(&key_, arena);
ValueTypeHandler::InitializeMaybeByDefaultEnum(&value_, default_enum_value,
arena);
@@ -202,7 +202,7 @@
}
~MapEntryImpl() {
- if (GetArenaNoVirtual() != NULL) return;
+ if (Base::GetArena() != NULL) return;
KeyTypeHandler::DeleteNoArena(key_);
ValueTypeHandler::DeleteNoArena(value_);
}
@@ -218,11 +218,11 @@
}
inline KeyMapEntryAccessorType* mutable_key() {
set_has_key();
- return KeyTypeHandler::EnsureMutable(&key_, GetArenaNoVirtual());
+ return KeyTypeHandler::EnsureMutable(&key_, Base::GetArena());
}
inline ValueMapEntryAccessorType* mutable_value() {
set_has_value();
- return ValueTypeHandler::EnsureMutable(&value_, GetArenaNoVirtual());
+ return ValueTypeHandler::EnsureMutable(&value_, Base::GetArena());
}
// implements MessageLite =========================================
@@ -315,13 +315,13 @@
void MergeFromInternal(const MapEntryImpl& from) {
if (from._has_bits_[0]) {
if (from.has_key()) {
- KeyTypeHandler::EnsureMutable(&key_, GetArenaNoVirtual());
- KeyTypeHandler::Merge(from.key(), &key_, GetArenaNoVirtual());
+ KeyTypeHandler::EnsureMutable(&key_, Base::GetArena());
+ KeyTypeHandler::Merge(from.key(), &key_, Base::GetArena());
set_has_key();
}
if (from.has_value()) {
- ValueTypeHandler::EnsureMutable(&value_, GetArenaNoVirtual());
- ValueTypeHandler::Merge(from.value(), &value_, GetArenaNoVirtual());
+ ValueTypeHandler::EnsureMutable(&value_, Base::GetArena());
+ ValueTypeHandler::Merge(from.value(), &value_, Base::GetArena());
set_has_value();
}
}
@@ -329,8 +329,8 @@
public:
void Clear() override {
- KeyTypeHandler::Clear(&key_, GetArenaNoVirtual());
- ValueTypeHandler::ClearMaybeByDefaultEnum(&value_, GetArenaNoVirtual(),
+ KeyTypeHandler::Clear(&key_, Base::GetArena());
+ ValueTypeHandler::ClearMaybeByDefaultEnum(&value_, Base::GetArena(),
default_enum_value);
clear_has_key();
clear_has_value();
@@ -342,8 +342,6 @@
ValueTypeHandler::AssignDefaultValue(&d->value_);
}
- Arena* GetArena() const override { return GetArenaNoVirtual(); }
-
// Parsing using MergePartialFromCodedStream, above, is not as
// efficient as it could be. This helper class provides a speedier way.
template <typename MapField, typename Map>
@@ -440,10 +438,10 @@
return ptr;
}
- template <typename Metadata>
+ template <typename UnknownType>
const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx,
bool (*is_valid)(int), uint32 field_num,
- Metadata* metadata) {
+ InternalMetadata* metadata) {
auto entry = NewEntry();
ptr = entry->_InternalParse(ptr, ctx);
if (!ptr) return nullptr;
@@ -451,7 +449,7 @@
UseKeyAndValueFromEntry();
} else {
WriteLengthDelimited(field_num, entry->SerializeAsString(),
- metadata->mutable_unknown_fields());
+ metadata->mutable_unknown_fields<UnknownType>());
}
return ptr;
}
@@ -515,12 +513,11 @@
void clear_has_value() { _has_bits_[0] &= ~0x00000002u; }
public:
- inline Arena* GetArenaNoVirtual() const { return arena_; }
+ inline Arena* GetArena() const { return Base::GetArena(); }
public: // Needed for constructing tables
KeyOnMemory key_;
ValueOnMemory value_;
- Arena* arena_;
uint32 _has_bits_[1];
private:
@@ -549,6 +546,7 @@
SuperType;
MapEntryLite() {}
explicit MapEntryLite(Arena* arena) : SuperType(arena) {}
+ ~MapEntryLite() { MessageLite::_internal_metadata_.Delete<std::string>(); }
void MergeFrom(const MapEntryLite& other) { MergeFromInternal(other); }
private:
@@ -658,7 +656,7 @@
key_(FromHelper<kKeyFieldType>::From(map_pair.first)),
value_(FromHelper<kValueFieldType>::From(map_pair.second)) {}
- // Purposely not folowing the style guide naming. These are the names
+ // Purposely not following the style guide naming. These are the names
// the proto compiler would generate given the map entry descriptor.
// The proto compiler generates the offsets in this struct as if this was
// a regular message. This way the table driven code barely notices it's
diff --git a/src/google/protobuf/map_field.cc b/src/google/protobuf/map_field.cc
index d61fddd..0949f58 100644
--- a/src/google/protobuf/map_field.cc
+++ b/src/google/protobuf/map_field.cc
@@ -196,8 +196,7 @@
}
void DynamicMapField::AllocateMapValue(MapValueRef* map_val) {
- const FieldDescriptor* val_des =
- default_entry_->GetDescriptor()->FindFieldByName("value");
+ const FieldDescriptor* val_des = default_entry_->GetDescriptor()->map_value();
map_val->SetType(val_des->cpp_type());
// Allocate memory for the MapValueRef, and initialize to
// default value.
@@ -300,7 +299,7 @@
// Copy map value
const FieldDescriptor* field_descriptor =
- default_entry_->GetDescriptor()->FindFieldByName("value");
+ default_entry_->GetDescriptor()->map_value();
switch (field_descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: {
map_val->SetInt32Value(other_it->second.GetInt32Value());
@@ -360,10 +359,8 @@
void DynamicMapField::SyncRepeatedFieldWithMapNoLock() const {
const Reflection* reflection = default_entry_->GetReflection();
- const FieldDescriptor* key_des =
- default_entry_->GetDescriptor()->FindFieldByName("key");
- const FieldDescriptor* val_des =
- default_entry_->GetDescriptor()->FindFieldByName("value");
+ const FieldDescriptor* key_des = default_entry_->GetDescriptor()->map_key();
+ const FieldDescriptor* val_des = default_entry_->GetDescriptor()->map_value();
if (MapFieldBase::repeated_field_ == NULL) {
if (MapFieldBase::arena_ == NULL) {
MapFieldBase::repeated_field_ = new RepeatedPtrField<Message>();
@@ -448,10 +445,8 @@
void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const {
Map<MapKey, MapValueRef>* map = &const_cast<DynamicMapField*>(this)->map_;
const Reflection* reflection = default_entry_->GetReflection();
- const FieldDescriptor* key_des =
- default_entry_->GetDescriptor()->FindFieldByName("key");
- const FieldDescriptor* val_des =
- default_entry_->GetDescriptor()->FindFieldByName("value");
+ const FieldDescriptor* key_des = default_entry_->GetDescriptor()->map_key();
+ const FieldDescriptor* val_des = default_entry_->GetDescriptor()->map_value();
// DynamicMapField owns map values. Need to delete them before clearing
// the map.
if (MapFieldBase::arena_ == nullptr) {
diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h
index 38bf26a..9ea3fad 100644
--- a/src/google/protobuf/map_field.h
+++ b/src/google/protobuf/map_field.h
@@ -32,6 +32,7 @@
#define GOOGLE_PROTOBUF_MAP_FIELD_H__
#include <atomic>
+#include <functional>
#include <google/protobuf/arena.h>
#include <google/protobuf/descriptor.h>
@@ -56,321 +57,7 @@
namespace google {
namespace protobuf {
class DynamicMessage;
-class MapKey;
class MapIterator;
-namespace internal {
-
-class ContendedMapCleanTest;
-class GeneratedMessageReflection;
-class MapFieldAccessor;
-
-// This class provides access to map field using reflection, which is the same
-// as those provided for RepeatedPtrField<Message>. It is used for internal
-// reflection implentation only. Users should never use this directly.
-class PROTOBUF_EXPORT MapFieldBase {
- public:
- MapFieldBase()
- : arena_(NULL), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) {}
- explicit MapFieldBase(Arena* arena)
- : arena_(arena), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) {
- // Mutex's destructor needs to be called explicitly to release resources
- // acquired in its constructor.
- arena->OwnDestructor(&mutex_);
- }
- virtual ~MapFieldBase();
-
- // Returns reference to internal repeated field. Data written using
- // Map's api prior to calling this function is guarantted to be
- // included in repeated field.
- const RepeatedPtrFieldBase& GetRepeatedField() const;
-
- // Like above. Returns mutable pointer to the internal repeated field.
- RepeatedPtrFieldBase* MutableRepeatedField();
-
- // Pure virtual map APIs for Map Reflection.
- virtual bool ContainsMapKey(const MapKey& map_key) const = 0;
- virtual bool InsertOrLookupMapValue(const MapKey& map_key,
- MapValueRef* val) = 0;
- // Returns whether changes to the map are reflected in the repeated field.
- bool IsRepeatedFieldValid() const;
- // Insures operations after won't get executed before calling this.
- bool IsMapValid() const;
- virtual bool DeleteMapValue(const MapKey& map_key) = 0;
- virtual bool EqualIterator(const MapIterator& a,
- const MapIterator& b) const = 0;
- virtual void MapBegin(MapIterator* map_iter) const = 0;
- virtual void MapEnd(MapIterator* map_iter) const = 0;
- virtual void MergeFrom(const MapFieldBase& other) = 0;
- virtual void Swap(MapFieldBase* other) = 0;
- // Sync Map with repeated field and returns the size of map.
- virtual int size() const = 0;
- virtual void Clear() = 0;
-
- // Returns the number of bytes used by the repeated field, excluding
- // sizeof(*this)
- size_t SpaceUsedExcludingSelfLong() const;
-
- int SpaceUsedExcludingSelf() const {
- return internal::ToIntSize(SpaceUsedExcludingSelfLong());
- }
-
- protected:
- // Gets the size of space used by map field.
- virtual size_t SpaceUsedExcludingSelfNoLock() const;
-
- // Synchronizes the content in Map to RepeatedPtrField if there is any change
- // to Map after last synchronization.
- void SyncRepeatedFieldWithMap() const;
- virtual void SyncRepeatedFieldWithMapNoLock() const;
-
- // Synchronizes the content in RepeatedPtrField to Map if there is any change
- // to RepeatedPtrField after last synchronization.
- void SyncMapWithRepeatedField() const;
- virtual void SyncMapWithRepeatedFieldNoLock() const {}
-
- // Tells MapFieldBase that there is new change to Map.
- void SetMapDirty();
-
- // Tells MapFieldBase that there is new change to RepeatedPTrField.
- void SetRepeatedDirty();
-
- // Provides derived class the access to repeated field.
- void* MutableRepeatedPtrField() const;
-
- enum State {
- STATE_MODIFIED_MAP = 0, // map has newly added data that has not been
- // synchronized to repeated field
- STATE_MODIFIED_REPEATED = 1, // repeated field has newly added data that
- // has not been synchronized to map
- CLEAN = 2, // data in map and repeated field are same
- };
-
- Arena* arena_;
- mutable RepeatedPtrField<Message>* repeated_field_;
-
- mutable internal::WrappedMutex
- mutex_; // The thread to synchronize map and repeated field
- // needs to get lock first;
- mutable std::atomic<State> state_;
-
- private:
- friend class ContendedMapCleanTest;
- friend class GeneratedMessageReflection;
- friend class MapFieldAccessor;
- friend class ::PROTOBUF_NAMESPACE_ID::DynamicMessage;
-
- // Virtual helper methods for MapIterator. MapIterator doesn't have the
- // type helper for key and value. Call these help methods to deal with
- // different types. Real helper methods are implemented in
- // TypeDefinedMapFieldBase.
- friend class ::PROTOBUF_NAMESPACE_ID::MapIterator;
- // Allocate map<...>::iterator for MapIterator.
- virtual void InitializeIterator(MapIterator* map_iter) const = 0;
-
- // DeleteIterator() is called by the destructor of MapIterator only.
- // It deletes map<...>::iterator for MapIterator.
- virtual void DeleteIterator(MapIterator* map_iter) const = 0;
-
- // Copy the map<...>::iterator from other_iterator to
- // this_iterator.
- virtual void CopyIterator(MapIterator* this_iterator,
- const MapIterator& other_iterator) const = 0;
-
- // IncreaseIterator() is called by operator++() of MapIterator only.
- // It implements the ++ operator of MapIterator.
- virtual void IncreaseIterator(MapIterator* map_iter) const = 0;
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldBase);
-};
-
-// This class provides common Map Reflection implementations for generated
-// message and dynamic message.
-template <typename Key, typename T>
-class TypeDefinedMapFieldBase : public MapFieldBase {
- public:
- TypeDefinedMapFieldBase() {}
- explicit TypeDefinedMapFieldBase(Arena* arena) : MapFieldBase(arena) {}
- ~TypeDefinedMapFieldBase() override {}
- void MapBegin(MapIterator* map_iter) const override;
- void MapEnd(MapIterator* map_iter) const override;
- bool EqualIterator(const MapIterator& a, const MapIterator& b) const override;
-
- virtual const Map<Key, T>& GetMap() const = 0;
- virtual Map<Key, T>* MutableMap() = 0;
-
- protected:
- typename Map<Key, T>::const_iterator& InternalGetIterator(
- const MapIterator* map_iter) const;
-
- private:
- void InitializeIterator(MapIterator* map_iter) const override;
- void DeleteIterator(MapIterator* map_iter) const override;
- void CopyIterator(MapIterator* this_iteratorm,
- const MapIterator& that_iterator) const override;
- void IncreaseIterator(MapIterator* map_iter) const override;
-
- virtual void SetMapIteratorValue(MapIterator* map_iter) const = 0;
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeDefinedMapFieldBase);
-};
-
-// This class provides access to map field using generated api. It is used for
-// internal generated message implentation only. Users should never use this
-// directly.
-template <typename Derived, typename Key, typename T,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType, int default_enum_value = 0>
-class MapField : public TypeDefinedMapFieldBase<Key, T> {
- // Provide utilities to parse/serialize key/value. Provide utilities to
- // manipulate internal stored type.
- typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
- typedef MapTypeHandler<kValueFieldType, T> ValueTypeHandler;
-
- // Define message type for internal repeated field.
- typedef Derived EntryType;
-
- // Define abbreviation for parent MapFieldLite
- typedef MapFieldLite<Derived, Key, T, kKeyFieldType, kValueFieldType,
- default_enum_value>
- MapFieldLiteType;
-
- // Enum needs to be handled differently from other types because it has
- // different exposed type in Map's api and repeated field's api. For
- // details see the comment in the implementation of
- // SyncMapWithRepeatedFieldNoLock.
- static const bool kIsValueEnum = ValueTypeHandler::kIsEnum;
- typedef typename MapIf<kIsValueEnum, T, const T&>::type CastValueType;
-
- public:
- typedef typename Derived::SuperType EntryTypeTrait;
- typedef Map<Key, T> MapType;
-
- MapField() {}
- explicit MapField(Arena* arena)
- : TypeDefinedMapFieldBase<Key, T>(arena), impl_(arena) {}
-
- // Implement MapFieldBase
- bool ContainsMapKey(const MapKey& map_key) const override;
- bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override;
- bool DeleteMapValue(const MapKey& map_key) override;
-
- const Map<Key, T>& GetMap() const override {
- MapFieldBase::SyncMapWithRepeatedField();
- return impl_.GetMap();
- }
-
- Map<Key, T>* MutableMap() override {
- MapFieldBase::SyncMapWithRepeatedField();
- Map<Key, T>* result = impl_.MutableMap();
- MapFieldBase::SetMapDirty();
- return result;
- }
-
- int size() const override;
- void Clear() override;
- void MergeFrom(const MapFieldBase& other) override;
- void Swap(MapFieldBase* other) override;
-
- // Used in the implementation of parsing. Caller should take the ownership iff
- // arena_ is NULL.
- EntryType* NewEntry() const { return impl_.NewEntry(); }
- // Used in the implementation of serializing enum value type. Caller should
- // take the ownership iff arena_ is NULL.
- EntryType* NewEnumEntryWrapper(const Key& key, const T t) const {
- return impl_.NewEnumEntryWrapper(key, t);
- }
- // Used in the implementation of serializing other value types. Caller should
- // take the ownership iff arena_ is NULL.
- EntryType* NewEntryWrapper(const Key& key, const T& t) const {
- return impl_.NewEntryWrapper(key, t);
- }
-
- const char* _InternalParse(const char* ptr, ParseContext* ctx) {
- return impl_._InternalParse(ptr, ctx);
- }
- template <typename Metadata>
- const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx,
- bool (*is_valid)(int), uint32 field_num,
- Metadata* metadata) {
- return impl_.ParseWithEnumValidation(ptr, ctx, is_valid, field_num,
- metadata);
- }
-
- private:
- MapFieldLiteType impl_;
-
- typedef void InternalArenaConstructable_;
- typedef void DestructorSkippable_;
-
- // Implements MapFieldBase
- void SyncRepeatedFieldWithMapNoLock() const override;
- void SyncMapWithRepeatedFieldNoLock() const override;
- size_t SpaceUsedExcludingSelfNoLock() const override;
-
- void SetMapIteratorValue(MapIterator* map_iter) const override;
-
- friend class ::PROTOBUF_NAMESPACE_ID::Arena;
- friend class MapFieldStateTest; // For testing, it needs raw access to impl_
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField);
-};
-
-template <typename Derived, typename Key, typename T,
- WireFormatLite::FieldType key_wire_type,
- WireFormatLite::FieldType value_wire_type, int default_enum_value>
-bool AllAreInitialized(
- const MapField<Derived, Key, T, key_wire_type, value_wire_type,
- default_enum_value>& field) {
- const auto& t = field.GetMap();
- for (typename Map<Key, T>::const_iterator it = t.begin(); it != t.end();
- ++it) {
- if (!it->second.IsInitialized()) return false;
- }
- return true;
-}
-
-template <typename T, typename Key, typename Value,
- WireFormatLite::FieldType kKeyFieldType,
- WireFormatLite::FieldType kValueFieldType, int default_enum_value>
-struct MapEntryToMapField<MapEntry<T, Key, Value, kKeyFieldType,
- kValueFieldType, default_enum_value>> {
- typedef MapField<T, Key, Value, kKeyFieldType, kValueFieldType,
- default_enum_value>
- MapFieldType;
-};
-
-class PROTOBUF_EXPORT DynamicMapField
- : public TypeDefinedMapFieldBase<MapKey, MapValueRef> {
- public:
- explicit DynamicMapField(const Message* default_entry);
- DynamicMapField(const Message* default_entry, Arena* arena);
- ~DynamicMapField() override;
-
- // Implement MapFieldBase
- bool ContainsMapKey(const MapKey& map_key) const override;
- bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override;
- bool DeleteMapValue(const MapKey& map_key) override;
- void MergeFrom(const MapFieldBase& other) override;
- void Swap(MapFieldBase* other) override;
-
- const Map<MapKey, MapValueRef>& GetMap() const override;
- Map<MapKey, MapValueRef>* MutableMap() override;
-
- int size() const override;
- void Clear() override;
-
- private:
- Map<MapKey, MapValueRef> map_;
- const Message* default_entry_;
-
- void AllocateMapValue(MapValueRef* map_val);
-
- // Implements MapFieldBase
- void SyncRepeatedFieldWithMapNoLock() const override;
- void SyncMapWithRepeatedFieldNoLock() const override;
- size_t SpaceUsedExcludingSelfNoLock() const override;
- void SetMapIteratorValue(MapIterator* map_iter) const override;
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMapField);
-};
-
-} // namespace internal
#define TYPE_CHECK(EXPECTEDTYPE, METHOD) \
if (type() != EXPECTEDTYPE) { \
@@ -577,6 +264,322 @@
int type_;
};
+namespace internal {
+
+class ContendedMapCleanTest;
+class GeneratedMessageReflection;
+class MapFieldAccessor;
+
+// This class provides access to map field using reflection, which is the same
+// as those provided for RepeatedPtrField<Message>. It is used for internal
+// reflection implentation only. Users should never use this directly.
+class PROTOBUF_EXPORT MapFieldBase {
+ public:
+ MapFieldBase()
+ : arena_(NULL), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) {}
+ explicit MapFieldBase(Arena* arena)
+ : arena_(arena), repeated_field_(NULL), state_(STATE_MODIFIED_MAP) {
+ // Mutex's destructor needs to be called explicitly to release resources
+ // acquired in its constructor.
+ if (arena) {
+ arena->OwnDestructor(&mutex_);
+ }
+ }
+ virtual ~MapFieldBase();
+
+ // Returns reference to internal repeated field. Data written using
+ // Map's api prior to calling this function is guarantted to be
+ // included in repeated field.
+ const RepeatedPtrFieldBase& GetRepeatedField() const;
+
+ // Like above. Returns mutable pointer to the internal repeated field.
+ RepeatedPtrFieldBase* MutableRepeatedField();
+
+ // Pure virtual map APIs for Map Reflection.
+ virtual bool ContainsMapKey(const MapKey& map_key) const = 0;
+ virtual bool InsertOrLookupMapValue(const MapKey& map_key,
+ MapValueRef* val) = 0;
+ // Returns whether changes to the map are reflected in the repeated field.
+ bool IsRepeatedFieldValid() const;
+ // Insures operations after won't get executed before calling this.
+ bool IsMapValid() const;
+ virtual bool DeleteMapValue(const MapKey& map_key) = 0;
+ virtual bool EqualIterator(const MapIterator& a,
+ const MapIterator& b) const = 0;
+ virtual void MapBegin(MapIterator* map_iter) const = 0;
+ virtual void MapEnd(MapIterator* map_iter) const = 0;
+ virtual void MergeFrom(const MapFieldBase& other) = 0;
+ virtual void Swap(MapFieldBase* other) = 0;
+ // Sync Map with repeated field and returns the size of map.
+ virtual int size() const = 0;
+ virtual void Clear() = 0;
+
+ // Returns the number of bytes used by the repeated field, excluding
+ // sizeof(*this)
+ size_t SpaceUsedExcludingSelfLong() const;
+
+ int SpaceUsedExcludingSelf() const {
+ return internal::ToIntSize(SpaceUsedExcludingSelfLong());
+ }
+
+ protected:
+ // Gets the size of space used by map field.
+ virtual size_t SpaceUsedExcludingSelfNoLock() const;
+
+ // Synchronizes the content in Map to RepeatedPtrField if there is any change
+ // to Map after last synchronization.
+ void SyncRepeatedFieldWithMap() const;
+ virtual void SyncRepeatedFieldWithMapNoLock() const;
+
+ // Synchronizes the content in RepeatedPtrField to Map if there is any change
+ // to RepeatedPtrField after last synchronization.
+ void SyncMapWithRepeatedField() const;
+ virtual void SyncMapWithRepeatedFieldNoLock() const {}
+
+ // Tells MapFieldBase that there is new change to Map.
+ void SetMapDirty();
+
+ // Tells MapFieldBase that there is new change to RepeatedPTrField.
+ void SetRepeatedDirty();
+
+ // Provides derived class the access to repeated field.
+ void* MutableRepeatedPtrField() const;
+
+ enum State {
+ STATE_MODIFIED_MAP = 0, // map has newly added data that has not been
+ // synchronized to repeated field
+ STATE_MODIFIED_REPEATED = 1, // repeated field has newly added data that
+ // has not been synchronized to map
+ CLEAN = 2, // data in map and repeated field are same
+ };
+
+ Arena* arena_;
+ mutable RepeatedPtrField<Message>* repeated_field_;
+
+ mutable internal::WrappedMutex
+ mutex_; // The thread to synchronize map and repeated field
+ // needs to get lock first;
+ mutable std::atomic<State> state_;
+
+ private:
+ friend class ContendedMapCleanTest;
+ friend class GeneratedMessageReflection;
+ friend class MapFieldAccessor;
+ friend class ::PROTOBUF_NAMESPACE_ID::DynamicMessage;
+
+ // Virtual helper methods for MapIterator. MapIterator doesn't have the
+ // type helper for key and value. Call these help methods to deal with
+ // different types. Real helper methods are implemented in
+ // TypeDefinedMapFieldBase.
+ friend class ::PROTOBUF_NAMESPACE_ID::MapIterator;
+ // Allocate map<...>::iterator for MapIterator.
+ virtual void InitializeIterator(MapIterator* map_iter) const = 0;
+
+ // DeleteIterator() is called by the destructor of MapIterator only.
+ // It deletes map<...>::iterator for MapIterator.
+ virtual void DeleteIterator(MapIterator* map_iter) const = 0;
+
+ // Copy the map<...>::iterator from other_iterator to
+ // this_iterator.
+ virtual void CopyIterator(MapIterator* this_iterator,
+ const MapIterator& other_iterator) const = 0;
+
+ // IncreaseIterator() is called by operator++() of MapIterator only.
+ // It implements the ++ operator of MapIterator.
+ virtual void IncreaseIterator(MapIterator* map_iter) const = 0;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldBase);
+};
+
+// This class provides common Map Reflection implementations for generated
+// message and dynamic message.
+template <typename Key, typename T>
+class TypeDefinedMapFieldBase : public MapFieldBase {
+ public:
+ TypeDefinedMapFieldBase() {}
+ explicit TypeDefinedMapFieldBase(Arena* arena) : MapFieldBase(arena) {}
+ ~TypeDefinedMapFieldBase() override {}
+ void MapBegin(MapIterator* map_iter) const override;
+ void MapEnd(MapIterator* map_iter) const override;
+ bool EqualIterator(const MapIterator& a, const MapIterator& b) const override;
+
+ virtual const Map<Key, T>& GetMap() const = 0;
+ virtual Map<Key, T>* MutableMap() = 0;
+
+ protected:
+ typename Map<Key, T>::const_iterator& InternalGetIterator(
+ const MapIterator* map_iter) const;
+
+ private:
+ void InitializeIterator(MapIterator* map_iter) const override;
+ void DeleteIterator(MapIterator* map_iter) const override;
+ void CopyIterator(MapIterator* this_iteratorm,
+ const MapIterator& that_iterator) const override;
+ void IncreaseIterator(MapIterator* map_iter) const override;
+
+ virtual void SetMapIteratorValue(MapIterator* map_iter) const = 0;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeDefinedMapFieldBase);
+};
+
+// This class provides access to map field using generated api. It is used for
+// internal generated message implentation only. Users should never use this
+// directly.
+template <typename Derived, typename Key, typename T,
+ WireFormatLite::FieldType kKeyFieldType,
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value = 0>
+class MapField : public TypeDefinedMapFieldBase<Key, T> {
+ // Provide utilities to parse/serialize key/value. Provide utilities to
+ // manipulate internal stored type.
+ typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
+ typedef MapTypeHandler<kValueFieldType, T> ValueTypeHandler;
+
+ // Define message type for internal repeated field.
+ typedef Derived EntryType;
+
+ // Define abbreviation for parent MapFieldLite
+ typedef MapFieldLite<Derived, Key, T, kKeyFieldType, kValueFieldType,
+ default_enum_value>
+ MapFieldLiteType;
+
+ // Enum needs to be handled differently from other types because it has
+ // different exposed type in Map's api and repeated field's api. For
+ // details see the comment in the implementation of
+ // SyncMapWithRepeatedFieldNoLock.
+ static constexpr bool kIsValueEnum = ValueTypeHandler::kIsEnum;
+ typedef typename MapIf<kIsValueEnum, T, const T&>::type CastValueType;
+
+ public:
+ typedef typename Derived::SuperType EntryTypeTrait;
+ typedef Map<Key, T> MapType;
+
+ MapField() {}
+ explicit MapField(Arena* arena)
+ : TypeDefinedMapFieldBase<Key, T>(arena), impl_(arena) {}
+
+ // Implement MapFieldBase
+ bool ContainsMapKey(const MapKey& map_key) const override;
+ bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override;
+ bool DeleteMapValue(const MapKey& map_key) override;
+
+ const Map<Key, T>& GetMap() const override {
+ MapFieldBase::SyncMapWithRepeatedField();
+ return impl_.GetMap();
+ }
+
+ Map<Key, T>* MutableMap() override {
+ MapFieldBase::SyncMapWithRepeatedField();
+ Map<Key, T>* result = impl_.MutableMap();
+ MapFieldBase::SetMapDirty();
+ return result;
+ }
+
+ int size() const override;
+ void Clear() override;
+ void MergeFrom(const MapFieldBase& other) override;
+ void Swap(MapFieldBase* other) override;
+
+ // Used in the implementation of parsing. Caller should take the ownership iff
+ // arena_ is NULL.
+ EntryType* NewEntry() const { return impl_.NewEntry(); }
+ // Used in the implementation of serializing enum value type. Caller should
+ // take the ownership iff arena_ is NULL.
+ EntryType* NewEnumEntryWrapper(const Key& key, const T t) const {
+ return impl_.NewEnumEntryWrapper(key, t);
+ }
+ // Used in the implementation of serializing other value types. Caller should
+ // take the ownership iff arena_ is NULL.
+ EntryType* NewEntryWrapper(const Key& key, const T& t) const {
+ return impl_.NewEntryWrapper(key, t);
+ }
+
+ const char* _InternalParse(const char* ptr, ParseContext* ctx) {
+ return impl_._InternalParse(ptr, ctx);
+ }
+ template <typename UnknownType>
+ const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx,
+ bool (*is_valid)(int), uint32 field_num,
+ InternalMetadata* metadata) {
+ return impl_.template ParseWithEnumValidation<UnknownType>(
+ ptr, ctx, is_valid, field_num, metadata);
+ }
+
+ private:
+ MapFieldLiteType impl_;
+
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
+
+ // Implements MapFieldBase
+ void SyncRepeatedFieldWithMapNoLock() const override;
+ void SyncMapWithRepeatedFieldNoLock() const override;
+ size_t SpaceUsedExcludingSelfNoLock() const override;
+
+ void SetMapIteratorValue(MapIterator* map_iter) const override;
+
+ friend class ::PROTOBUF_NAMESPACE_ID::Arena;
+ friend class MapFieldStateTest; // For testing, it needs raw access to impl_
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField);
+};
+
+template <typename Derived, typename Key, typename T,
+ WireFormatLite::FieldType key_wire_type,
+ WireFormatLite::FieldType value_wire_type, int default_enum_value>
+bool AllAreInitialized(
+ const MapField<Derived, Key, T, key_wire_type, value_wire_type,
+ default_enum_value>& field) {
+ const auto& t = field.GetMap();
+ for (typename Map<Key, T>::const_iterator it = t.begin(); it != t.end();
+ ++it) {
+ if (!it->second.IsInitialized()) return false;
+ }
+ return true;
+}
+
+template <typename T, typename Key, typename Value,
+ WireFormatLite::FieldType kKeyFieldType,
+ WireFormatLite::FieldType kValueFieldType, int default_enum_value>
+struct MapEntryToMapField<MapEntry<T, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value>> {
+ typedef MapField<T, Key, Value, kKeyFieldType, kValueFieldType,
+ default_enum_value>
+ MapFieldType;
+};
+
+class PROTOBUF_EXPORT DynamicMapField
+ : public TypeDefinedMapFieldBase<MapKey, MapValueRef> {
+ public:
+ explicit DynamicMapField(const Message* default_entry);
+ DynamicMapField(const Message* default_entry, Arena* arena);
+ ~DynamicMapField() override;
+
+ // Implement MapFieldBase
+ bool ContainsMapKey(const MapKey& map_key) const override;
+ bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override;
+ bool DeleteMapValue(const MapKey& map_key) override;
+ void MergeFrom(const MapFieldBase& other) override;
+ void Swap(MapFieldBase* other) override;
+
+ const Map<MapKey, MapValueRef>& GetMap() const override;
+ Map<MapKey, MapValueRef>* MutableMap() override;
+
+ int size() const override;
+ void Clear() override;
+
+ private:
+ Map<MapKey, MapValueRef> map_;
+ const Message* default_entry_;
+
+ void AllocateMapValue(MapValueRef* map_val);
+
+ // Implements MapFieldBase
+ void SyncRepeatedFieldWithMapNoLock() const override;
+ void SyncMapWithRepeatedFieldNoLock() const override;
+ size_t SpaceUsedExcludingSelfNoLock() const override;
+ void SetMapIteratorValue(MapIterator* map_iter) const override;
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMapField);
+};
+
+} // namespace internal
+
// MapValueRef points to a map value.
class PROTOBUF_EXPORT MapValueRef {
public:
@@ -794,7 +797,7 @@
} // namespace protobuf
} // namespace google
-GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START
+namespace std {
template <>
struct hash<::PROTOBUF_NAMESPACE_ID::MapKey> {
size_t operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key) const {
@@ -807,16 +810,25 @@
break;
case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_STRING:
return hash<std::string>()(map_key.GetStringValue());
- case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT64:
- return hash<int64>()(map_key.GetInt64Value());
- case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT32:
- return hash<int32>()(map_key.GetInt32Value());
- case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT64:
- return hash<uint64>()(map_key.GetUInt64Value());
- case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT32:
- return hash<uint32>()(map_key.GetUInt32Value());
- case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_BOOL:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT64: {
+ auto value = map_key.GetInt64Value();
+ return hash<decltype(value)>()(value);
+ }
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT32: {
+ auto value = map_key.GetInt32Value();
+ return hash<decltype(value)>()(map_key.GetInt32Value());
+ }
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT64: {
+ auto value = map_key.GetUInt64Value();
+ return hash<decltype(value)>()(map_key.GetUInt64Value());
+ }
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT32: {
+ auto value = map_key.GetUInt32Value();
+ return hash<decltype(value)>()(map_key.GetUInt32Value());
+ }
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_BOOL: {
return hash<bool>()(map_key.GetBoolValue());
+ }
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return 0;
@@ -826,8 +838,7 @@
return map_key1 < map_key2;
}
};
-GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END
-
+} // namespace std
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_MAP_FIELD_H__
diff --git a/src/google/protobuf/map_field_lite.h b/src/google/protobuf/map_field_lite.h
index 3f2f632..d641d17 100644
--- a/src/google/protobuf/map_field_lite.h
+++ b/src/google/protobuf/map_field_lite.h
@@ -108,13 +108,13 @@
return parser._InternalParse(ptr, ctx);
}
- template <typename Metadata>
+ template <typename UnknownType>
const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx,
bool (*is_valid)(int), uint32 field_num,
- Metadata* metadata) {
+ InternalMetadata* metadata) {
typename Derived::template Parser<MapFieldLite, Map<Key, T>> parser(this);
- return parser.ParseWithEnumValidation(ptr, ctx, is_valid, field_num,
- metadata);
+ return parser.template ParseWithEnumValidation<UnknownType>(
+ ptr, ctx, is_valid, field_num, metadata);
}
private:
@@ -125,28 +125,27 @@
friend class ::PROTOBUF_NAMESPACE_ID::Arena;
};
-template <typename T, typename Metadata>
+template <typename UnknownType, typename T>
struct EnumParseWrapper {
const char* _InternalParse(const char* ptr, ParseContext* ctx) {
- return map_field->ParseWithEnumValidation(ptr, ctx, is_valid, field_num,
- metadata);
+ return map_field->template ParseWithEnumValidation<UnknownType>(
+ ptr, ctx, is_valid, field_num, metadata);
}
T* map_field;
bool (*is_valid)(int);
uint32 field_num;
- Metadata* metadata;
+ InternalMetadata* metadata;
};
// Helper function because the typenames of maps are horrendous to print. This
// leverages compiler type deduction, to keep all type data out of the
// generated code
-template <typename T, typename Metadata>
-EnumParseWrapper<T, Metadata> InitEnumParseWrapper(T* map_field,
- bool (*is_valid)(int),
- uint32 field_num,
- Metadata* metadata) {
- return EnumParseWrapper<T, Metadata>{map_field, is_valid, field_num,
- metadata};
+template <typename UnknownType, typename T>
+EnumParseWrapper<UnknownType, T> InitEnumParseWrapper(
+ T* map_field, bool (*is_valid)(int), uint32 field_num,
+ InternalMetadata* metadata) {
+ return EnumParseWrapper<UnknownType, T>{map_field, is_valid, field_num,
+ metadata};
}
// True if IsInitialized() is true for value field in all elements of t. T is
diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc
index 05f83e2..5ccb7b0 100644
--- a/src/google/protobuf/map_field_test.cc
+++ b/src/google/protobuf/map_field_test.cc
@@ -107,8 +107,8 @@
map_descriptor_ = unittest::TestMap::descriptor()
->FindFieldByName("map_int32_int32")
->message_type();
- key_descriptor_ = map_descriptor_->FindFieldByName("key");
- value_descriptor_ = map_descriptor_->FindFieldByName("value");
+ key_descriptor_ = map_descriptor_->map_key();
+ value_descriptor_ = map_descriptor_->map_value();
// Build map field
map_field_.reset(new MapFieldType);
diff --git a/src/google/protobuf/map_test.cc b/src/google/protobuf/map_test.cc
index a2d81db..6deb35f 100644
--- a/src/google/protobuf/map_test.cc
+++ b/src/google/protobuf/map_test.cc
@@ -39,9 +39,11 @@
#include <algorithm>
#include <map>
#include <memory>
+#include <random>
#include <set>
#include <sstream>
#include <unordered_map>
+#include <unordered_set>
#include <vector>
#include <google/protobuf/stubs/logging.h>
@@ -94,6 +96,8 @@
io::CodedOutputStream::SetDefaultSerializationDeterministic();
}
+namespace {
+
// Map API Test =====================================================
class MapImplTest : public ::testing::Test {
@@ -980,11 +984,7 @@
static int Func(int i, int j) { return i * j; }
-static std::string StrFunc(int i, int j) {
- std::string str;
- SStringPrintf(&str, "%d", Func(i, j));
- return str;
-}
+static std::string StrFunc(int i, int j) { return StrCat(Func(i, j)); }
static int Int(const std::string& value) {
int result = 0;
@@ -992,6 +992,9 @@
return result;
}
+} // namespace
+
+// This class is a friend, so no anonymous namespace.
class MapFieldReflectionTest : public testing::Test {
protected:
typedef FieldDescriptor FD;
@@ -1002,6 +1005,8 @@
}
};
+namespace {
+
TEST_F(MapFieldReflectionTest, RegularFields) {
TestMap message;
const Reflection* refl = message.GetReflection();
@@ -2134,7 +2139,7 @@
unittest::TestMap message1, message2;
std::string data;
MapTestUtil::SetMapFields(&message1);
- int size = message1.ByteSize();
+ size_t size = message1.ByteSizeLong();
data.resize(size);
uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
@@ -2147,7 +2152,7 @@
TEST(GeneratedMapFieldTest, SerializationToStream) {
unittest::TestMap message1, message2;
MapTestUtil::SetMapFields(&message1);
- int size = message1.ByteSize();
+ size_t size = message1.ByteSizeLong();
std::string data;
data.resize(size);
{
@@ -2364,7 +2369,7 @@
EXPECT_TRUE(TextFormat::ParseFromString(text, &message));
EXPECT_EQ(1, message.map_int32_foreign_message().size());
- EXPECT_EQ(11, message.ByteSize());
+ EXPECT_EQ(11, message.ByteSizeLong());
}
TEST(GeneratedMapFieldTest, UnknownFieldWireFormat) {
@@ -2476,7 +2481,7 @@
MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
reflection_tester.SetMapFieldsViaReflection(&message);
- EXPECT_LT(0, message.GetReflection()->SpaceUsed(message));
+ EXPECT_LT(0, message.GetReflection()->SpaceUsedLong(message));
}
TEST(GeneratedMapFieldReflectionTest, Accessors) {
@@ -2762,7 +2767,7 @@
}
TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) {
- // Test that SpaceUsed() works properly
+ // Test that SpaceUsedLong() works properly
// Since we share the implementation with generated messages, we don't need
// to test very much here. Just make sure it appears to be working.
@@ -2770,10 +2775,10 @@
std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
- int initial_space_used = message->SpaceUsed();
+ int initial_space_used = message->SpaceUsedLong();
reflection_tester.SetMapFieldsViaReflection(message.get());
- EXPECT_LT(initial_space_used, message->SpaceUsed());
+ EXPECT_LT(initial_space_used, message->SpaceUsedLong());
}
TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) {
@@ -2947,9 +2952,9 @@
unittest::TestMap message;
MapTestUtil::SetMapFields(&message);
- EXPECT_EQ(message.ByteSize(), WireFormat::ByteSize(message));
+ EXPECT_EQ(message.ByteSizeLong(), WireFormat::ByteSize(message));
message.Clear();
- EXPECT_EQ(0, message.ByteSize());
+ EXPECT_EQ(0, message.ByteSizeLong());
EXPECT_EQ(0, WireFormat::ByteSize(message));
}
@@ -2962,7 +2967,7 @@
// Serialize using the generated code.
{
- message.ByteSize();
+ message.ByteSizeLong();
io::StringOutputStream raw_output(&generated_data);
io::CodedOutputStream output(&raw_output);
message.SerializeWithCachedSizes(&output);
@@ -2973,7 +2978,7 @@
{
io::StringOutputStream raw_output(&dynamic_data);
io::CodedOutputStream output(&raw_output);
- int size = WireFormat::ByteSize(message);
+ size_t size = WireFormat::ByteSize(message);
WireFormat::SerializeWithCachedSizes(message, size, &output);
ASSERT_FALSE(output.HadError());
}
@@ -3021,7 +3026,7 @@
std::string expected_serialized_data;
dynamic_message->SerializeToString(&expected_serialized_data);
int expected_size = expected_serialized_data.size();
- EXPECT_EQ(dynamic_message->ByteSize(), expected_size);
+ EXPECT_EQ(dynamic_message->ByteSizeLong(), expected_size);
std::unique_ptr<Message> message2;
message2.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
@@ -3035,27 +3040,27 @@
reflection->RemoveLast(dynamic_message.get(), field);
dynamic_message->MergeFrom(*message2);
dynamic_message->MergeFrom(*message2);
- // The map field is marked as STATE_MODIFIED_REPEATED, ByteSize() will use
+ // The map field is marked as STATE_MODIFIED_REPEATED, ByteSizeLong() will use
// repeated field which have duplicate keys to calculate.
- int duplicate_size = dynamic_message->ByteSize();
+ size_t duplicate_size = dynamic_message->ByteSizeLong();
EXPECT_TRUE(duplicate_size > expected_size);
std::string duplicate_serialized_data;
dynamic_message->SerializeToString(&duplicate_serialized_data);
- EXPECT_EQ(dynamic_message->ByteSize(), duplicate_serialized_data.size());
+ EXPECT_EQ(dynamic_message->ByteSizeLong(), duplicate_serialized_data.size());
// Force the map field to mark with map CLEAN
EXPECT_EQ(reflection_tester.MapSize(*dynamic_message, "map_int32_int32"), 2);
- // The map field is marked as CLEAN, ByteSize() will use map which do not
+ // The map field is marked as CLEAN, ByteSizeLong() will use map which do not
// have duplicate keys to calculate.
- int size = dynamic_message->ByteSize();
+ int size = dynamic_message->ByteSizeLong();
EXPECT_EQ(expected_size, size);
// Protobuf used to have a bug for serialize when map it marked CLEAN. It used
- // repeated field to calulate ByteSize but use map to serialize the real data,
- // thus the ByteSize may bigger than real serialized size. A crash might be
- // happen at SerializeToString(). Or an "unexpect end group" warning was
- // raised at parse back if user use SerializeWithCachedSizes() which avoids
- // size check at serialize.
+ // repeated field to calculate ByteSizeLong but use map to serialize the real
+ // data, thus the ByteSizeLong may bigger than real serialized size. A crash
+ // might be happen at SerializeToString(). Or an "unexpect end group" warning
+ // was raised at parse back if user use SerializeWithCachedSizes() which
+ // avoids size check at serialize.
std::string serialized_data;
dynamic_message->SerializeToString(&serialized_data);
EXPECT_EQ(serialized_data, expected_serialized_data);
@@ -3113,7 +3118,7 @@
template <typename T>
static std::string DeterministicSerializationWithSerializePartialToCodedStream(
const T& t) {
- const int size = t.ByteSize();
+ const size_t size = t.ByteSizeLong();
std::string result(size, '\0');
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
io::CodedOutputStream output_stream(&array_stream);
@@ -3127,7 +3132,7 @@
template <typename T>
static std::string DeterministicSerializationWithSerializeToCodedStream(
const T& t) {
- const int size = t.ByteSize();
+ const size_t size = t.ByteSizeLong();
std::string result(size, '\0');
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
io::CodedOutputStream output_stream(&array_stream);
@@ -3140,7 +3145,7 @@
template <typename T>
static std::string DeterministicSerialization(const T& t) {
- const int size = t.ByteSize();
+ const size_t size = t.ByteSizeLong();
std::string result(size, '\0');
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
{
@@ -3320,7 +3325,7 @@
TextFormat::Printer printer;
printer.PrintToString(source, &output);
- // Modify map via the iterator (invalidated in prvious implementation.).
+ // Modify map via the iterator (invalidated in previous implementation.).
iter->second = 2;
// In previous implementation, the new change won't be reflected in text
@@ -3350,13 +3355,13 @@
reflection->MutableRepeatedPtrField<Message>(&source, field_desc);
RepeatedPtrField<Message>::iterator iter = map_field->begin();
- // Serialize message to text format, which will invalidate the prvious
+ // Serialize message to text format, which will invalidate the previous
// iterator previously.
std::string output;
TextFormat::Printer printer;
printer.PrintToString(source, &output);
- // Modify map via the iterator (invalidated in prvious implementation.).
+ // Modify map via the iterator (invalidated in previous implementation.).
const Reflection* map_entry_reflection = iter->GetReflection();
const FieldDescriptor* value_field_desc =
iter->GetDescriptor()->FindFieldByName("value");
@@ -3505,6 +3510,8 @@
EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
}
+
+} // namespace
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/map_test_util.h b/src/google/protobuf/map_test_util.h
index 9787d3d..8f0bdcf 100644
--- a/src/google/protobuf/map_test_util.h
+++ b/src/google/protobuf/map_test_util.h
@@ -238,6 +238,51 @@
EXPECT_FALSE(map_int32_enum_val_ == nullptr);
EXPECT_FALSE(map_int32_foreign_message_key_ == nullptr);
EXPECT_FALSE(map_int32_foreign_message_val_ == nullptr);
+
+ std::vector<const FieldDescriptor*> all_map_descriptors = {
+ map_int32_int32_key_,
+ map_int32_int32_val_,
+ map_int64_int64_key_,
+ map_int64_int64_val_,
+ map_uint32_uint32_key_,
+ map_uint32_uint32_val_,
+ map_uint64_uint64_key_,
+ map_uint64_uint64_val_,
+ map_sint32_sint32_key_,
+ map_sint32_sint32_val_,
+ map_sint64_sint64_key_,
+ map_sint64_sint64_val_,
+ map_fixed32_fixed32_key_,
+ map_fixed32_fixed32_val_,
+ map_fixed64_fixed64_key_,
+ map_fixed64_fixed64_val_,
+ map_sfixed32_sfixed32_key_,
+ map_sfixed32_sfixed32_val_,
+ map_sfixed64_sfixed64_key_,
+ map_sfixed64_sfixed64_val_,
+ map_int32_float_key_,
+ map_int32_float_val_,
+ map_int32_double_key_,
+ map_int32_double_val_,
+ map_bool_bool_key_,
+ map_bool_bool_val_,
+ map_string_string_key_,
+ map_string_string_val_,
+ map_int32_bytes_key_,
+ map_int32_bytes_val_,
+ map_int32_enum_key_,
+ map_int32_enum_val_,
+ map_int32_foreign_message_key_,
+ map_int32_foreign_message_val_};
+ for (const FieldDescriptor* fdesc : all_map_descriptors) {
+ GOOGLE_CHECK(fdesc->containing_type() != nullptr) << fdesc->name();
+ if (fdesc->name() == "key") {
+ EXPECT_EQ(fdesc->containing_type()->map_key(), fdesc);
+ } else {
+ EXPECT_EQ(fdesc->name(), "value");
+ EXPECT_EQ(fdesc->containing_type()->map_value(), fdesc);
+ }
+ }
}
// Shorthand to get a FieldDescriptor for a field of unittest::TestMap.
diff --git a/src/google/protobuf/map_test_util.inc b/src/google/protobuf/map_test_util.inc
old mode 100755
new mode 100644
diff --git a/src/google/protobuf/map_type_handler.h b/src/google/protobuf/map_type_handler.h
index d63a10c..5efc6fb 100644
--- a/src/google/protobuf/map_type_handler.h
+++ b/src/google/protobuf/map_type_handler.h
@@ -155,13 +155,13 @@
typedef typename MapWireFieldTypeTraits<WireFormatLite::TYPE_MESSAGE,
Type>::TypeOnMemory TypeOnMemory;
// Corresponding wire type for field type.
- static const WireFormatLite::WireType kWireType =
+ static constexpr WireFormatLite::WireType kWireType =
MapWireFieldTypeTraits<WireFormatLite::TYPE_MESSAGE, Type>::kWireType;
// Whether wire type is for message.
- static const bool kIsMessage =
+ static constexpr bool kIsMessage =
MapWireFieldTypeTraits<WireFormatLite::TYPE_MESSAGE, Type>::kIsMessage;
// Whether wire type is for enum.
- static const bool kIsEnum =
+ static constexpr bool kIsEnum =
MapWireFieldTypeTraits<WireFormatLite::TYPE_MESSAGE, Type>::kIsEnum;
// Functions used in parsing and serialization. ===================
@@ -467,11 +467,11 @@
}
template <typename E>
inline const char* ReadENUM(const char* ptr, E* value) {
- *value = static_cast<E>(ReadVarint(&ptr));
+ *value = static_cast<E>(ReadVarint32(&ptr));
return ptr;
}
inline const char* ReadBOOL(const char* ptr, bool* value) {
- *value = static_cast<bool>(ReadVarint(&ptr));
+ *value = static_cast<bool>(ReadVarint32(&ptr));
return ptr;
}
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc
index 5d768b9..d35dfff 100644
--- a/src/google/protobuf/message.cc
+++ b/src/google/protobuf/message.cc
@@ -32,13 +32,12 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <google/protobuf/message.h>
+
#include <iostream>
#include <stack>
#include <unordered_map>
-#include <google/protobuf/generated_message_reflection.h>
-#include <google/protobuf/message.h>
-
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -48,6 +47,7 @@
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/map_field_inl.h>
@@ -136,388 +136,9 @@
return ReflectionOps::DiscardUnknownFields(this);
}
-namespace internal {
-
-class ReflectionAccessor {
- public:
- static void* GetOffset(void* msg, const google::protobuf::FieldDescriptor* f,
- const google::protobuf::Reflection* r) {
- return static_cast<char*>(msg) + r->schema_.GetFieldOffset(f);
- }
-
- static void* GetRepeatedEnum(const Reflection* reflection,
- const FieldDescriptor* field, Message* msg) {
- return reflection->MutableRawRepeatedField(
- msg, field, FieldDescriptor::CPPTYPE_ENUM, 0, nullptr);
- }
-
- static InternalMetadataWithArena* MutableInternalMetadataWithArena(
- const Reflection* reflection, Message* msg) {
- return reflection->MutableInternalMetadataWithArena(msg);
- }
-};
-
-} // namespace internal
-
-void SetField(uint64 val, const FieldDescriptor* field, Message* msg,
- const Reflection* reflection) {
-#define STORE_TYPE(CPPTYPE_METHOD) \
- do \
- if (field->is_repeated()) { \
- reflection->Add##CPPTYPE_METHOD(msg, field, value); \
- } else { \
- reflection->Set##CPPTYPE_METHOD(msg, field, value); \
- } \
- while (0)
-
- switch (field->type()) {
-#define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
- case FieldDescriptor::TYPE_##TYPE: { \
- CPPTYPE value = val; \
- STORE_TYPE(CPPTYPE_METHOD); \
- break; \
- }
-
- // Varints
- HANDLE_TYPE(INT32, int32, Int32)
- HANDLE_TYPE(INT64, int64, Int64)
- HANDLE_TYPE(UINT32, uint32, UInt32)
- HANDLE_TYPE(UINT64, uint64, UInt64)
- case FieldDescriptor::TYPE_SINT32: {
- int32 value = WireFormatLite::ZigZagDecode32(val);
- STORE_TYPE(Int32);
- break;
- }
- case FieldDescriptor::TYPE_SINT64: {
- int64 value = WireFormatLite::ZigZagDecode64(val);
- STORE_TYPE(Int64);
- break;
- }
- HANDLE_TYPE(BOOL, bool, Bool)
-
- // Fixed
- HANDLE_TYPE(FIXED32, uint32, UInt32)
- HANDLE_TYPE(FIXED64, uint64, UInt64)
- HANDLE_TYPE(SFIXED32, int32, Int32)
- HANDLE_TYPE(SFIXED64, int64, Int64)
-
- case FieldDescriptor::TYPE_FLOAT: {
- float value;
- uint32 bit_rep = val;
- std::memcpy(&value, &bit_rep, sizeof(value));
- STORE_TYPE(Float);
- break;
- }
- case FieldDescriptor::TYPE_DOUBLE: {
- double value;
- uint64 bit_rep = val;
- std::memcpy(&value, &bit_rep, sizeof(value));
- STORE_TYPE(Double);
- break;
- }
- case FieldDescriptor::TYPE_ENUM: {
- int value = val;
- if (field->is_repeated()) {
- reflection->AddEnumValue(msg, field, value);
- } else {
- reflection->SetEnumValue(msg, field, value);
- }
- break;
- }
- default:
- GOOGLE_LOG(FATAL) << "Error in descriptors, primitve field with field type "
- << field->type();
- }
-#undef STORE_TYPE
-#undef HANDLE_TYPE
-}
-
-bool ReflectiveValidator(const void* arg, int val) {
- auto d = static_cast<const EnumDescriptor*>(arg);
- return d->FindValueByNumber(val) != nullptr;
-}
-
-const char* ParsePackedField(const FieldDescriptor* field, Message* msg,
- const Reflection* reflection, const char* ptr,
- internal::ParseContext* ctx) {
- switch (field->type()) {
-#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, METHOD_NAME) \
- case FieldDescriptor::TYPE_##TYPE: \
- return internal::Packed##METHOD_NAME##Parser( \
- reflection->MutableRepeatedFieldInternal<CPPTYPE>(msg, field), ptr, \
- ctx)
- HANDLE_PACKED_TYPE(INT32, int32, Int32);
- HANDLE_PACKED_TYPE(INT64, int64, Int64);
- HANDLE_PACKED_TYPE(SINT32, int32, SInt32);
- HANDLE_PACKED_TYPE(SINT64, int64, SInt64);
- HANDLE_PACKED_TYPE(UINT32, uint32, UInt32);
- HANDLE_PACKED_TYPE(UINT64, uint64, UInt64);
- HANDLE_PACKED_TYPE(BOOL, bool, Bool);
- case FieldDescriptor::TYPE_ENUM: {
- auto object =
- internal::ReflectionAccessor::GetRepeatedEnum(reflection, field, msg);
- if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
- return internal::PackedEnumParser(object, ptr, ctx);
- } else {
- return internal::PackedEnumParserArg(
- object, ptr, ctx, ReflectiveValidator, field->enum_type(),
- internal::ReflectionAccessor::MutableInternalMetadataWithArena(
- reflection, msg),
- field->number());
- }
- }
- HANDLE_PACKED_TYPE(FIXED32, uint32, Fixed32);
- HANDLE_PACKED_TYPE(FIXED64, uint64, Fixed64);
- HANDLE_PACKED_TYPE(SFIXED32, int32, SFixed32);
- HANDLE_PACKED_TYPE(SFIXED64, int64, SFixed64);
- HANDLE_PACKED_TYPE(FLOAT, float, Float);
- HANDLE_PACKED_TYPE(DOUBLE, double, Double);
-#undef HANDLE_PACKED_TYPE
-
- default:
- GOOGLE_LOG(FATAL) << "Type is not packable " << field->type();
- return nullptr; // Make compiler happy
- }
-}
-
-const char* ParseLenDelim(int field_number, const FieldDescriptor* field,
- Message* msg, const Reflection* reflection,
- const char* ptr, internal::ParseContext* ctx) {
- if (WireFormat::WireTypeForFieldType(field->type()) !=
- WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
- GOOGLE_DCHECK(field->is_packable());
- return ParsePackedField(field, msg, reflection, ptr, ctx);
- }
- enum { kNone = 0, kVerify, kStrict } utf8_level = kNone;
- const char* field_name = nullptr;
- auto parse_string = [ptr, ctx, &utf8_level,
- &field_name](std::string* s) -> const char* {
- auto res = internal::InlineGreedyStringParser(s, ptr, ctx);
- if (utf8_level != kNone) {
- if (!internal::VerifyUTF8(s, field_name) && utf8_level == kStrict) {
- return nullptr;
- }
- }
- return res;
- };
- switch (field->type()) {
- case FieldDescriptor::TYPE_STRING: {
- bool enforce_utf8 = true;
- bool utf8_verification = true;
- if (enforce_utf8 &&
- field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
- utf8_level = kStrict;
- } else if (utf8_verification) {
- utf8_level = kVerify;
- }
- field_name = field->full_name().c_str();
- PROTOBUF_FALLTHROUGH_INTENDED;
- }
- case FieldDescriptor::TYPE_BYTES: {
- if (field->is_repeated()) {
- int index = reflection->FieldSize(*msg, field);
- // Add new empty value.
- reflection->AddString(msg, field, "");
- if (field->options().ctype() == FieldOptions::STRING ||
- field->is_extension()) {
- auto object =
- reflection
- ->MutableRepeatedPtrFieldInternal<std::string>(msg, field)
- ->Mutable(index);
- return parse_string(object);
- } else {
- auto object =
- reflection
- ->MutableRepeatedPtrFieldInternal<std::string>(msg, field)
- ->Mutable(index);
- return parse_string(object);
- }
- } else {
- // Clear value and make sure it's set.
- reflection->SetString(msg, field, "");
- if (field->options().ctype() == FieldOptions::STRING ||
- field->is_extension()) {
- // HACK around inability to get mutable_string in reflection
- std::string* object = &const_cast<std::string&>(
- reflection->GetStringReference(*msg, field, nullptr));
- return parse_string(object);
- } else {
- // HACK around inability to get mutable_string in reflection
- std::string* object = &const_cast<std::string&>(
- reflection->GetStringReference(*msg, field, nullptr));
- return parse_string(object);
- }
- }
- GOOGLE_LOG(FATAL) << "No other type than string supported";
- }
- case FieldDescriptor::TYPE_MESSAGE: {
- Message* object;
- if (field->is_repeated()) {
- object = reflection->AddMessage(msg, field, ctx->data().factory);
- } else {
- object = reflection->MutableMessage(msg, field, ctx->data().factory);
- }
- return ctx->ParseMessage(object, ptr);
- }
- default:
- GOOGLE_LOG(FATAL) << "Wrong type for length delim " << field->type();
- }
- return nullptr; // Make compiler happy.
-}
-
-Message* GetGroup(int field_number, const FieldDescriptor* field, Message* msg,
- const Reflection* reflection) {
- if (field->is_repeated()) {
- return reflection->AddMessage(msg, field, nullptr);
- } else {
- return reflection->MutableMessage(msg, field, nullptr);
- }
-}
-
const char* Message::_InternalParse(const char* ptr,
internal::ParseContext* ctx) {
- class ReflectiveFieldParser {
- public:
- ReflectiveFieldParser(Message* msg, internal::ParseContext* ctx)
- : ReflectiveFieldParser(msg, ctx, false) {}
-
- void AddVarint(uint32 num, uint64 value) {
- if (is_item_ && num == 2) {
- if (!payload_.empty()) {
- auto field = Field(value, 2);
- if (field && field->message_type()) {
- auto child = reflection_->MutableMessage(msg_, field);
- // TODO(gerbens) signal error
- child->ParsePartialFromString(payload_);
- } else {
- MutableUnknown()->AddLengthDelimited(value)->swap(payload_);
- }
- return;
- }
- type_id_ = value;
- return;
- }
- auto field = Field(num, 0);
- if (field) {
- SetField(value, field, msg_, reflection_);
- } else {
- MutableUnknown()->AddVarint(num, value);
- }
- }
- void AddFixed64(uint32 num, uint64 value) {
- auto field = Field(num, 1);
- if (field) {
- SetField(value, field, msg_, reflection_);
- } else {
- MutableUnknown()->AddFixed64(num, value);
- }
- }
- const char* ParseLengthDelimited(uint32 num, const char* ptr,
- internal::ParseContext* ctx) {
- if (is_item_ && num == 3) {
- if (type_id_ == 0) {
- return InlineGreedyStringParser(&payload_, ptr, ctx);
- }
- num = type_id_;
- type_id_ = 0;
- }
- auto field = Field(num, 2);
- if (field) {
- return ParseLenDelim(num, field, msg_, reflection_, ptr, ctx);
- } else {
- return InlineGreedyStringParser(
- MutableUnknown()->AddLengthDelimited(num), ptr, ctx);
- }
- }
- const char* ParseGroup(uint32 num, const char* ptr,
- internal::ParseContext* ctx) {
- if (!is_item_ && descriptor_->options().message_set_wire_format() &&
- num == 1) {
- is_item_ = true;
- ptr = ctx->ParseGroup(this, ptr, num * 8 + 3);
- is_item_ = false;
- type_id_ = 0;
- return ptr;
- }
- auto field = Field(num, 3);
- if (field) {
- auto msg = GetGroup(num, field, msg_, reflection_);
- return ctx->ParseGroup(msg, ptr, num * 8 + 3);
- } else {
- return UnknownFieldParse(num * 8 + 3, MutableUnknown(), ptr, ctx);
- }
- }
- void AddFixed32(uint32 num, uint32 value) {
- auto field = Field(num, 5);
- if (field) {
- SetField(value, field, msg_, reflection_);
- } else {
- MutableUnknown()->AddFixed32(num, value);
- }
- }
-
- const char* _InternalParse(const char* ptr, internal::ParseContext* ctx) {
- // We're parsing the a MessageSetItem
- GOOGLE_DCHECK(is_item_);
- return internal::WireFormatParser(*this, ptr, ctx);
- }
-
- private:
- Message* msg_;
- const Descriptor* descriptor_;
- const Reflection* reflection_;
- internal::ParseContext* ctx_;
- UnknownFieldSet* unknown_ = nullptr;
- bool is_item_ = false;
- uint32 type_id_ = 0;
- std::string payload_;
-
- ReflectiveFieldParser(Message* msg, internal::ParseContext* ctx,
- bool is_item)
- : msg_(msg),
- descriptor_(msg->GetDescriptor()),
- reflection_(msg->GetReflection()),
- ctx_(ctx),
- is_item_(is_item) {
- GOOGLE_CHECK(descriptor_) << msg->GetTypeName();
- GOOGLE_CHECK(reflection_) << msg->GetTypeName();
- }
-
- const FieldDescriptor* Field(int num, int wire_type) {
- auto field = descriptor_->FindFieldByNumber(num);
-
- // If that failed, check if the field is an extension.
- if (field == nullptr && descriptor_->IsExtensionNumber(num)) {
- const DescriptorPool* pool = ctx_->data().pool;
- if (pool == nullptr) {
- field = reflection_->FindKnownExtensionByNumber(num);
- } else {
- field = pool->FindExtensionByNumber(descriptor_, num);
- }
- }
- if (field == nullptr) return nullptr;
-
- if (internal::WireFormat::WireTypeForFieldType(field->type()) !=
- wire_type) {
- if (field->is_packable()) {
- if (wire_type ==
- internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
- return field;
- }
- }
- return nullptr;
- }
- return field;
- }
-
- UnknownFieldSet* MutableUnknown() {
- if (unknown_) return unknown_;
- return unknown_ = reflection_->MutableUnknownFields(msg_);
- }
- };
-
- ReflectiveFieldParser field_parser(this, ctx);
- return internal::WireFormatParser(field_parser, ptr, ctx);
+ return WireFormat::_InternalParse(this, ptr, ctx);
}
uint8* Message::_InternalSerialize(uint8* target,
@@ -548,6 +169,11 @@
namespace {
+
+#define HASH_MAP std::unordered_map
+#define HASH_FXN hash
+
+
class GeneratedMessageFactory : public MessageFactory {
public:
static GeneratedMessageFactory* singleton();
@@ -560,8 +186,8 @@
private:
// Only written at static init time, so does not require locking.
- std::unordered_map<const char*, const google::protobuf::internal::DescriptorTable*,
- hash<const char*>, streq>
+ HASH_MAP<const char*, const google::protobuf::internal::DescriptorTable*,
+ HASH_FXN<const char*>, streq>
file_map_;
internal::WrappedMutex mutex_;
diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h
index 237ba73..13762be 100644
--- a/src/google/protobuf/message.h
+++ b/src/google/protobuf/message.h
@@ -192,6 +192,26 @@
const Reflection* reflection;
};
+namespace internal {
+template <class To>
+inline To* GetPointerAtOffset(Message* message, uint32 offset) {
+ return reinterpret_cast<To*>(reinterpret_cast<char*>(message) + offset);
+}
+
+template <class To>
+const To* GetConstPointerAtOffset(const Message* message, uint32 offset) {
+ return reinterpret_cast<const To*>(reinterpret_cast<const char*>(message) +
+ offset);
+}
+
+template <class To>
+const To& GetConstRefAtOffset(const Message& message, uint32 offset) {
+ return *GetConstPointerAtOffset<To>(&message, offset);
+}
+
+bool CreateUnknownEnumValues(const FieldDescriptor* field);
+} // namespace internal
+
// Abstract interface for protocol messages.
//
// See also MessageLite, which contains most every-day operations. Message
@@ -202,10 +222,12 @@
// optimized for speed will want to override these with faster implementations,
// but classes optimized for code size may be happy with keeping them. See
// the optimize_for option in descriptor.proto.
+//
+// Users must not derive from this class. Only the protocol compiler and
+// the internal library are allowed to create subclasses.
class PROTOBUF_EXPORT Message : public MessageLite {
public:
inline Message() {}
- ~Message() override {}
// Basic Operations ------------------------------------------------
@@ -337,6 +359,8 @@
// to implement GetDescriptor() and GetReflection() above.
virtual Metadata GetMetadata() const = 0;
+ inline explicit Message(Arena* arena) : MessageLite(arena) {}
+
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Message);
@@ -716,8 +740,7 @@
// long as the message is not destroyed.
//
// Note that to use this method users need to include the header file
- // "net/proto2/public/reflection.h" (which defines the RepeatedFieldRef
- // class templates).
+ // "reflection.h" (which defines the RepeatedFieldRef class templates).
template <typename T>
RepeatedFieldRef<T> GetRepeatedFieldRef(const Message& message,
const FieldDescriptor* field) const;
@@ -914,7 +937,6 @@
friend class internal::ReflectionOps;
// Needed for implementing text format for map.
friend class internal::MapFieldPrinterHelper;
- friend class internal::ReflectionAccessor;
Reflection(const Descriptor* descriptor,
const internal::ReflectionSchema& schema,
@@ -936,7 +958,7 @@
// If key is in map field: Saves the value pointer to val and returns
// false. If key in not in map field: Insert the key into map, saves
- // value pointer to val and retuns true.
+ // value pointer to val and returns true.
bool InsertOrLookupMapValue(Message* message, const FieldDescriptor* field,
const MapKey& key, MapValueRef* val) const;
@@ -980,7 +1002,7 @@
template <typename Type>
inline Type* MutableRaw(Message* message, const FieldDescriptor* field) const;
template <typename Type>
- inline const Type& DefaultRaw(const FieldDescriptor* field) const;
+ const Type& DefaultRaw(const FieldDescriptor* field) const;
inline const uint32* GetHasBits(const Message& message) const;
inline uint32* MutableHasBits(Message* message) const;
@@ -988,16 +1010,17 @@
const OneofDescriptor* oneof_descriptor) const;
inline uint32* MutableOneofCase(
Message* message, const OneofDescriptor* oneof_descriptor) const;
- inline const internal::ExtensionSet& GetExtensionSet(
- const Message& message) const;
- inline internal::ExtensionSet* MutableExtensionSet(Message* message) const;
+ inline bool HasExtensionSet(const Message& message) const {
+ return schema_.HasExtensionSet();
+ }
+ const internal::ExtensionSet& GetExtensionSet(const Message& message) const;
+ internal::ExtensionSet* MutableExtensionSet(Message* message) const;
inline Arena* GetArena(Message* message) const;
- inline const internal::InternalMetadataWithArena&
- GetInternalMetadataWithArena(const Message& message) const;
+ inline const internal::InternalMetadata& GetInternalMetadata(
+ const Message& message) const;
- internal::InternalMetadataWithArena* MutableInternalMetadataWithArena(
- Message* message) const;
+ internal::InternalMetadata* MutableInternalMetadata(Message* message) const;
inline bool IsInlined(const FieldDescriptor* field) const;
@@ -1193,11 +1216,11 @@
const Message* unused = static_cast<T*>(nullptr);
(void)unused;
-#ifdef GOOGLE_PROTOBUF_NO_RTTI
+#if PROTOBUF_RTTI
+ return dynamic_cast<const T*>(from);
+#else
bool ok = T::default_instance().GetReflection() == from->GetReflection();
return ok ? down_cast<const T*>(from) : nullptr;
-#else
- return dynamic_cast<const T*>(from);
#endif
}
@@ -1287,6 +1310,11 @@
MutableRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE,
-1, PB::default_instance().GetDescriptor()));
}
+
+template <typename Type>
+const Type& Reflection::DefaultRaw(const FieldDescriptor* field) const {
+ return *reinterpret_cast<const Type*>(schema_.GetFieldDefault(field));
+}
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc
index 4f5cc5f..5b1db7b 100644
--- a/src/google/protobuf/message_lite.cc
+++ b/src/google/protobuf/message_lite.cc
@@ -117,6 +117,16 @@
return StringPiece(static_cast<const char*>(data), size);
}
+// Returns true of all required fields are present / have values.
+inline bool CheckFieldPresence(const internal::ParseContext& ctx,
+ const MessageLite& msg,
+ MessageLite::ParseFlags parse_flags) {
+ if (PROTOBUF_PREDICT_FALSE((parse_flags & MessageLite::kMergePartial) != 0)) {
+ return true;
+ }
+ return msg.IsInitializedWithErrors();
+}
+
} // namespace
void MessageLite::LogInitializationErrorMessage() const {
@@ -126,46 +136,62 @@
namespace internal {
template <bool aliasing>
-bool MergePartialFromImpl(StringPiece input, MessageLite* msg) {
+bool MergeFromImpl(StringPiece input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags) {
const char* ptr;
internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(),
aliasing, &ptr, input);
ptr = msg->_InternalParse(ptr, &ctx);
// ctx has an explicit limit set (length of string_view).
- return ptr && ctx.EndedAtLimit();
+ if (PROTOBUF_PREDICT_TRUE(ptr && ctx.EndedAtLimit())) {
+ return CheckFieldPresence(ctx, *msg, parse_flags);
+ }
+ return false;
}
template <bool aliasing>
-bool MergePartialFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg) {
+bool MergeFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags) {
const char* ptr;
internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(),
aliasing, &ptr, input);
ptr = msg->_InternalParse(ptr, &ctx);
// ctx has no explicit limit (hence we end on end of stream)
- return ptr && ctx.EndedAtEndOfStream();
+ if (PROTOBUF_PREDICT_TRUE(ptr && ctx.EndedAtEndOfStream())) {
+ return CheckFieldPresence(ctx, *msg, parse_flags);
+ }
+ return false;
}
template <bool aliasing>
-bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg) {
+bool MergeFromImpl(BoundedZCIS input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags) {
const char* ptr;
internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(),
aliasing, &ptr, input.zcis, input.limit);
ptr = msg->_InternalParse(ptr, &ctx);
if (PROTOBUF_PREDICT_FALSE(!ptr)) return false;
ctx.BackUp(ptr);
- return ctx.EndedAtLimit();
+ if (PROTOBUF_PREDICT_TRUE(ctx.EndedAtLimit())) {
+ return CheckFieldPresence(ctx, *msg, parse_flags);
+ }
+ return false;
}
-template bool MergePartialFromImpl<false>(StringPiece input,
- MessageLite* msg);
-template bool MergePartialFromImpl<true>(StringPiece input,
- MessageLite* msg);
-template bool MergePartialFromImpl<false>(io::ZeroCopyInputStream* input,
- MessageLite* msg);
-template bool MergePartialFromImpl<true>(io::ZeroCopyInputStream* input,
- MessageLite* msg);
-template bool MergePartialFromImpl<false>(BoundedZCIS input, MessageLite* msg);
-template bool MergePartialFromImpl<true>(BoundedZCIS input, MessageLite* msg);
+template bool MergeFromImpl<false>(StringPiece input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+template bool MergeFromImpl<true>(StringPiece input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+template bool MergeFromImpl<false>(io::ZeroCopyInputStream* input,
+ MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+template bool MergeFromImpl<true>(io::ZeroCopyInputStream* input,
+ MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+template bool MergeFromImpl<false>(BoundedZCIS input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+template bool MergeFromImpl<true>(BoundedZCIS input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
} // namespace internal
@@ -195,7 +221,8 @@
io::CodedInputStream* cis_;
};
-bool MessageLite::MergePartialFromCodedStream(io::CodedInputStream* input) {
+bool MessageLite::MergeFromImpl(io::CodedInputStream* input,
+ MessageLite::ParseFlags parse_flags) {
ZeroCopyCodedInputStream zcis(input);
const char* ptr;
internal::ParseContext ctx(input->RecursionBudget(), zcis.aliasing_enabled(),
@@ -213,24 +240,28 @@
GOOGLE_DCHECK(ctx.LastTag() != 1); // We can't end on a pushed limit.
if (ctx.IsExceedingLimit(ptr)) return false;
input->SetLastTag(ctx.LastTag());
- return true;
+ } else {
+ input->SetConsumed();
}
- input->SetConsumed();
- return true;
+ return CheckFieldPresence(ctx, *this, parse_flags);
+}
+
+bool MessageLite::MergePartialFromCodedStream(io::CodedInputStream* input) {
+ return MergeFromImpl(input, kMergePartial);
}
bool MessageLite::MergeFromCodedStream(io::CodedInputStream* input) {
- return MergePartialFromCodedStream(input) && IsInitializedWithErrors();
+ return MergeFromImpl(input, kMerge);
}
bool MessageLite::ParseFromCodedStream(io::CodedInputStream* input) {
Clear();
- return MergeFromCodedStream(input);
+ return MergeFromImpl(input, kParse);
}
bool MessageLite::ParsePartialFromCodedStream(io::CodedInputStream* input) {
Clear();
- return MergePartialFromCodedStream(input);
+ return MergeFromImpl(input, kParsePartial);
}
bool MessageLite::ParseFromZeroCopyStream(io::ZeroCopyInputStream* input) {
diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h
index 31746f3..32a79bd 100644
--- a/src/google/protobuf/message_lite.h
+++ b/src/google/protobuf/message_lite.h
@@ -46,6 +46,7 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/port.h>
#include <google/protobuf/stubs/strutil.h>
@@ -181,10 +182,13 @@
// is best when you only have a small number of message types linked
// into your binary, in which case the size of the protocol buffers
// runtime itself is the biggest problem.
+//
+// Users must not derive from this class. Only the protocol compiler and
+// the internal library are allowed to create subclasses.
class PROTOBUF_EXPORT MessageLite {
public:
inline MessageLite() {}
- virtual ~MessageLite() {}
+ virtual ~MessageLite() = default;
// Basic Operations ------------------------------------------------
@@ -201,10 +205,10 @@
// Get the arena, if any, associated with this message. Virtual method
// required for generic operations but most arena-related operations should
- // use the GetArenaNoVirtual() generated-code method. Default implementation
+ // use the GetArena() generated-code method. Default implementation
// to reduce code size by avoiding the need for per-type implementations
// when types do not implement arena support.
- virtual Arena* GetArena() const { return NULL; }
+ Arena* GetArena() const { return _internal_metadata_.arena(); }
// Get a pointer that may be equal to this message's arena, or may not be.
// If the value returned by this method is equal to some arena pointer, then
@@ -215,7 +219,9 @@
// store the arena pointer directly, and sometimes in a more indirect way,
// and allow a fastpath comparison against the arena pointer when it's easy
// to obtain.
- virtual void* GetMaybeArenaPointer() const { return GetArena(); }
+ void* GetMaybeArenaPointer() const {
+ return _internal_metadata_.raw_arena_ptr();
+ }
// Clear all fields of the message and set them to their default values.
// Clear() avoids freeing memory, assuming that any memory allocated
@@ -444,6 +450,10 @@
return Arena::CreateMaybeMessage<T>(arena);
}
+ inline explicit MessageLite(Arena* arena) : _internal_metadata_(arena) {}
+
+ internal::InternalMetadata _internal_metadata_;
+
public:
enum ParseFlags {
kMerge = 0,
@@ -464,6 +474,13 @@
virtual uint8* _InternalSerialize(uint8* ptr,
io::EpsCopyOutputStream* stream) const = 0;
+ // Identical to IsInitialized() except that it logs an error message.
+ bool IsInitializedWithErrors() const {
+ if (IsInitialized()) return true;
+ LogInitializationErrorMessage();
+ return false;
+ }
+
private:
// TODO(gerbens) make this a pure abstract function
virtual const void* InternalGetTable() const { return NULL; }
@@ -472,32 +489,34 @@
friend class Message;
friend class internal::WeakFieldMap;
- bool IsInitializedWithErrors() const {
- if (IsInitialized()) return true;
- LogInitializationErrorMessage();
- return false;
- }
-
void LogInitializationErrorMessage() const;
+ bool MergeFromImpl(io::CodedInputStream* input, ParseFlags parse_flags);
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite);
};
namespace internal {
template <bool alias>
-bool MergePartialFromImpl(StringPiece input, MessageLite* msg);
-extern template bool MergePartialFromImpl<false>(StringPiece input,
- MessageLite* msg);
-extern template bool MergePartialFromImpl<true>(StringPiece input,
- MessageLite* msg);
+bool MergeFromImpl(StringPiece input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+extern template bool MergeFromImpl<false>(StringPiece input,
+ MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+extern template bool MergeFromImpl<true>(StringPiece input,
+ MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
template <bool alias>
-bool MergePartialFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg);
-extern template bool MergePartialFromImpl<false>(io::ZeroCopyInputStream* input,
- MessageLite* msg);
-extern template bool MergePartialFromImpl<true>(io::ZeroCopyInputStream* input,
- MessageLite* msg);
+bool MergeFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+extern template bool MergeFromImpl<false>(io::ZeroCopyInputStream* input,
+ MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+extern template bool MergeFromImpl<true>(io::ZeroCopyInputStream* input,
+ MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
struct BoundedZCIS {
io::ZeroCopyInputStream* zcis;
@@ -505,18 +524,20 @@
};
template <bool alias>
-bool MergePartialFromImpl(BoundedZCIS input, MessageLite* msg);
-extern template bool MergePartialFromImpl<false>(BoundedZCIS input,
- MessageLite* msg);
-extern template bool MergePartialFromImpl<true>(BoundedZCIS input,
- MessageLite* msg);
+bool MergeFromImpl(BoundedZCIS input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+extern template bool MergeFromImpl<false>(BoundedZCIS input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
+extern template bool MergeFromImpl<true>(BoundedZCIS input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags);
template <typename T>
struct SourceWrapper;
template <bool alias, typename T>
-bool MergePartialFromImpl(const SourceWrapper<T>& input, MessageLite* msg) {
- return input.template MergePartialInto<alias>(msg);
+bool MergeFromImpl(const SourceWrapper<T>& input, MessageLite* msg,
+ MessageLite::ParseFlags parse_flags) {
+ return input.template MergeInto<alias>(msg, parse_flags);
}
} // namespace internal
@@ -524,9 +545,8 @@
template <MessageLite::ParseFlags flags, typename T>
bool MessageLite::ParseFrom(const T& input) {
if (flags & kParse) Clear();
- constexpr bool alias = flags & kMergeWithAliasing;
- bool res = internal::MergePartialFromImpl<alias>(input, this);
- return res && ((flags & kMergePartial) || IsInitializedWithErrors());
+ constexpr bool alias = (flags & kMergeWithAliasing) != 0;
+ return internal::MergeFromImpl<alias>(input, this, flags);
}
// ===================================================================
diff --git a/src/google/protobuf/message_unittest.inc b/src/google/protobuf/message_unittest.inc
index 843a1c0..46ae35d 100644
--- a/src/google/protobuf/message_unittest.inc
+++ b/src/google/protobuf/message_unittest.inc
@@ -309,7 +309,7 @@
private:
std::string data_;
- size_t count_; // The number of strings that haven't been consuemd.
+ size_t count_; // The number of strings that haven't been consumed.
size_t position_; // Position in the std::string for the next read.
int64 total_byte_count_;
};
@@ -331,7 +331,7 @@
UNITTEST::TestAllTypes result;
EXPECT_TRUE(result.ParseFromZeroCopyStream(&input));
- // When there are multiple occurences of a singulr field, the last one
+ // When there are multiple occurrences of a singular field, the last one
// should win.
EXPECT_EQ(value, result.optional_string());
}
diff --git a/src/google/protobuf/metadata.h b/src/google/protobuf/metadata.h
index 009a7e9..4e89648 100644
--- a/src/google/protobuf/metadata.h
+++ b/src/google/protobuf/metadata.h
@@ -28,51 +28,9 @@
// (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 header file defines an internal class that encapsulates internal message
-// metadata (Unknown-field set, Arena pointer, ...) and allows its
-// representation to be made more space-efficient via various optimizations.
-//
-// Note that this is distinct from google::protobuf::Metadata, which encapsulates
-// Descriptor and Reflection pointers.
-
#ifndef GOOGLE_PROTOBUF_METADATA_H__
#define GOOGLE_PROTOBUF_METADATA_H__
-#include <google/protobuf/metadata_lite.h>
-#include <google/protobuf/unknown_field_set.h>
-
-#ifdef SWIG
-#error "You cannot SWIG proto headers"
-#endif
-
-namespace google {
-namespace protobuf {
-namespace internal {
-
-class InternalMetadataWithArena
- : public InternalMetadataWithArenaBase<UnknownFieldSet,
- InternalMetadataWithArena> {
- public:
- InternalMetadataWithArena() {}
- explicit InternalMetadataWithArena(Arena* arena)
- : InternalMetadataWithArenaBase<UnknownFieldSet,
- InternalMetadataWithArena>(arena) {}
-
- void DoSwap(UnknownFieldSet* other) { mutable_unknown_fields()->Swap(other); }
-
- void DoMergeFrom(const UnknownFieldSet& other) {
- mutable_unknown_fields()->MergeFrom(other);
- }
-
- void DoClear() { mutable_unknown_fields()->Clear(); }
-
- static const UnknownFieldSet& default_instance() {
- return *UnknownFieldSet::default_instance();
- }
-};
-
-} // namespace internal
-} // namespace protobuf
-} // namespace google
+// TODO(b/151117630): Remove this file and all instances where it gets imported.
#endif // GOOGLE_PROTOBUF_METADATA_H__
diff --git a/src/google/protobuf/metadata_lite.h b/src/google/protobuf/metadata_lite.h
index 40c7ea7..781a1f5 100644
--- a/src/google/protobuf/metadata_lite.h
+++ b/src/google/protobuf/metadata_lite.h
@@ -34,8 +34,6 @@
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/arena.h>
-#include <google/protobuf/generated_message_util.h>
-#include <google/protobuf/message_lite.h>
#include <google/protobuf/port.h>
#include <google/protobuf/port_def.inc>
@@ -58,38 +56,22 @@
// The tagged pointer uses the LSB to disambiguate cases, and uses bit 0 == 0 to
// indicate an arena pointer and bit 0 == 1 to indicate a UFS+Arena-container
// pointer.
-template <class T, class Derived>
-class InternalMetadataWithArenaBase {
+class InternalMetadata {
public:
- InternalMetadataWithArenaBase() : ptr_(NULL) {}
- explicit InternalMetadataWithArenaBase(Arena* arena) : ptr_(arena) {}
+ InternalMetadata() : ptr_(nullptr) {}
+ explicit InternalMetadata(Arena* arena) : ptr_(arena) {}
- ~InternalMetadataWithArenaBase() {
+ template <typename T>
+ void Delete() {
+ // Note that Delete<> should be called not more than once.
if (have_unknown_fields() && arena() == NULL) {
- delete PtrValue<Container>();
- }
- ptr_ = NULL;
- }
-
- PROTOBUF_ALWAYS_INLINE const T& unknown_fields() const {
- if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) {
- return PtrValue<Container>()->unknown_fields;
- } else {
- return Derived::default_instance();
- }
- }
-
- PROTOBUF_ALWAYS_INLINE T* mutable_unknown_fields() {
- if (PROTOBUF_PREDICT_TRUE(have_unknown_fields())) {
- return &PtrValue<Container>()->unknown_fields;
- } else {
- return mutable_unknown_fields_slow();
+ delete PtrValue<Container<T>>();
}
}
PROTOBUF_ALWAYS_INLINE Arena* arena() const {
if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) {
- return PtrValue<Container>()->arena;
+ return PtrValue<ContainerBase>()->arena;
} else {
return PtrValue<Arena>();
}
@@ -99,7 +81,29 @@
return PtrTag() == kTagContainer;
}
- PROTOBUF_ALWAYS_INLINE void Swap(Derived* other) {
+ PROTOBUF_ALWAYS_INLINE void* raw_arena_ptr() const { return ptr_; }
+
+ template <typename T>
+ PROTOBUF_ALWAYS_INLINE const T& unknown_fields(
+ const T& (*default_instance)()) const {
+ if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) {
+ return PtrValue<Container<T>>()->unknown_fields;
+ } else {
+ return default_instance();
+ }
+ }
+
+ template <typename T>
+ PROTOBUF_ALWAYS_INLINE T* mutable_unknown_fields() {
+ if (PROTOBUF_PREDICT_TRUE(have_unknown_fields())) {
+ return &PtrValue<Container<T>>()->unknown_fields;
+ } else {
+ return mutable_unknown_fields_slow<T>();
+ }
+ }
+
+ template <typename T>
+ PROTOBUF_ALWAYS_INLINE void Swap(InternalMetadata* other) {
// Semantics here are that we swap only the unknown fields, not the arena
// pointer. We cannot simply swap ptr_ with other->ptr_ because we need to
// maintain our own arena ptr. Also, our ptr_ and other's ptr_ may be in
@@ -107,24 +111,24 @@
// cannot simply swap ptr_ and then restore the arena pointers. We reuse
// UFS's swap implementation instead.
if (have_unknown_fields() || other->have_unknown_fields()) {
- static_cast<Derived*>(this)->DoSwap(other->mutable_unknown_fields());
+ DoSwap<T>(other->mutable_unknown_fields<T>());
}
}
- PROTOBUF_ALWAYS_INLINE void MergeFrom(const Derived& other) {
+ template <typename T>
+ PROTOBUF_ALWAYS_INLINE void MergeFrom(const InternalMetadata& other) {
if (other.have_unknown_fields()) {
- static_cast<Derived*>(this)->DoMergeFrom(other.unknown_fields());
+ DoMergeFrom<T>(other.unknown_fields<T>(nullptr));
}
}
+ template <typename T>
PROTOBUF_ALWAYS_INLINE void Clear() {
if (have_unknown_fields()) {
- static_cast<Derived*>(this)->DoClear();
+ DoClear<T>();
}
}
- PROTOBUF_ALWAYS_INLINE void* raw_arena_ptr() const { return ptr_; }
-
private:
void* ptr_;
@@ -135,8 +139,8 @@
// ptr_ is a Container*.
kTagContainer = 1,
};
- static const intptr_t kPtrTagMask = 1;
- static const intptr_t kPtrValueMask = ~kPtrTagMask;
+ static constexpr intptr_t kPtrTagMask = 1;
+ static constexpr intptr_t kPtrValueMask = ~kPtrTagMask;
// Accessors for pointer tag and pointer value.
PROTOBUF_ALWAYS_INLINE int PtrTag() const {
@@ -150,14 +154,19 @@
}
// If ptr_'s tag is kTagContainer, it points to an instance of this struct.
- struct Container {
- T unknown_fields;
+ struct ContainerBase {
Arena* arena;
};
+ template <typename T>
+ struct Container : public ContainerBase {
+ T unknown_fields;
+ };
+
+ template <typename T>
PROTOBUF_NOINLINE T* mutable_unknown_fields_slow() {
Arena* my_arena = arena();
- Container* container = Arena::Create<Container>(my_arena);
+ Container<T>* container = Arena::Create<Container<T>>(my_arena);
// Two-step assignment works around a bug in clang's static analyzer:
// https://bugs.llvm.org/show_bug.cgi?id=34198.
ptr_ = container;
@@ -166,40 +175,43 @@
container->arena = my_arena;
return &(container->unknown_fields);
}
-};
-// We store unknown fields as a std::string right now, because there is
-// currently no good interface for reading unknown fields into an ArenaString.
-// We may want to revisit this to allow unknown fields to be parsed onto the
-// Arena.
-class InternalMetadataWithArenaLite
- : public InternalMetadataWithArenaBase<std::string,
- InternalMetadataWithArenaLite> {
- public:
- InternalMetadataWithArenaLite() {}
+ // Templated functions.
- explicit InternalMetadataWithArenaLite(Arena* arena)
- : InternalMetadataWithArenaBase<std::string,
- InternalMetadataWithArenaLite>(arena) {}
-
- void DoSwap(std::string* other) { mutable_unknown_fields()->swap(*other); }
-
- void DoMergeFrom(const std::string& other) {
- mutable_unknown_fields()->append(other);
+ template <typename T>
+ void DoClear() {
+ mutable_unknown_fields<T>()->Clear();
}
- void DoClear() { mutable_unknown_fields()->clear(); }
+ template <typename T>
+ void DoMergeFrom(const T& other) {
+ mutable_unknown_fields<T>()->MergeFrom(other);
+ }
- static const std::string& default_instance() {
- // Can't use GetEmptyStringAlreadyInited() here because empty string
- // may not have been initalized yet. This happens when protocol compiler
- // statically determines the user can't access defaults and omits init code
- // from proto constructors. However unknown fields are always part of a
- // proto so it needs to be lazily initailzed. See b/112613846.
- return GetEmptyString();
+ template <typename T>
+ void DoSwap(T* other) {
+ mutable_unknown_fields<T>()->Swap(other);
}
};
+// String Template specializations.
+
+template <>
+inline void InternalMetadata::DoClear<std::string>() {
+ mutable_unknown_fields<std::string>()->clear();
+}
+
+template <>
+inline void InternalMetadata::DoMergeFrom<std::string>(
+ const std::string& other) {
+ mutable_unknown_fields<std::string>()->append(other);
+}
+
+template <>
+inline void InternalMetadata::DoSwap<std::string>(std::string* other) {
+ mutable_unknown_fields<std::string>()->swap(*other);
+}
+
// This helper RAII class is needed to efficiently parse unknown fields. We
// should only call mutable_unknown_fields if there are actual unknown fields.
// The obvious thing to just use a stack string and swap it at the end of
@@ -210,19 +222,20 @@
// guarantees that the string is only swapped after stream is destroyed.
class PROTOBUF_EXPORT LiteUnknownFieldSetter {
public:
- explicit LiteUnknownFieldSetter(InternalMetadataWithArenaLite* metadata)
+ explicit LiteUnknownFieldSetter(InternalMetadata* metadata)
: metadata_(metadata) {
if (metadata->have_unknown_fields()) {
- buffer_.swap(*metadata->mutable_unknown_fields());
+ buffer_.swap(*metadata->mutable_unknown_fields<std::string>());
}
}
~LiteUnknownFieldSetter() {
- if (!buffer_.empty()) metadata_->mutable_unknown_fields()->swap(buffer_);
+ if (!buffer_.empty())
+ metadata_->mutable_unknown_fields<std::string>()->swap(buffer_);
}
std::string* buffer() { return &buffer_; }
private:
- InternalMetadataWithArenaLite* metadata_;
+ InternalMetadata* metadata_;
std::string buffer_;
};
diff --git a/src/google/protobuf/parse_context.cc b/src/google/protobuf/parse_context.cc
index 6cf63b7..ea4ed19 100644
--- a/src/google/protobuf/parse_context.cc
+++ b/src/google/protobuf/parse_context.cc
@@ -474,36 +474,6 @@
return VarintParser<int, false>(object, ptr, ctx);
}
-const char* PackedEnumParser(void* object, const char* ptr, ParseContext* ctx,
- bool (*is_valid)(int),
- InternalMetadataWithArenaLite* metadata,
- int field_num) {
- return ctx->ReadPackedVarint(
- ptr, [object, is_valid, metadata, field_num](uint64 val) {
- if (is_valid(val)) {
- static_cast<RepeatedField<int>*>(object)->Add(val);
- } else {
- WriteVarint(field_num, val, metadata->mutable_unknown_fields());
- }
- });
-}
-
-const char* PackedEnumParserArg(void* object, const char* ptr,
- ParseContext* ctx,
- bool (*is_valid)(const void*, int),
- const void* data,
- InternalMetadataWithArenaLite* metadata,
- int field_num) {
- return ctx->ReadPackedVarint(
- ptr, [object, is_valid, data, metadata, field_num](uint64 val) {
- if (is_valid(data, val)) {
- static_cast<RepeatedField<int>*>(object)->Add(val);
- } else {
- WriteVarint(field_num, val, metadata->mutable_unknown_fields());
- }
- });
-}
-
const char* PackedBoolParser(void* object, const char* ptr, ParseContext* ctx) {
return VarintParser<bool, false>(object, ptr, ctx);
}
@@ -604,12 +574,6 @@
return FieldParser(tag, field_parser, ptr, ctx);
}
-const char* UnknownFieldParse(uint32 tag,
- InternalMetadataWithArenaLite* metadata,
- const char* ptr, ParseContext* ctx) {
- return UnknownFieldParse(tag, metadata->mutable_unknown_fields(), ptr, ctx);
-}
-
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/parse_context.h b/src/google/protobuf/parse_context.h
index 553ed52..c83eed9 100644
--- a/src/google/protobuf/parse_context.h
+++ b/src/google/protobuf/parse_context.h
@@ -79,7 +79,7 @@
//
// Where the '-' represent the bytes which are vertically lined up with the
// bytes of the stream. The proto parser requires its input to be presented
-// similarily with the extra
+// similarly with the extra
// property that each chunk has kSlopBytes past its end that overlaps with the
// first kSlopBytes of the next chunk, or if there is no next chunk at least its
// still valid to read those bytes. Again, pictorially, we now have
@@ -239,6 +239,7 @@
const char* InitFrom(io::ZeroCopyInputStream* zcis);
const char* InitFrom(io::ZeroCopyInputStream* zcis, int limit) {
+ if (limit == -1) return InitFrom(zcis);
overall_limit_ = limit;
auto res = InitFrom(zcis);
limit_ = limit - static_cast<int>(buffer_end_ - res);
@@ -579,12 +580,18 @@
// function composition. We rely on the compiler to inline this.
// Also in debug compiles having local scoped variables tend to generated
// stack frames that scale as O(num fields).
-inline uint64 ReadVarint(const char** p) {
+inline uint64 ReadVarint64(const char** p) {
uint64 tmp;
*p = VarintParse(*p, &tmp);
return tmp;
}
+inline uint32 ReadVarint32(const char** p) {
+ uint32 tmp;
+ *p = VarintParse(*p, &tmp);
+ return tmp;
+}
+
inline int64 ReadVarintZigZag64(const char** p) {
uint64 tmp;
*p = VarintParse(*p, &tmp);
@@ -735,13 +742,39 @@
void* object, const char* ptr, ParseContext* ctx);
PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedEnumParser(
void* object, const char* ptr, ParseContext* ctx);
-PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedEnumParser(
- void* object, const char* ptr, ParseContext* ctx, bool (*is_valid)(int),
- InternalMetadataWithArenaLite* metadata, int field_num);
-PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedEnumParserArg(
- void* object, const char* ptr, ParseContext* ctx,
- bool (*is_valid)(const void*, int), const void* data,
- InternalMetadataWithArenaLite* metadata, int field_num);
+
+template <typename T>
+PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+PROTOBUF_MUST_USE_RESULT const
+ char* PackedEnumParser(void* object, const char* ptr, ParseContext* ctx,
+ bool (*is_valid)(int), InternalMetadata* metadata,
+ int field_num) {
+ return ctx->ReadPackedVarint(
+ ptr, [object, is_valid, metadata, field_num](uint64 val) {
+ if (is_valid(val)) {
+ static_cast<RepeatedField<int>*>(object)->Add(val);
+ } else {
+ WriteVarint(field_num, val, metadata->mutable_unknown_fields<T>());
+ }
+ });
+}
+
+template <typename T>
+PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+PROTOBUF_MUST_USE_RESULT const
+ char* PackedEnumParserArg(void* object, const char* ptr, ParseContext* ctx,
+ bool (*is_valid)(const void*, int),
+ const void* data, InternalMetadata* metadata,
+ int field_num) {
+ return ctx->ReadPackedVarint(
+ ptr, [object, is_valid, data, metadata, field_num](uint64 val) {
+ if (is_valid(data, val)) {
+ static_cast<RepeatedField<int>*>(object)->Add(val);
+ } else {
+ WriteVarint(field_num, val, metadata->mutable_unknown_fields<T>());
+ }
+ });
+}
PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedBoolParser(
void* object, const char* ptr, ParseContext* ctx);
@@ -766,9 +799,6 @@
// UnknownFieldSet* to make the generated code isomorphic between full and lite.
PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* UnknownFieldParse(
uint32 tag, std::string* unknown, const char* ptr, ParseContext* ctx);
-PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* UnknownFieldParse(
- uint32 tag, InternalMetadataWithArenaLite* metadata, const char* ptr,
- ParseContext* ctx);
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/port_def.inc b/src/google/protobuf/port_def.inc
index a497f77..d0c2c8f 100644
--- a/src/google/protobuf/port_def.inc
+++ b/src/google/protobuf/port_def.inc
@@ -136,6 +136,9 @@
#ifdef PROTOBUF_UNUSED
#error PROTOBUF_UNUSED was previously defined
#endif
+#ifdef PROTOBUF_FINAL
+#error PROTOBUF_FINAL was previously defined
+#endif
#define PROTOBUF_NAMESPACE "google::protobuf"
@@ -297,17 +300,26 @@
// Shared google3/opensource definitions. //////////////////////////////////////
-#define PROTOBUF_VERSION 3011000
-#define PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC 3011000
-#define PROTOBUF_MIN_PROTOC_VERSION 3011000
+#define PROTOBUF_VERSION 3012000
+#define PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC 3012000
+#define PROTOBUF_MIN_PROTOC_VERSION 3012000
#define PROTOBUF_VERSION_SUFFIX ""
// The minimum library version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3011000
+#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3012000
#if defined(GOOGLE_PROTOBUF_NO_RTTI) && GOOGLE_PROTOBUF_NO_RTTI
#define PROTOBUF_RTTI 0
+#elif defined(__has_feature)
+// https://clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
+#define PROTOBUF_RTTI __has_feature(cxx_rtti)
+#elif !defined(__cxx_rtti)
+// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros#C.2B.2B98
+#define PROTOBUF_RTTI 0
+#elif defined(__GNUC__) && !defined(__GXX_RTTI)
+#https: // gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
+#define PROTOBUF_RTTI 0
#else
#define PROTOBUF_RTTI 1
#endif
@@ -329,7 +341,10 @@
_Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
__builtin_offsetof(TYPE, FIELD) \
_Pragma("clang diagnostic pop")
-#else
+#elif defined(__GNUC__) && \
+ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
+#define PROTOBUF_FIELD_OFFSET(TYPE, FIELD) __builtin_offsetof(TYPE, FIELD)
+#else // defined(__clang__)
// Note that we calculate relative to the pointer value 16 here since if we
// just use zero, GCC complains about dereferencing a NULL pointer. We
// choose 16 rather than some other number just in case the compiler would
@@ -343,28 +358,20 @@
#if defined(PROTOBUF_USE_DLLS)
#if defined(_MSC_VER)
#ifdef LIBPROTOBUF_EXPORTS
- #define PROTOBUF_EXPORT __declspec(dllexport)
- #define PROTOBUF_EXPORT_TEMPLATE_DECLARE
- #define PROTOBUF_EXPORT_TEMPLATE_DEFINE __declspec(dllexport)
+ #define PROTOBUF_EXPORT __declspec(dllexport)
#else
- #define PROTOBUF_EXPORT __declspec(dllimport)
- #define PROTOBUF_EXPORT_TEMPLATE_DECLARE
- #define PROTOBUF_EXPORT_TEMPLATE_DEFINE __declspec(dllimport)
+ #define PROTOBUF_EXPORT __declspec(dllimport)
#endif
#ifdef LIBPROTOC_EXPORTS
- #define PROTOC_EXPORT __declspec(dllexport)
+ #define PROTOC_EXPORT __declspec(dllexport)
#else
- #define PROTOC_EXPORT __declspec(dllimport)
+ #define PROTOC_EXPORT __declspec(dllimport)
#endif
#else // defined(_MSC_VER)
#ifdef LIBPROTOBUF_EXPORTS
#define PROTOBUF_EXPORT __attribute__((visibility("default")))
- #define PROTOBUF_EXPORT_TEMPLATE_DECLARE __attribute__((visibility("default")))
- #define PROTOBUF_EXPORT_TEMPLATE_DEFINE
#else
#define PROTOBUF_EXPORT
- #define PROTOBUF_EXPORT_TEMPLATE_DECLARE
- #define PROTOBUF_EXPORT_TEMPLATE_DEFINE
#endif
#ifdef LIBPROTOC_EXPORTS
#define PROTOC_EXPORT __attribute__((visibility("default")))
@@ -375,30 +382,229 @@
#else // defined(PROTOBUF_USE_DLLS)
#define PROTOBUF_EXPORT
#define PROTOC_EXPORT
- #define PROTOBUF_EXPORT_TEMPLATE_DECLARE
- #define PROTOBUF_EXPORT_TEMPLATE_DEFINE
#endif
+
+// This portion provides macros for using FOO_EXPORT macros with explicit
+// template instantiation declarations and definitions.
+// Generally, the FOO_EXPORT macros are used at declarations,
+// and GCC requires them to be used at explicit instantiation declarations,
+// but MSVC requires __declspec(dllexport) to be used at the explicit
+// instantiation definitions instead.
+
+// Usage
+//
+// In a header file, write:
+//
+// extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(FOO_EXPORT) foo<bar>;
+//
+// In a source file, write:
+//
+// template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(FOO_EXPORT) foo<bar>;
+//
+// Where FOO_EXPORT is either PROTOBUF_EXPORT or PROTOC_EXPORT
+
+// Implementation notes
+//
+// The implementation of these macros uses some subtle macro semantics to
+// detect what the provided FOO_EXPORT value was defined as and then
+// to dispatch to appropriate macro definitions. Unfortunately,
+// MSVC's C preprocessor is rather non-compliant and requires special
+// care to make it work.
+//
+// Issue 1.
+//
+// #define F(x)
+// F()
+//
+// MSVC emits warning C4003 ("not enough actual parameters for macro
+// 'F'), even though it's a valid macro invocation. This affects the
+// macros below that take just an "export" parameter, because export
+// may be empty.
+//
+// As a workaround, we can add a dummy parameter and arguments:
+//
+// #define F(x,_)
+// F(,)
+//
+// Issue 2.
+//
+// #define F(x) G##x
+// #define Gj() ok
+// F(j())
+//
+// The correct replacement for "F(j())" is "ok", but MSVC replaces it
+// with "Gj()". As a workaround, we can pass the result to an
+// identity macro to force MSVC to look for replacements again. (This
+// is why PROTOBUF_EXPORT_TEMPLATE_STYLE_3 exists.)
+
+#define PROTOBUF_EXPORT_TEMPLATE_DECLARE(export) \
+ PROTOBUF_EXPORT_TEMPLATE_INVOKE( \
+ DECLARE, PROTOBUF_EXPORT_TEMPLATE_STYLE(export, ), export)
+#define PROTOBUF_EXPORT_TEMPLATE_DEFINE(export) \
+ PROTOBUF_EXPORT_TEMPLATE_INVOKE( \
+ DEFINE, PROTOBUF_EXPORT_TEMPLATE_STYLE(export, ), export)
+
+// INVOKE is an internal helper macro to perform parameter replacements
+// and token pasting to chain invoke another macro. E.g.,
+// PROTOBUF_EXPORT_TEMPLATE_INVOKE(DECLARE, DEFAULT, FOO_EXPORT)
+// will export to call
+// PROTOBUF_EXPORT_TEMPLATE_DECLARE_DEFAULT(FOO_EXPORT, )
+// (but with FOO_EXPORT expanded too).
+#define PROTOBUF_EXPORT_TEMPLATE_INVOKE(which, style, export) \
+ PROTOBUF_EXPORT_TEMPLATE_INVOKE_2(which, style, export)
+#define PROTOBUF_EXPORT_TEMPLATE_INVOKE_2(which, style, export) \
+ PROTOBUF_EXPORT_TEMPLATE_##which##_##style(export, )
+
+// Default style is to apply the FOO_EXPORT macro at declaration sites.
+#define PROTOBUF_EXPORT_TEMPLATE_DECLARE_DEFAULT(export, _) export
+#define PROTOBUF_EXPORT_TEMPLATE_DEFINE_DEFAULT(export, _)
+
+// The "MSVC hack" style is used when FOO_EXPORT is defined
+// as __declspec(dllexport), which MSVC requires to be used at
+// definition sites instead.
+#define PROTOBUF_EXPORT_TEMPLATE_DECLARE_MSVC_HACK(export, _)
+#define PROTOBUF_EXPORT_TEMPLATE_DEFINE_MSVC_HACK(export, _) export
+
+// PROTOBUF_EXPORT_TEMPLATE_STYLE is an internal helper macro that identifies
+// which export style needs to be used for the provided FOO_EXPORT macro
+// definition. "", "__attribute__(...)", and "__declspec(dllimport)" are
+// mapped to "DEFAULT"; while "__declspec(dllexport)" is mapped to "MSVC_HACK".
+//
+// It's implemented with token pasting to transform the __attribute__ and
+// __declspec annotations into macro invocations. E.g., if FOO_EXPORT is
+// defined as "__declspec(dllimport)", it undergoes the following sequence of
+// macro substitutions:
+// PROTOBUF_EXPORT_TEMPLATE_STYLE(FOO_EXPORT, )
+// PROTOBUF_EXPORT_TEMPLATE_STYLE_2(__declspec(dllimport), )
+// PROTOBUF_EXPORT_TEMPLATE_STYLE_3(
+// PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH__declspec(dllimport))
+// PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH__declspec(dllimport)
+// PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_DECLSPEC_dllimport
+// DEFAULT
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE(export, _) \
+ PROTOBUF_EXPORT_TEMPLATE_STYLE_2(export, )
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE_2(export, _) \
+ PROTOBUF_EXPORT_TEMPLATE_STYLE_3( \
+ PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_foj3FJo5StF0OvIzl7oMxA##export)
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE_3(style) style
+
+// Internal helper macros for PROTOBUF_EXPORT_TEMPLATE_STYLE.
+//
+// XXX: C++ reserves all identifiers containing "__" for the implementation,
+// but "__attribute__" and "__declspec" already contain "__" and the token-paste
+// operator can only add characters; not remove them. To minimize the risk of
+// conflict with implementations, we include "foj3FJo5StF0OvIzl7oMxA" (a random
+// 128-bit string, encoded in Base64) in the macro name.
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_foj3FJo5StF0OvIzl7oMxA DEFAULT
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_foj3FJo5StF0OvIzl7oMxA__attribute__(...) \
+ DEFAULT
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_foj3FJo5StF0OvIzl7oMxA__declspec(arg) \
+ PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_DECLSPEC_##arg
+
+// Internal helper macros for PROTOBUF_EXPORT_TEMPLATE_STYLE.
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_DECLSPEC_dllexport MSVC_HACK
+#define PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_DECLSPEC_dllimport DEFAULT
+
+// Sanity checks.
+//
+// PROTOBUF_EXPORT_TEMPLATE_TEST uses the same macro invocation pattern as
+// PROTOBUF_EXPORT_TEMPLATE_DECLARE and PROTOBUF_EXPORT_TEMPLATE_DEFINE do to
+// check that they're working correctly. When they're working correctly, the
+// sequence of macro replacements should go something like:
+//
+// PROTOBUF_EXPORT_TEMPLATE_TEST(DEFAULT, __declspec(dllimport));
+//
+// static_assert(PROTOBUF_EXPORT_TEMPLATE_INVOKE(TEST_DEFAULT,
+// PROTOBUF_EXPORT_TEMPLATE_STYLE(__declspec(dllimport), ),
+// __declspec(dllimport)), "__declspec(dllimport)");
+//
+// static_assert(PROTOBUF_EXPORT_TEMPLATE_INVOKE(TEST_DEFAULT,
+// DEFAULT, __declspec(dllimport)), "__declspec(dllimport)");
+//
+// static_assert(PROTOBUF_EXPORT_TEMPLATE_TEST_DEFAULT_DEFAULT(
+// __declspec(dllimport)), "__declspec(dllimport)");
+//
+// static_assert(true, "__declspec(dllimport)");
+//
+// When they're not working correctly, a syntax error should occur instead.
+#define PROTOBUF_EXPORT_TEMPLATE_TEST(want, export) \
+ static_assert(PROTOBUF_EXPORT_TEMPLATE_INVOKE( \
+ TEST_##want, PROTOBUF_EXPORT_TEMPLATE_STYLE(export, ), \
+ export), #export)
+#define PROTOBUF_EXPORT_TEMPLATE_TEST_DEFAULT_DEFAULT(...) true
+#define PROTOBUF_EXPORT_TEMPLATE_TEST_MSVC_HACK_MSVC_HACK(...) true
+
+PROTOBUF_EXPORT_TEMPLATE_TEST(DEFAULT, );
+PROTOBUF_EXPORT_TEMPLATE_TEST(DEFAULT, __attribute__((visibility("default"))));
+PROTOBUF_EXPORT_TEMPLATE_TEST(MSVC_HACK, __declspec(dllexport));
+PROTOBUF_EXPORT_TEMPLATE_TEST(DEFAULT, __declspec(dllimport));
+
+#undef PROTOBUF_EXPORT_TEMPLATE_TEST
+#undef PROTOBUF_EXPORT_TEMPLATE_TEST_DEFAULT_DEFAULT
+#undef PROTOBUF_EXPORT_TEMPLATE_TEST_MSVC_HACK_MSVC_HACK
+
// Windows declares several inconvenient macro names. We #undef them and then
// restore them in port_undef.inc.
#ifdef _MSC_VER
+#pragma push_macro("CREATE_NEW")
+#undef CREATE_NEW
+#pragma push_macro("DOUBLE_CLICK")
+#undef DOUBLE_CLICK
+#pragma push_macro("ERROR")
+#undef ERROR
+#pragma push_macro("ERROR_BUSY")
+#undef ERROR_BUSY
+#pragma push_macro("ERROR_NOT_FOUND")
+#undef ERROR_NOT_FOUND
#pragma push_macro("GetMessage")
#undef GetMessage
#pragma push_macro("IGNORE")
#undef IGNORE
#pragma push_macro("IN")
#undef IN
+#pragma push_macro("INPUT_KEYBOARD")
+#undef INPUT_KEYBOARD
+#pragma push_macro("NO_ERROR")
+#undef NO_ERROR
+#pragma push_macro("OUT")
+#undef OUT
+#pragma push_macro("OPTIONAL")
+#undef OPTIONAL
#pragma push_macro("min")
#undef min
#pragma push_macro("max")
#undef max
+#pragma push_macro("REASON_UNKNOWN")
+#undef REASON_UNKNOWN
+#pragma push_macro("SERVICE_DISABLED")
+#undef SERVICE_DISABLED
+#pragma push_macro("SEVERITY_ERROR")
+#undef SEVERITY_ERROR
+#pragma push_macro("STRICT")
+#undef STRICT
#endif // _MSC_VER
+#if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
+// Don't let the YES/NO Objective-C Macros interfere with proto identifiers with
+// the same name.
+#pragma push_macro("YES")
+#undef YES
+#pragma push_macro("NO")
+#undef NO
+#endif // defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
+
#if defined(__clang__)
#pragma clang diagnostic push
// TODO(gerbens) ideally we cleanup the code. But a cursory try shows many
// violations. So let's ignore for now.
#pragma clang diagnostic ignored "-Wshorten-64-to-32"
+#elif defined(__GNUC__)
+// GCC does not allow disabling diagnostics within an expression:
+// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60875, so we disable this one
+// globally even though it's only used for PROTOBUF_FIELD_OFFSET.
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif
// PROTOBUF_ASSUME(pred) tells the compiler that it can assume pred is true. To
@@ -416,3 +622,41 @@
#else
#define PROTOBUF_ASSUME(pred) GOOGLE_DCHECK(pred)
#endif
+
+// Specify memory alignment for structs, classes, etc.
+// Use like:
+// class PROTOBUF_ALIGNAS(16) MyClass { ... }
+// PROTOBUF_ALIGNAS(16) int array[4];
+//
+// In most places you can use the C++11 keyword "alignas", which is preferred.
+//
+// But compilers have trouble mixing __attribute__((...)) syntax with
+// alignas(...) syntax.
+//
+// Doesn't work in clang or gcc:
+// struct alignas(16) __attribute__((packed)) S { char c; };
+// Works in clang but not gcc:
+// struct __attribute__((packed)) alignas(16) S2 { char c; };
+// Works in clang and gcc:
+// struct alignas(16) S3 { char c; } __attribute__((packed));
+//
+// There are also some attributes that must be specified *before* a class
+// definition: visibility (used for exporting functions/classes) is one of
+// these attributes. This means that it is not possible to use alignas() with a
+// class that is marked as exported.
+#if defined(_MSC_VER)
+#define PROTOBUF_ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
+#elif defined(__GNUC__)
+#define PROTOBUF_ALIGNAS(byte_alignment) \
+ __attribute__((aligned(byte_alignment)))
+#else
+#define PROTOBUF_ALIGNAS(byte_alignment) alignas(byte_alignment)
+#endif
+
+#define PROTOBUF_FINAL final
+
+#if defined(_MSC_VER)
+#define PROTOBUF_THREAD_LOCAL __declspec(thread)
+#else
+#define PROTOBUF_THREAD_LOCAL __thread
+#endif
diff --git a/src/google/protobuf/port_undef.inc b/src/google/protobuf/port_undef.inc
index dc61ba1..e93e669 100644
--- a/src/google/protobuf/port_undef.inc
+++ b/src/google/protobuf/port_undef.inc
@@ -68,16 +68,52 @@
#undef PROTOBUF_ASSUME
#undef PROTOBUF_EXPORT_TEMPLATE_DECLARE
#undef PROTOBUF_EXPORT_TEMPLATE_DEFINE
+#undef PROTOBUF_ALIGNAS
+#undef PROTOBUF_EXPORT_TEMPLATE_INVOKE_2
+#undef PROTOBUF_EXPORT_TEMPLATE_DECLARE_DEFAULT
+#undef PROTOBUF_EXPORT_TEMPLATE_DEFINE_DEFAULT
+#undef PROTOBUF_EXPORT_TEMPLATE_DECLARE_MSVC_HACK
+#undef PROTOBUF_EXPORT_TEMPLATE_DEFINE_MSVC_HACK
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE_2
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE_3
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_foj3FJo5StF0OvIzl7oMxA
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_foj3FJo5StF0OvIzl7oMxA__attribute__
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_foj3FJo5StF0OvIzl7oMxA__declspec
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_DECLSPEC_dllexport
+#undef PROTOBUF_EXPORT_TEMPLATE_STYLE_MATCH_DECLSPEC_dllimport
+#undef PROTOBUF_FINAL
+#undef PROTOBUF_THREAD_LOCAL
// Restore macro that may have been #undef'd in port_def.inc.
#ifdef _MSC_VER
+#pragma pop_macro("CREATE_NEW")
+#pragma pop_macro("DOUBLE_CLICK")
+#pragma pop_macro("ERROR")
+#pragma pop_macro("ERROR_BUSY")
+#pragma pop_macro("ERROR_NOT_FOUND")
#pragma pop_macro("GetMessage")
#pragma pop_macro("IGNORE")
#pragma pop_macro("IN")
+#pragma pop_macro("INPUT_KEYBOARD")
+#pragma pop_macro("OUT")
+#pragma pop_macro("OPTIONAL")
#pragma pop_macro("min")
#pragma pop_macro("max")
+#pragma pop_macro("NO_ERROR")
+#pragma pop_macro("REASON_UNKNOWN")
+#pragma pop_macro("SERVICE_DISABLED")
+#pragma pop_macro("SEVERITY_ERROR")
+#pragma pop_macro("STRICT")
#endif
+#if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
+#pragma pop_macro("YES")
+#pragma pop_macro("NO")
+#endif // defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
+
#if defined(__clang__)
#pragma clang diagnostic pop
+#elif defined(__GNUC__)
+#pragma GCC diagnostic pop
#endif
diff --git a/src/google/protobuf/proto3_arena_unittest.cc b/src/google/protobuf/proto3_arena_unittest.cc
index 75da9eb..0d81dd1 100644
--- a/src/google/protobuf/proto3_arena_unittest.cc
+++ b/src/google/protobuf/proto3_arena_unittest.cc
@@ -35,9 +35,12 @@
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_proto3_arena.pb.h>
+#include <google/protobuf/unittest_proto3_optional.pb.h>
#include <google/protobuf/arena.h>
+#include <google/protobuf/text_format.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/strutil.h>
using proto3_arena_unittest::TestAllTypes;
@@ -194,6 +197,290 @@
EXPECT_EQ(0, message->optional_nested_message().bb());
}
+TEST(Proto3OptionalTest, OptionalFields) {
+ protobuf_unittest::TestProto3Optional msg;
+ EXPECT_FALSE(msg.has_optional_int32());
+ msg.set_optional_int32(0);
+ EXPECT_TRUE(msg.has_optional_int32());
+
+ string serialized;
+ msg.SerializeToString(&serialized);
+ EXPECT_GT(serialized.size(), 0);
+
+ msg.clear_optional_int32();
+ EXPECT_FALSE(msg.has_optional_int32());
+ msg.SerializeToString(&serialized);
+ EXPECT_EQ(serialized.size(), 0);
+}
+
+TEST(Proto3OptionalTest, OptionalFieldDescriptor) {
+ const Descriptor* d = protobuf_unittest::TestProto3Optional::descriptor();
+
+ for (int i = 0; i < d->field_count(); i++) {
+ const FieldDescriptor* f = d->field(i);
+ if (HasPrefixString(f->name(), "singular")) {
+ EXPECT_FALSE(f->has_optional_keyword()) << f->full_name();
+ EXPECT_FALSE(f->has_presence()) << f->full_name();
+ EXPECT_FALSE(f->containing_oneof()) << f->full_name();
+ } else {
+ EXPECT_TRUE(f->has_optional_keyword()) << f->full_name();
+ EXPECT_TRUE(f->has_presence()) << f->full_name();
+ EXPECT_TRUE(f->containing_oneof()) << f->full_name();
+ }
+ }
+}
+
+TEST(Proto3OptionalTest, OptionalField) {
+ protobuf_unittest::TestProto3Optional msg;
+ EXPECT_FALSE(msg.has_optional_int32());
+ msg.set_optional_int32(0);
+ EXPECT_TRUE(msg.has_optional_int32());
+
+ string serialized;
+ msg.SerializeToString(&serialized);
+ EXPECT_GT(serialized.size(), 0);
+
+ msg.clear_optional_int32();
+ EXPECT_FALSE(msg.has_optional_int32());
+ msg.SerializeToString(&serialized);
+ EXPECT_EQ(serialized.size(), 0);
+}
+
+TEST(Proto3OptionalTest, OptionalFieldReflection) {
+ // Tests that oneof reflection works on synthetic oneofs.
+ //
+ // We test this more deeply elsewhere by parsing/serializing TextFormat (which
+ // doesn't treat synthetic oneofs specially, so reflects over them normally).
+ protobuf_unittest::TestProto3Optional msg;
+ const google::protobuf::Descriptor* d = msg.GetDescriptor();
+ const google::protobuf::Reflection* r = msg.GetReflection();
+ const google::protobuf::FieldDescriptor* f = d->FindFieldByName("optional_int32");
+ const google::protobuf::OneofDescriptor* o = d->FindOneofByName("_optional_int32");
+ GOOGLE_CHECK(f);
+ GOOGLE_CHECK(o);
+ EXPECT_TRUE(o->is_synthetic());
+
+ EXPECT_FALSE(r->HasField(msg, f));
+ EXPECT_FALSE(r->HasOneof(msg, o));
+ EXPECT_TRUE(r->GetOneofFieldDescriptor(msg, o) == nullptr);
+
+ r->SetInt32(&msg, f, 123);
+ EXPECT_EQ(123, msg.optional_int32());
+ EXPECT_EQ(123, r->GetInt32(msg, f));
+ EXPECT_TRUE(r->HasField(msg, f));
+ EXPECT_TRUE(r->HasOneof(msg, o));
+ EXPECT_EQ(f, r->GetOneofFieldDescriptor(msg, o));
+
+ std::vector<const FieldDescriptor*> fields;
+ r->ListFields(msg, &fields);
+ EXPECT_EQ(1, fields.size());
+ EXPECT_EQ(f, fields[0]);
+
+ r->ClearOneof(&msg, o);
+ EXPECT_FALSE(r->HasField(msg, f));
+ EXPECT_FALSE(r->HasOneof(msg, o));
+ EXPECT_TRUE(r->GetOneofFieldDescriptor(msg, o) == nullptr);
+
+ msg.set_optional_int32(123);
+ EXPECT_EQ(123, r->GetInt32(msg, f));
+ EXPECT_TRUE(r->HasField(msg, f));
+ EXPECT_TRUE(r->HasOneof(msg, o));
+ EXPECT_EQ(f, r->GetOneofFieldDescriptor(msg, o));
+
+ r->ClearOneof(&msg, o);
+ EXPECT_FALSE(r->HasField(msg, f));
+ EXPECT_FALSE(r->HasOneof(msg, o));
+ EXPECT_TRUE(r->GetOneofFieldDescriptor(msg, o) == nullptr);
+}
+
+void SetAllFieldsZero(protobuf_unittest::TestProto3Optional* msg) {
+ msg->set_optional_int32(0);
+ msg->set_optional_int64(0);
+ msg->set_optional_uint32(0);
+ msg->set_optional_uint64(0);
+ msg->set_optional_sint32(0);
+ msg->set_optional_sint64(0);
+ msg->set_optional_fixed32(0);
+ msg->set_optional_fixed64(0);
+ msg->set_optional_sfixed32(0);
+ msg->set_optional_sfixed64(0);
+ msg->set_optional_float(0);
+ msg->set_optional_double(0);
+ msg->set_optional_bool(false);
+ msg->set_optional_string("");
+ msg->set_optional_bytes("");
+ msg->mutable_optional_nested_message();
+ msg->mutable_lazy_nested_message();
+ msg->set_optional_nested_enum(
+ protobuf_unittest::TestProto3Optional::UNSPECIFIED);
+}
+
+void SetAllFieldsNonZero(protobuf_unittest::TestProto3Optional* msg) {
+ msg->set_optional_int32(101);
+ msg->set_optional_int64(102);
+ msg->set_optional_uint32(103);
+ msg->set_optional_uint64(104);
+ msg->set_optional_sint32(105);
+ msg->set_optional_sint64(106);
+ msg->set_optional_fixed32(107);
+ msg->set_optional_fixed64(108);
+ msg->set_optional_sfixed32(109);
+ msg->set_optional_sfixed64(110);
+ msg->set_optional_float(111);
+ msg->set_optional_double(112);
+ msg->set_optional_bool(true);
+ msg->set_optional_string("abc");
+ msg->set_optional_bytes("def");
+ msg->mutable_optional_nested_message();
+ msg->mutable_lazy_nested_message();
+ msg->set_optional_nested_enum(protobuf_unittest::TestProto3Optional::BAZ);
+}
+
+void TestAllFieldsZero(const protobuf_unittest::TestProto3Optional& msg) {
+ EXPECT_EQ(0, msg.optional_int32());
+ EXPECT_EQ(0, msg.optional_int64());
+ EXPECT_EQ(0, msg.optional_uint32());
+ EXPECT_EQ(0, msg.optional_uint64());
+ EXPECT_EQ(0, msg.optional_sint32());
+ EXPECT_EQ(0, msg.optional_sint64());
+ EXPECT_EQ(0, msg.optional_fixed32());
+ EXPECT_EQ(0, msg.optional_fixed64());
+ EXPECT_EQ(0, msg.optional_sfixed32());
+ EXPECT_EQ(0, msg.optional_sfixed64());
+ EXPECT_EQ(0, msg.optional_float());
+ EXPECT_EQ(0, msg.optional_double());
+ EXPECT_EQ(0, msg.optional_bool());
+ EXPECT_EQ("", msg.optional_string());
+ EXPECT_EQ("", msg.optional_bytes());
+ EXPECT_EQ(protobuf_unittest::TestProto3Optional::UNSPECIFIED,
+ msg.optional_nested_enum());
+
+ const Reflection* r = msg.GetReflection();
+ const Descriptor* d = msg.GetDescriptor();
+ EXPECT_EQ("", r->GetString(msg, d->FindFieldByName("optional_string")));
+}
+
+void TestAllFieldsNonZero(const protobuf_unittest::TestProto3Optional& msg) {
+ EXPECT_EQ(101, msg.optional_int32());
+ EXPECT_EQ(102, msg.optional_int64());
+ EXPECT_EQ(103, msg.optional_uint32());
+ EXPECT_EQ(104, msg.optional_uint64());
+ EXPECT_EQ(105, msg.optional_sint32());
+ EXPECT_EQ(106, msg.optional_sint64());
+ EXPECT_EQ(107, msg.optional_fixed32());
+ EXPECT_EQ(108, msg.optional_fixed64());
+ EXPECT_EQ(109, msg.optional_sfixed32());
+ EXPECT_EQ(110, msg.optional_sfixed64());
+ EXPECT_EQ(111, msg.optional_float());
+ EXPECT_EQ(112, msg.optional_double());
+ EXPECT_EQ(true, msg.optional_bool());
+ EXPECT_EQ("abc", msg.optional_string());
+ EXPECT_EQ("def", msg.optional_bytes());
+ EXPECT_EQ(protobuf_unittest::TestProto3Optional::BAZ,
+ msg.optional_nested_enum());
+}
+
+void TestAllFieldsSet(const protobuf_unittest::TestProto3Optional& msg,
+ bool set) {
+ EXPECT_EQ(set, msg.has_optional_int32());
+ EXPECT_EQ(set, msg.has_optional_int64());
+ EXPECT_EQ(set, msg.has_optional_uint32());
+ EXPECT_EQ(set, msg.has_optional_uint64());
+ EXPECT_EQ(set, msg.has_optional_sint32());
+ EXPECT_EQ(set, msg.has_optional_sint64());
+ EXPECT_EQ(set, msg.has_optional_fixed32());
+ EXPECT_EQ(set, msg.has_optional_fixed64());
+ EXPECT_EQ(set, msg.has_optional_sfixed32());
+ EXPECT_EQ(set, msg.has_optional_sfixed64());
+ EXPECT_EQ(set, msg.has_optional_float());
+ EXPECT_EQ(set, msg.has_optional_double());
+ EXPECT_EQ(set, msg.has_optional_bool());
+ EXPECT_EQ(set, msg.has_optional_string());
+ EXPECT_EQ(set, msg.has_optional_bytes());
+ EXPECT_EQ(set, msg.has_optional_nested_message());
+ EXPECT_EQ(set, msg.has_lazy_nested_message());
+ EXPECT_EQ(set, msg.has_optional_nested_enum());
+}
+
+TEST(Proto3OptionalTest, BinaryRoundTrip) {
+ protobuf_unittest::TestProto3Optional msg;
+ TestAllFieldsSet(msg, false);
+ SetAllFieldsZero(&msg);
+ TestAllFieldsZero(msg);
+ TestAllFieldsSet(msg, true);
+
+ protobuf_unittest::TestProto3Optional msg2;
+ std::string serialized;
+ msg.SerializeToString(&serialized);
+ EXPECT_TRUE(msg2.ParseFromString(serialized));
+ TestAllFieldsZero(msg2);
+ TestAllFieldsSet(msg2, true);
+}
+
+TEST(Proto3OptionalTest, TextFormatRoundTripZeros) {
+ protobuf_unittest::TestProto3Optional msg;
+ SetAllFieldsZero(&msg);
+
+ protobuf_unittest::TestProto3Optional msg2;
+ std::string text;
+ EXPECT_TRUE(TextFormat::PrintToString(msg, &text));
+ EXPECT_TRUE(TextFormat::ParseFromString(text, &msg2));
+ TestAllFieldsSet(msg2, true);
+ TestAllFieldsZero(msg2);
+}
+
+TEST(Proto3OptionalTest, TextFormatRoundTripNonZeros) {
+ protobuf_unittest::TestProto3Optional msg;
+ SetAllFieldsNonZero(&msg);
+
+ protobuf_unittest::TestProto3Optional msg2;
+ std::string text;
+ EXPECT_TRUE(TextFormat::PrintToString(msg, &text));
+ EXPECT_TRUE(TextFormat::ParseFromString(text, &msg2));
+ TestAllFieldsSet(msg2, true);
+ TestAllFieldsNonZero(msg2);
+}
+
+TEST(Proto3OptionalTest, SwapRoundTripZero) {
+ protobuf_unittest::TestProto3Optional msg;
+ SetAllFieldsZero(&msg);
+ TestAllFieldsSet(msg, true);
+
+ protobuf_unittest::TestProto3Optional msg2;
+ msg.Swap(&msg2);
+ TestAllFieldsSet(msg2, true);
+ TestAllFieldsZero(msg2);
+}
+
+TEST(Proto3OptionalTest, SwapRoundTripNonZero) {
+ protobuf_unittest::TestProto3Optional msg;
+ SetAllFieldsNonZero(&msg);
+ TestAllFieldsSet(msg, true);
+
+ protobuf_unittest::TestProto3Optional msg2;
+ msg.Swap(&msg2);
+ TestAllFieldsSet(msg2, true);
+ TestAllFieldsNonZero(msg2);
+}
+
+TEST(Proto3OptionalTest, ReflectiveSwapRoundTrip) {
+ protobuf_unittest::TestProto3Optional msg;
+ SetAllFieldsZero(&msg);
+ TestAllFieldsSet(msg, true);
+
+ protobuf_unittest::TestProto3Optional msg2;
+ msg2.GetReflection()->Swap(&msg, &msg2);
+ TestAllFieldsSet(msg2, true);
+ TestAllFieldsZero(msg2);
+}
+
+TEST(Proto3OptionalTest, PlainFields) {
+ const Descriptor* d = TestAllTypes::descriptor();
+
+ EXPECT_FALSE(d->FindFieldByName("optional_int32")->has_presence());
+ EXPECT_TRUE(d->FindFieldByName("oneof_nested_message")->has_presence());
+}
+
} // namespace
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h
index 6b1e5f2..af8eb00 100644
--- a/src/google/protobuf/reflection.h
+++ b/src/google/protobuf/reflection.h
@@ -471,7 +471,7 @@
// RepeatedFieldAccessor type, etc.
template <typename T>
struct PrimitiveTraits {
- static const bool is_primitive = false;
+ static constexpr bool is_primitive = false;
};
#define DEFINE_PRIMITIVE(TYPE, type) \
template <> \
@@ -497,7 +497,8 @@
typedef T AccessorValueType;
typedef T IteratorValueType;
typedef T* IteratorPointerType;
- static const FieldDescriptor::CppType cpp_type = PrimitiveTraits<T>::cpp_type;
+ static constexpr FieldDescriptor::CppType cpp_type =
+ PrimitiveTraits<T>::cpp_type;
static const Descriptor* GetMessageFieldDescriptor() { return NULL; }
};
@@ -510,7 +511,7 @@
typedef int32 AccessorValueType;
typedef T IteratorValueType;
typedef int32* IteratorPointerType;
- static const FieldDescriptor::CppType cpp_type =
+ static constexpr FieldDescriptor::CppType cpp_type =
FieldDescriptor::CPPTYPE_ENUM;
static const Descriptor* GetMessageFieldDescriptor() { return NULL; }
};
@@ -523,7 +524,7 @@
typedef std::string AccessorValueType;
typedef const std::string IteratorValueType;
typedef const std::string* IteratorPointerType;
- static const FieldDescriptor::CppType cpp_type =
+ static constexpr FieldDescriptor::CppType cpp_type =
FieldDescriptor::CPPTYPE_STRING;
static const Descriptor* GetMessageFieldDescriptor() { return NULL; }
};
@@ -547,7 +548,7 @@
typedef Message AccessorValueType;
typedef const T& IteratorValueType;
typedef const T* IteratorPointerType;
- static const FieldDescriptor::CppType cpp_type =
+ static constexpr FieldDescriptor::CppType cpp_type =
FieldDescriptor::CPPTYPE_MESSAGE;
static const Descriptor* GetMessageFieldDescriptor() {
return MessageDescriptorGetter<T>::get();
diff --git a/src/google/protobuf/reflection_internal.h b/src/google/protobuf/reflection_internal.h
index 40c070f..3ccf4a0 100644
--- a/src/google/protobuf/reflection_internal.h
+++ b/src/google/protobuf/reflection_internal.h
@@ -122,7 +122,7 @@
return reinterpret_cast<RepeatedFieldType*>(data);
}
- // Convert an object recevied by this accessor to an object to be stored in
+ // Convert an object received by this accessor to an object to be stored in
// the underlying RepeatedField.
virtual T ConvertToT(const Value* value) const = 0;
diff --git a/src/google/protobuf/reflection_ops.cc b/src/google/protobuf/reflection_ops.cc
index 077956a..518da75 100644
--- a/src/google/protobuf/reflection_ops.cc
+++ b/src/google/protobuf/reflection_ops.cc
@@ -125,8 +125,16 @@
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_MESSAGE:
- to_reflection->AddMessage(to, field)->MergeFrom(
- from_reflection->GetRepeatedMessage(from, field, j));
+ const Message& from_child =
+ from_reflection->GetRepeatedMessage(from, field, j);
+ if (from_reflection == to_reflection) {
+ to_reflection
+ ->AddMessage(to, field,
+ from_child.GetReflection()->GetMessageFactory())
+ ->MergeFrom(from_child);
+ } else {
+ to_reflection->AddMessage(to, field)->MergeFrom(from_child);
+ }
break;
}
}
@@ -150,8 +158,15 @@
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_MESSAGE:
- to_reflection->MutableMessage(to, field)->MergeFrom(
- from_reflection->GetMessage(from, field));
+ const Message& from_child = from_reflection->GetMessage(from, field);
+ if (from_reflection == to_reflection) {
+ to_reflection
+ ->MutableMessage(
+ to, field, from_child.GetReflection()->GetMessageFactory())
+ ->MergeFrom(from_child);
+ } else {
+ to_reflection->MutableMessage(to, field)->MergeFrom(from_child);
+ }
break;
}
}
@@ -173,15 +188,80 @@
reflection->MutableUnknownFields(message)->Clear();
}
+bool ReflectionOps::IsInitialized(const Message& message, bool check_fields,
+ bool check_descendants) {
+ const Descriptor* descriptor = message.GetDescriptor();
+ const Reflection* reflection = GetReflectionOrDie(message);
+ if (const int field_count = descriptor->field_count()) {
+ const FieldDescriptor* begin = descriptor->field(0);
+ const FieldDescriptor* end = begin + field_count;
+ GOOGLE_DCHECK_EQ(descriptor->field(field_count - 1), end - 1);
+
+ if (check_fields) {
+ // Check required fields of this message.
+ for (const FieldDescriptor* field = begin; field != end; ++field) {
+ if (field->is_required() && !reflection->HasField(message, field)) {
+ return false;
+ }
+ }
+ }
+
+ if (check_descendants) {
+ for (const FieldDescriptor* field = begin; field != end; ++field) {
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ const Descriptor* message_type = field->message_type();
+ if (PROTOBUF_PREDICT_FALSE(message_type->options().map_entry())) {
+ if (message_type->field(1)->cpp_type() ==
+ FieldDescriptor::CPPTYPE_MESSAGE) {
+ const MapFieldBase* map_field =
+ reflection->GetMapData(message, field);
+ if (map_field->IsMapValid()) {
+ MapIterator it(const_cast<Message*>(&message), field);
+ MapIterator end(const_cast<Message*>(&message), field);
+ for (map_field->MapBegin(&it), map_field->MapEnd(&end);
+ it != end; ++it) {
+ if (!it.GetValueRef().GetMessageValue().IsInitialized()) {
+ return false;
+ }
+ }
+ }
+ }
+ } else if (field->is_repeated()) {
+ const int size = reflection->FieldSize(message, field);
+ for (int j = 0; j < size; j++) {
+ if (!reflection->GetRepeatedMessage(message, field, j)
+ .IsInitialized()) {
+ return false;
+ }
+ }
+ } else if (reflection->HasField(message, field)) {
+ if (!reflection->GetMessage(message, field).IsInitialized()) {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ }
+ if (check_descendants && reflection->HasExtensionSet(message) &&
+ !reflection->GetExtensionSet(message).IsInitialized()) {
+ return false;
+ }
+ return true;
+}
+
bool ReflectionOps::IsInitialized(const Message& message) {
const Descriptor* descriptor = message.GetDescriptor();
const Reflection* reflection = GetReflectionOrDie(message);
// Check required fields of this message.
- for (int i = 0; i < descriptor->field_count(); i++) {
- if (descriptor->field(i)->is_required()) {
- if (!reflection->HasField(message, descriptor->field(i))) {
- return false;
+ {
+ const int field_count = descriptor->field_count();
+ for (int i = 0; i < field_count; i++) {
+ if (descriptor->field(i)->is_required()) {
+ if (!reflection->HasField(message, descriptor->field(i))) {
+ return false;
+ }
}
}
}
@@ -306,10 +386,13 @@
const Reflection* reflection = GetReflectionOrDie(message);
// Check required fields of this message.
- for (int i = 0; i < descriptor->field_count(); i++) {
- if (descriptor->field(i)->is_required()) {
- if (!reflection->HasField(message, descriptor->field(i))) {
- errors->push_back(prefix + descriptor->field(i)->name());
+ {
+ const int field_count = descriptor->field_count();
+ for (int i = 0; i < field_count; i++) {
+ if (descriptor->field(i)->is_required()) {
+ if (!reflection->HasField(message, descriptor->field(i))) {
+ errors->push_back(prefix + descriptor->field(i)->name());
+ }
}
}
}
@@ -339,6 +422,21 @@
}
}
+void GenericSwap(Message* m1, Message* m2) {
+ Arena* m2_arena = m2->GetArena();
+ GOOGLE_DCHECK(m1->GetArena() != m2_arena);
+
+ // Copy semantics in this case. We try to improve efficiency by placing the
+ // temporary on |m2|'s arena so that messages are copied twice rather than
+ // three times.
+ Message* tmp = m2->New(m2_arena);
+ std::unique_ptr<Message> tmp_deleter(m2_arena == nullptr ? tmp : nullptr);
+ tmp->CheckTypeAndMergeFrom(*m1);
+ m1->Clear();
+ m1->CheckTypeAndMergeFrom(*m2);
+ m2->GetReflection()->Swap(tmp, m2);
+}
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/reflection_ops.h b/src/google/protobuf/reflection_ops.h
index b30c050..fb98714 100644
--- a/src/google/protobuf/reflection_ops.h
+++ b/src/google/protobuf/reflection_ops.h
@@ -66,6 +66,8 @@
static void Merge(const Message& from, Message* to);
static void Clear(Message* message);
static bool IsInitialized(const Message& message);
+ static bool IsInitialized(const Message& message, bool check_fields,
+ bool check_descendants);
static void DiscardUnknownFields(Message* message);
// Finds all unset required fields in the message and adds their full
diff --git a/src/google/protobuf/reflection_ops_unittest.cc b/src/google/protobuf/reflection_ops_unittest.cc
index bd14193..dee2af2 100644
--- a/src/google/protobuf/reflection_ops_unittest.cc
+++ b/src/google/protobuf/reflection_ops_unittest.cc
@@ -340,12 +340,20 @@
unittest::TestRequired message;
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
message.set_a(1);
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, true, true));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
message.set_b(2);
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, true, true));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
message.set_c(3);
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
}
TEST(ReflectionOpsTest, ForeignIsInitialized) {
@@ -354,26 +362,35 @@
// Starts out initialized because the foreign message is itself an optional
// field.
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
// Once we create that field, the message is no longer initialized.
message.mutable_optional_message();
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true));
// Initialize it. Now we're initialized.
message.mutable_optional_message()->set_a(1);
message.mutable_optional_message()->set_b(2);
message.mutable_optional_message()->set_c(3);
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
// Add a repeated version of the message. No longer initialized.
unittest::TestRequired* sub_message = message.add_repeated_message();
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true));
// Initialize that repeated version.
sub_message->set_a(1);
sub_message->set_b(2);
sub_message->set_c(3);
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
}
TEST(ReflectionOpsTest, ExtensionIsInitialized) {
@@ -382,42 +399,62 @@
// Starts out initialized because the foreign message is itself an optional
// field.
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
// Once we create that field, the message is no longer initialized.
message.MutableExtension(unittest::TestRequired::single);
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true));
// Initialize it. Now we're initialized.
message.MutableExtension(unittest::TestRequired::single)->set_a(1);
message.MutableExtension(unittest::TestRequired::single)->set_b(2);
message.MutableExtension(unittest::TestRequired::single)->set_c(3);
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
// Add a repeated version of the message. No longer initialized.
message.AddExtension(unittest::TestRequired::multi);
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true));
// Initialize that repeated version.
message.MutableExtension(unittest::TestRequired::multi, 0)->set_a(1);
message.MutableExtension(unittest::TestRequired::multi, 0)->set_b(2);
message.MutableExtension(unittest::TestRequired::multi, 0)->set_c(3);
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
}
TEST(ReflectionOpsTest, OneofIsInitialized) {
unittest::TestRequiredOneof message;
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
message.mutable_foo_message();
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true));
message.set_foo_int(1);
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
message.mutable_foo_message();
EXPECT_FALSE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_FALSE(ReflectionOps::IsInitialized(message, false, true));
message.mutable_foo_message()->set_required_double(0.1);
EXPECT_TRUE(ReflectionOps::IsInitialized(message));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, true, false));
+ EXPECT_TRUE(ReflectionOps::IsInitialized(message, false, true));
}
static std::string FindInitializationErrors(const Message& message) {
@@ -473,6 +510,36 @@
EXPECT_EQ("foo_message.required_double", FindInitializationErrors(message));
}
+TEST(ReflectionOpsTest, GenericSwap) {
+ Arena arena;
+ {
+ unittest::TestAllTypes message;
+ auto* arena_message = Arena::CreateMessage<unittest::TestAllTypes>(&arena);
+ TestUtil::SetAllFields(arena_message);
+ const uint64 initial_arena_size = arena.SpaceUsed();
+
+ GenericSwap(&message, arena_message);
+
+ TestUtil::ExpectAllFieldsSet(message);
+ TestUtil::ExpectClear(*arena_message);
+ // The temp should be allocated on the arena in this case.
+ EXPECT_GT(arena.SpaceUsed(), initial_arena_size);
+ }
+ {
+ unittest::TestAllTypes message;
+ auto* arena_message = Arena::CreateMessage<unittest::TestAllTypes>(&arena);
+ TestUtil::SetAllFields(arena_message);
+ const uint64 initial_arena_size = arena.SpaceUsed();
+
+ GenericSwap(arena_message, &message);
+
+ TestUtil::ExpectAllFieldsSet(message);
+ TestUtil::ExpectClear(*arena_message);
+ // The temp shouldn't be allocated on the arena in this case.
+ EXPECT_EQ(arena.SpaceUsed(), initial_arena_size);
+ }
+}
+
} // namespace
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/repeated_field.cc b/src/google/protobuf/repeated_field.cc
index fc73917..1b5a0b8 100644
--- a/src/google/protobuf/repeated_field.cc
+++ b/src/google/protobuf/repeated_field.cc
@@ -55,8 +55,8 @@
return &rep_->elements[current_size_];
}
Rep* old_rep = rep_;
- Arena* arena = GetArenaNoVirtual();
- new_size = std::max(kMinRepeatedFieldAllocationSize,
+ Arena* arena = GetArena();
+ new_size = std::max(internal::kRepeatedFieldLowerClampLimit,
std::max(total_size_ * 2, new_size));
GOOGLE_CHECK_LE(new_size, (std::numeric_limits<size_t>::max() - kRepHeaderSize) /
sizeof(old_rep->elements[0]))
@@ -123,14 +123,22 @@
} // namespace internal
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedField<bool>;
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedField<int32>;
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedField<uint32>;
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedField<int64>;
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedField<uint64>;
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedField<float>;
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedField<double>;
-template class PROTOBUF_EXPORT_TEMPLATE_DEFINE RepeatedPtrField<std::string>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedField<bool>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedField<int32>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedField<uint32>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedField<int64>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedField<uint64>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedField<float>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedField<double>;
+template class PROTOBUF_EXPORT_TEMPLATE_DEFINE(PROTOBUF_EXPORT)
+ RepeatedPtrField<std::string>;
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h
index 280e0ef..9e27882 100644
--- a/src/google/protobuf/repeated_field.h
+++ b/src/google/protobuf/repeated_field.h
@@ -66,6 +66,7 @@
#include <type_traits>
+// Must be included last.
#include <google/protobuf/port_def.inc>
#ifdef SWIG
@@ -85,7 +86,16 @@
class MergePartialFromCodedStreamHelper;
-static const int kMinRepeatedFieldAllocationSize = 4;
+// kRepeatedFieldLowerClampLimit is the smallest size that will be allocated
+// when growing a repeated field.
+constexpr int kRepeatedFieldLowerClampLimit = 4;
+
+// kRepeatedFieldUpperClampLimit is the lowest signed integer value that
+// overflows when multiplied by 2 (which is undefined behavior). Sizes above
+// this will clamp to the maximum int value instead of following exponential
+// growth when growing a repeated field.
+constexpr int kRepeatedFieldUpperClampLimit =
+ (std::numeric_limits<int>::max() / 2) + 1;
// A utility function for logging that doesn't need any template types.
void LogIndexOutOfBounds(int index, int size);
@@ -106,6 +116,46 @@
typedef typename std::iterator_traits<Iter>::iterator_category Category;
return CalculateReserve(begin, end, Category());
}
+
+// Swaps two blocks of memory of size sizeof(T).
+template <typename T>
+inline void SwapBlock(char* p, char* q) {
+ T tmp;
+ memcpy(&tmp, p, sizeof(T));
+ memcpy(p, q, sizeof(T));
+ memcpy(q, &tmp, sizeof(T));
+}
+
+// Swaps two blocks of memory of size kSize:
+// template <int kSize> void memswap(char* p, char* q);
+
+template <int kSize>
+inline typename std::enable_if<(kSize == 0), void>::type memswap(char*, char*) {
+}
+
+#define PROTO_MEMSWAP_DEF_SIZE(reg_type, max_size) \
+ template <int kSize> \
+ typename std::enable_if<(kSize >= sizeof(reg_type) && kSize < (max_size)), \
+ void>::type \
+ memswap(char* p, char* q) { \
+ SwapBlock<reg_type>(p, q); \
+ memswap<kSize - sizeof(reg_type)>(p + sizeof(reg_type), \
+ q + sizeof(reg_type)); \
+ }
+
+PROTO_MEMSWAP_DEF_SIZE(uint8, 2)
+PROTO_MEMSWAP_DEF_SIZE(uint16, 4)
+PROTO_MEMSWAP_DEF_SIZE(uint32, 8)
+
+#ifdef __SIZEOF_INT128__
+PROTO_MEMSWAP_DEF_SIZE(uint64, 16)
+PROTO_MEMSWAP_DEF_SIZE(__uint128_t, (1u << 31))
+#else
+PROTO_MEMSWAP_DEF_SIZE(uint64, (1u << 31))
+#endif
+
+#undef PROTO_MEMSWAP_DEF_SIZE
+
} // namespace internal
// RepeatedField is used to represent repeated fields of a primitive type (in
@@ -258,7 +308,10 @@
iterator erase(const_iterator first, const_iterator last);
// Get the Arena on which this RepeatedField stores its elements.
- Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline Arena* GetArena() const {
+ return (total_size_ == 0) ? static_cast<Arena*>(arena_or_elements_)
+ : rep()->arena;
+ }
// For internal use only.
//
@@ -266,7 +319,7 @@
inline void InternalSwap(RepeatedField* other);
private:
- static const int kInitialSize = 0;
+ static constexpr int kInitialSize = 0;
// A note on the representation here (see also comment below for
// RepeatedPtrFieldBase's struct Rep):
//
@@ -327,12 +380,6 @@
// Copy the elements of |from| into |to|.
void CopyArray(Element* to, const Element* from, int size);
- // Internal helper expected by Arena methods.
- inline Arena* GetArenaNoVirtual() const {
- return (total_size_ == 0) ? static_cast<Arena*>(arena_or_elements_)
- : rep()->arena;
- }
-
// Internal helper to delete all elements and deallocate the storage.
// If Element has a trivial destructor (for example, if it's a fundamental
// type, like int32), the loop will be removed by the optimizer.
@@ -353,6 +400,84 @@
}
}
}
+
+ // This class is a performance wrapper around RepeatedField::Add(const T&)
+ // function. In general unless a RepeatedField is a local stack variable LLVM
+ // has a hard time optimizing Add. The machine code tends to be
+ // loop:
+ // mov %size, dword ptr [%repeated_field] // load
+ // cmp %size, dword ptr [%repeated_field + 4]
+ // jae fallback
+ // mov %buffer, qword ptr [%repeated_field + 8]
+ // mov dword [%buffer + %size * 4], %value
+ // inc %size // increment
+ // mov dword ptr [%repeated_field], %size // store
+ // jmp loop
+ //
+ // This puts a load/store in each iteration of the important loop variable
+ // size. It's a pretty bad compile that happens even in simple cases, but
+ // largely the presence of the fallback path disturbs the compilers mem-to-reg
+ // analysis.
+ //
+ // This class takes ownership of a repeated field for the duration of it's
+ // lifetime. The repeated field should not be accessed during this time, ie.
+ // only access through this class is allowed. This class should always be a
+ // function local stack variable. Intended use
+ //
+ // void AddSequence(const int* begin, const int* end, RepeatedField<int>* out)
+ // {
+ // RepeatedFieldAdder<int> adder(out); // Take ownership of out
+ // for (auto it = begin; it != end; ++it) {
+ // adder.Add(*it);
+ // }
+ // }
+ //
+ // Typically due to the fact adder is a local stack variable. The compiler
+ // will be successful in mem-to-reg transformation and the machine code will
+ // be loop: cmp %size, %capacity jae fallback mov dword ptr [%buffer + %size *
+ // 4], %val inc %size jmp loop
+ //
+ // The first version executes at 7 cycles per iteration while the second
+ // version near 1 or 2 cycles.
+ class FastAdder {
+ public:
+ explicit FastAdder(RepeatedField* rf) : repeated_field_(rf) {
+ if (kIsPod) {
+ index_ = repeated_field_->current_size_;
+ capacity_ = repeated_field_->total_size_;
+ buffer_ = repeated_field_->unsafe_elements();
+ }
+ }
+ ~FastAdder() {
+ if (kIsPod) repeated_field_->current_size_ = index_;
+ }
+
+ void Add(const Element& val) {
+ if (kIsPod) {
+ if (index_ == capacity_) {
+ repeated_field_->current_size_ = index_;
+ repeated_field_->Reserve(index_ + 1);
+ capacity_ = repeated_field_->total_size_;
+ buffer_ = repeated_field_->unsafe_elements();
+ }
+ buffer_[index_++] = val;
+ } else {
+ repeated_field_->Add(val);
+ }
+ }
+
+ private:
+ constexpr static bool kIsPod = std::is_pod<Element>::value;
+ RepeatedField* repeated_field_;
+ int index_;
+ int capacity_;
+ Element* buffer_;
+
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FastAdder);
+ };
+
+ friend class TestRepeatedFieldHelper;
+ friend class ::google::protobuf::internal::ParseContext;
};
template <typename Element>
@@ -589,10 +714,10 @@
template <typename TypeHandler>
PROTOBUF_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other);
- inline Arena* GetArenaNoVirtual() const { return arena_; }
+ inline Arena* GetArena() const { return arena_; }
private:
- static const int kInitialSize = 0;
+ static constexpr int kInitialSize = 0;
// A few notes on internal representation:
//
// We use an indirected approach, with struct Rep, to keep
@@ -611,7 +736,7 @@
int allocated_size;
void* elements[1];
};
- static const size_t kRepHeaderSize = sizeof(Rep) - sizeof(void*);
+ static constexpr size_t kRepHeaderSize = sizeof(Rep) - sizeof(void*);
Rep* rep_;
template <typename TypeHandler>
@@ -1016,7 +1141,7 @@
iterator erase(const_iterator first, const_iterator last);
// Gets the arena on which this RepeatedPtrField stores its elements.
- Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline Arena* GetArena() const;
// For internal use only.
//
@@ -1029,9 +1154,6 @@
// Note: RepeatedPtrField SHOULD NOT be subclassed by users.
class TypeHandler;
- // Internal arena accessor expected by helpers in Arena.
- inline Arena* GetArenaNoVirtual() const;
-
// Implementations for ExtractSubrange(). The copying behavior must be
// included only if the type supports the necessary operations (e.g.,
// MergeFrom()), so we must resolve this at compile time. ExtractSubrange()
@@ -1097,7 +1219,7 @@
// We don't just call Swap(&other) here because it would perform 3 copies if
// other is on an arena. This field can't be on an arena because arena
// construction always uses the Arena* accepting constructor.
- if (other.GetArenaNoVirtual()) {
+ if (other.GetArena()) {
CopyFrom(other);
} else {
InternalSwap(&other);
@@ -1110,7 +1232,7 @@
// We don't just call Swap(&other) here because it would perform 3 copies if
// the two fields are on different arenas.
if (this != &other) {
- if (this->GetArenaNoVirtual() != other.GetArenaNoVirtual()) {
+ if (this->GetArena() != other.GetArena()) {
CopyFrom(other);
} else {
InternalSwap(&other);
@@ -1206,14 +1328,19 @@
template <typename Element>
inline void RepeatedField<Element>::Add(const Element& value) {
- if (current_size_ == total_size_) Reserve(total_size_ + 1);
- elements()[current_size_++] = value;
+ uint32 size = current_size_;
+ if (static_cast<int>(size) == total_size_) Reserve(total_size_ + 1);
+ elements()[size] = value;
+ current_size_ = size + 1;
}
template <typename Element>
inline Element* RepeatedField<Element>::Add() {
- if (current_size_ == total_size_) Reserve(total_size_ + 1);
- return &elements()[current_size_++];
+ uint32 size = current_size_;
+ if (static_cast<int>(size) == total_size_) Reserve(total_size_ + 1);
+ auto ptr = &elements()[size];
+ current_size_ = size + 1;
+ return ptr;
}
template <typename Element>
@@ -1235,9 +1362,8 @@
std::copy(begin, end, elements() + size());
current_size_ = reserve + size();
} else {
- for (; begin != end; ++begin) {
- Add(*begin);
- }
+ FastAdder fast_adder(this);
+ for (; begin != end; ++begin) fast_adder.Add(*begin);
}
}
@@ -1319,20 +1445,25 @@
template <typename Element>
inline void RepeatedField<Element>::InternalSwap(RepeatedField* other) {
GOOGLE_DCHECK(this != other);
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
- std::swap(arena_or_elements_, other->arena_or_elements_);
- std::swap(current_size_, other->current_size_);
- std::swap(total_size_, other->total_size_);
+ // Swap all fields at once.
+ static_assert(std::is_standard_layout<RepeatedField<Element>>::value,
+ "offsetof() requires standard layout before c++17");
+ internal::memswap<offsetof(RepeatedField, arena_or_elements_) +
+ sizeof(this->arena_or_elements_) -
+ offsetof(RepeatedField, current_size_)>(
+ reinterpret_cast<char*>(this) + offsetof(RepeatedField, current_size_),
+ reinterpret_cast<char*>(other) + offsetof(RepeatedField, current_size_));
}
template <typename Element>
void RepeatedField<Element>::Swap(RepeatedField* other) {
if (this == other) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
- RepeatedField<Element> temp(other->GetArenaNoVirtual());
+ RepeatedField<Element> temp(other->GetArena());
temp.MergeFrom(*this);
CopyFrom(*other);
other->UnsafeArenaSwap(&temp);
@@ -1386,6 +1517,30 @@
return total_size_ > 0 ? (total_size_ * sizeof(Element) + kRepHeaderSize) : 0;
}
+namespace internal {
+// Returns the new size for a reserved field based on its 'total_size' and the
+// requested 'new_size'. The result is clamped to the closed interval:
+// [internal::kMinRepeatedFieldAllocationSize,
+// std::numeric_limits<int>::max()]
+// Requires:
+// new_size > total_size &&
+// (total_size == 0 ||
+// total_size >= kRepeatedFieldLowerClampLimit)
+inline int CalculateReserveSize(int total_size, int new_size) {
+ if (new_size < kRepeatedFieldLowerClampLimit) {
+ // Clamp to smallest allowed size.
+ return kRepeatedFieldLowerClampLimit;
+ }
+ if (total_size < kRepeatedFieldUpperClampLimit) {
+ return std::max(total_size * 2, new_size);
+ } else {
+ // Clamp to largest allowed size.
+ GOOGLE_DCHECK_GT(new_size, kRepeatedFieldUpperClampLimit);
+ return std::numeric_limits<int>::max();
+ }
+}
+} // namespace internal
+
// Avoid inlining of Reserve(): new, copy, and delete[] lead to a significant
// amount of code bloat.
template <typename Element>
@@ -1393,9 +1548,8 @@
if (total_size_ >= new_size) return;
Rep* old_rep = total_size_ > 0 ? rep() : NULL;
Rep* new_rep;
- Arena* arena = GetArenaNoVirtual();
- new_size = std::max(internal::kMinRepeatedFieldAllocationSize,
- std::max(total_size_ * 2, new_size));
+ Arena* arena = GetArena();
+ new_size = internal::CalculateReserveSize(total_size_, new_size);
GOOGLE_DCHECK_LE(
static_cast<size_t>(new_size),
(std::numeric_limits<size_t>::max() - kRepHeaderSize) / sizeof(Element))
@@ -1409,6 +1563,10 @@
}
new_rep->arena = arena;
int old_total_size = total_size_;
+ // Already known: new_size >= internal::kMinRepeatedFieldAllocationSize
+ // Maintain invariant:
+ // total_size_ == 0 ||
+ // total_size_ >= internal::kMinRepeatedFieldAllocationSize
total_size_ = new_size;
arena_or_elements_ = new_rep->elements;
// Invoke placement-new on newly allocated elements. We shouldn't have to do
@@ -1503,7 +1661,7 @@
template <typename TypeHandler>
inline void RepeatedPtrFieldBase::Swap(RepeatedPtrFieldBase* other) {
- if (other->GetArenaNoVirtual() == GetArenaNoVirtual()) {
+ if (other->GetArena() == GetArena()) {
InternalSwap(other);
} else {
SwapFallback<TypeHandler>(other);
@@ -1512,16 +1670,15 @@
template <typename TypeHandler>
void RepeatedPtrFieldBase::SwapFallback(RepeatedPtrFieldBase* other) {
- GOOGLE_DCHECK(other->GetArenaNoVirtual() != GetArenaNoVirtual());
+ GOOGLE_DCHECK(other->GetArena() != GetArena());
// Copy semantics in this case. We try to improve efficiency by placing the
- // temporary on |other|'s arena so that messages are copied cross-arena only
- // once, not twice.
- RepeatedPtrFieldBase temp(other->GetArenaNoVirtual());
+ // temporary on |other|'s arena so that messages are copied twice rather than
+ // three times.
+ RepeatedPtrFieldBase temp(other->GetArena());
temp.MergeFrom<TypeHandler>(*this);
this->Clear<TypeHandler>();
this->MergeFrom<TypeHandler>(*other);
- other->Clear<TypeHandler>();
other->InternalSwap(&temp);
temp.Destroy<TypeHandler>(); // Frees rep_ if `other` had no arena.
}
@@ -1664,7 +1821,7 @@
reinterpret_cast<typename TypeHandler::Type*>(our_elems[i]);
TypeHandler::Merge(*other_elem, new_elem);
}
- Arena* arena = GetArenaNoVirtual();
+ Arena* arena = GetArena();
for (int i = already_allocated; i < length; i++) {
// Not allocated: alloc a new element first, then merge it.
typename TypeHandler::Type* other_elem =
@@ -1741,7 +1898,7 @@
typename TypeHandler::Type* value, std::true_type) {
Arena* element_arena =
reinterpret_cast<Arena*>(TypeHandler::GetMaybeArenaPointer(value));
- Arena* arena = GetArenaNoVirtual();
+ Arena* arena = GetArena();
if (arena == element_arena && rep_ && rep_->allocated_size < total_size_) {
// Fast path: underlying arena representation (tagged pointer) is equal to
// our arena pointer, and we can add to array without resizing it (at least
@@ -1840,7 +1997,7 @@
// First, release an element.
typename TypeHandler::Type* result = UnsafeArenaReleaseLast<TypeHandler>();
// Now perform a copy if we're on an arena.
- Arena* arena = GetArenaNoVirtual();
+ Arena* arena = GetArena();
if (arena == NULL) {
return result;
} else {
@@ -1858,7 +2015,7 @@
template <typename TypeHandler>
inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseLastInternal(
std::false_type) {
- GOOGLE_DCHECK(GetArenaNoVirtual() == NULL)
+ GOOGLE_DCHECK(GetArena() == NULL)
<< "ReleaseLast() called on a RepeatedPtrField that is on an arena, "
<< "with a type that does not implement MergeFrom. This is unsafe; "
<< "please implement MergeFrom for your type.";
@@ -1887,7 +2044,7 @@
template <typename TypeHandler>
inline void RepeatedPtrFieldBase::AddCleared(
typename TypeHandler::Type* value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() == NULL)
+ GOOGLE_DCHECK(GetArena() == NULL)
<< "AddCleared() can only be used on a RepeatedPtrField not on an arena.";
GOOGLE_DCHECK(TypeHandler::GetArena(value) == NULL)
<< "AddCleared() can only accept values not on an arena.";
@@ -1899,10 +2056,10 @@
template <typename TypeHandler>
inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseCleared() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == NULL)
+ GOOGLE_DCHECK(GetArena() == NULL)
<< "ReleaseCleared() can only be used on a RepeatedPtrField not on "
<< "an arena.";
- GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
+ GOOGLE_DCHECK(GetArena() == NULL);
GOOGLE_DCHECK(rep_ != NULL);
GOOGLE_DCHECK_GT(rep_->allocated_size, current_size_);
return cast<TypeHandler>(rep_->elements[--rep_->allocated_size]);
@@ -1966,7 +2123,7 @@
// We don't just call Swap(&other) here because it would perform 3 copies if
// other is on an arena. This field can't be on an arena because arena
// construction always uses the Arena* accepting constructor.
- if (other.GetArenaNoVirtual()) {
+ if (other.GetArena()) {
CopyFrom(other);
} else {
InternalSwap(&other);
@@ -1979,7 +2136,7 @@
// We don't just call Swap(&other) here because it would perform 3 copies if
// the two fields are on different arenas.
if (this != &other) {
- if (this->GetArenaNoVirtual() != other.GetArenaNoVirtual()) {
+ if (this->GetArena() != other.GetArena()) {
CopyFrom(other);
} else {
InternalSwap(&other);
@@ -2065,7 +2222,7 @@
if (num > 0) {
// Save the values of the removed elements if requested.
if (elements != NULL) {
- if (GetArenaNoVirtual() != NULL) {
+ if (GetArena() != NULL) {
// If we're on an arena, we perform a copy for each element so that the
// returned elements are heap-allocated.
for (int i = 0; i < num; ++i) {
@@ -2095,7 +2252,7 @@
// ExtractSubrange() must return heap-allocated objects by contract, and we
// cannot fulfill this contract if we are an on arena, we must GOOGLE_DCHECK() that
// we are not on an arena.
- GOOGLE_DCHECK(GetArenaNoVirtual() == NULL)
+ GOOGLE_DCHECK(GetArena() == NULL)
<< "ExtractSubrange() when arena is non-NULL is only supported when "
<< "the Element type supplies a MergeFrom() operation to make copies.";
UnsafeArenaExtractSubrange(start, num, elements);
@@ -2179,8 +2336,8 @@
}
template <typename Element>
-inline Arena* RepeatedPtrField<Element>::GetArenaNoVirtual() const {
- return RepeatedPtrFieldBase::GetArenaNoVirtual();
+inline Arena* RepeatedPtrField<Element>::GetArena() const {
+ return RepeatedPtrFieldBase::GetArena();
}
template <typename Element>
@@ -2418,11 +2575,17 @@
void RepeatedPtrFieldBase::InternalSwap(RepeatedPtrFieldBase* other) {
GOOGLE_DCHECK(this != other);
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
- std::swap(rep_, other->rep_);
- std::swap(current_size_, other->current_size_);
- std::swap(total_size_, other->total_size_);
+ // Swap all fields at once.
+ static_assert(std::is_standard_layout<RepeatedPtrFieldBase>::value,
+ "offsetof() requires standard layout before c++17");
+ internal::memswap<offsetof(RepeatedPtrFieldBase, rep_) + sizeof(this->rep_) -
+ offsetof(RepeatedPtrFieldBase, current_size_)>(
+ reinterpret_cast<char*>(this) +
+ offsetof(RepeatedPtrFieldBase, current_size_),
+ reinterpret_cast<char*>(other) +
+ offsetof(RepeatedPtrFieldBase, current_size_));
}
} // namespace internal
@@ -2652,15 +2815,22 @@
mutable_field);
}
-// Extern declarations of common instantiations to reduce libray bloat.
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<bool>;
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<int32>;
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<uint32>;
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<int64>;
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<uint64>;
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<float>;
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE RepeatedField<double>;
-extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE
+// Extern declarations of common instantiations to reduce library bloat.
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
+ RepeatedField<bool>;
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
+ RepeatedField<int32>;
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
+ RepeatedField<uint32>;
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
+ RepeatedField<int64>;
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
+ RepeatedField<uint64>;
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
+ RepeatedField<float>;
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
+ RepeatedField<double>;
+extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE(PROTOBUF_EXPORT)
RepeatedPtrField<std::string>;
} // namespace protobuf
diff --git a/src/google/protobuf/repeated_field_reflection_unittest.cc b/src/google/protobuf/repeated_field_reflection_unittest.cc
index 0499102..384d32f 100644
--- a/src/google/protobuf/repeated_field_reflection_unittest.cc
+++ b/src/google/protobuf/repeated_field_reflection_unittest.cc
@@ -52,11 +52,7 @@
static int Func(int i, int j) { return i * j; }
-static std::string StrFunc(int i, int j) {
- std::string str;
- SStringPrintf(&str, "%d", Func(i, 4));
- return str;
-}
+static std::string StrFunc(int i, int j) { return StrCat(Func(i, 4)); }
TEST(RepeatedFieldReflectionTest, RegularFields) {
TestAllTypes message;
@@ -344,7 +340,7 @@
}
EXPECT_EQ(10, index);
- // Test iterator operators that are not ususally used in regular for-loops.
+ // Test iterator operators that are not usually used in regular for-loops.
// Including: post increment, assign, ==.
MessageIterator old_it = rf_foreign_message.begin();
MessageIterator new_it = old_it++;
diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc
index ca5452b..3d64782 100644
--- a/src/google/protobuf/repeated_field_unittest.cc
+++ b/src/google/protobuf/repeated_field_unittest.cc
@@ -38,6 +38,8 @@
#include <google/protobuf/repeated_field.h>
#include <algorithm>
+#include <cstdlib>
+#include <iterator>
#include <limits>
#include <list>
#include <sstream>
@@ -53,6 +55,9 @@
#include <gtest/gtest.h>
#include <google/protobuf/stubs/stl_util.h>
+// Must be included last.
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace {
@@ -268,6 +273,68 @@
EXPECT_TRUE(field.empty());
}
+TEST(RepeatedField, ReserveNothing) {
+ RepeatedField<int> field;
+ EXPECT_EQ(0, field.Capacity());
+
+ field.Reserve(-1);
+ EXPECT_EQ(0, field.Capacity());
+}
+
+TEST(RepeatedField, ReserveLowerClamp) {
+ const int clamped_value = internal::CalculateReserveSize(0, 1);
+ EXPECT_EQ(internal::kRepeatedFieldLowerClampLimit, clamped_value);
+ EXPECT_EQ(clamped_value, internal::CalculateReserveSize(clamped_value, 2));
+}
+
+TEST(RepeatedField, ReserveGrowth) {
+ // Make sure the field capacity doubles in size on repeated reservation.
+ for (int size = internal::kRepeatedFieldLowerClampLimit, i = 0; i < 4;
+ ++i, size *= 2) {
+ EXPECT_EQ(size * 2, internal::CalculateReserveSize(size, size + 1));
+ }
+}
+
+TEST(RepeatedField, ReserveLarge) {
+ const int old_size = 10;
+ // This is a size we won't get by doubling:
+ const int new_size = old_size * 3 + 1;
+
+ // Reserving more than 2x current capacity should grow directly to that size.
+ EXPECT_EQ(new_size, internal::CalculateReserveSize(old_size, new_size));
+}
+
+TEST(RepeatedField, ReserveHuge) {
+ // Largest value that does not clamp to the large limit:
+ constexpr int non_clamping_limit = std::numeric_limits<int>::max() / 2;
+ ASSERT_LT(2 * non_clamping_limit, std::numeric_limits<int>::max());
+ EXPECT_LT(internal::CalculateReserveSize(non_clamping_limit,
+ non_clamping_limit + 1),
+ std::numeric_limits<int>::max());
+
+ // Smallest size that *will* clamp to the upper limit:
+ constexpr int min_clamping_size = std::numeric_limits<int>::max() / 2 + 1;
+ EXPECT_EQ(
+ internal::CalculateReserveSize(min_clamping_size, min_clamping_size + 1),
+ std::numeric_limits<int>::max());
+
+#ifdef PROTOBUF_TEST_ALLOW_LARGE_ALLOC
+ // The rest of this test may allocate several GB of memory, so it is only
+ // built if explicitly requested.
+ RepeatedField<int> huge_field;
+
+ // Reserve a size for huge_field that will clamp.
+ huge_field.Reserve(min_clamping_size);
+ EXPECT_GE(huge_field.Capacity(), min_clamping_size);
+ ASSERT_LT(huge_field.Capacity(), std::numeric_limits<int>::max() - 1);
+
+ // Allocation may return more memory than we requested. However, the updated
+ // size must still be clamped to a valid range.
+ huge_field.Reserve(huge_field.Capacity() + 1);
+ EXPECT_EQ(huge_field.Capacity(), std::numeric_limits<int>::max());
+#endif // PROTOBUF_TEST_ALLOW_LARGE_ALLOC
+}
+
TEST(RepeatedField, MergeFrom) {
RepeatedField<int> source, destination;
source.Add(4);
diff --git a/src/google/protobuf/service.h b/src/google/protobuf/service.h
index d6b4ab8..b18a803 100644
--- a/src/google/protobuf/service.h
+++ b/src/google/protobuf/service.h
@@ -33,7 +33,7 @@
// Sanjay Ghemawat, Jeff Dean, and others.
//
// DEPRECATED: This module declares the abstract interfaces underlying proto2
-// RPC services. These are intented to be independent of any particular RPC
+// RPC services. These are intended to be independent of any particular RPC
// implementation, so that proto2 services can be used on top of a variety
// of implementations. Starting with version 2.3.0, RPC implementations should
// not try to build on these, but should instead provide code generator plugins
diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc
index 7ae9445..9f09bec 100644
--- a/src/google/protobuf/source_context.pb.cc
+++ b/src/google/protobuf/source_context.pb.cc
@@ -69,16 +69,15 @@
&scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto = {
- &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto, "google/protobuf/source_context.proto", 251,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto, "google/protobuf/source_context.proto", 251,
&descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once, descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_sccs, descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fsource_5fcontext_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fsource_5fcontext_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -89,18 +88,19 @@
public:
};
-SourceContext::SourceContext()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
+SourceContext::SourceContext(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.SourceContext)
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceContext)
}
SourceContext::SourceContext(const SourceContext& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
file_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_file_name().empty()) {
- file_name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.file_name_);
+ file_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_file_name(),
+ GetArena());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceContext)
}
@@ -113,12 +113,20 @@
SourceContext::~SourceContext() {
// @@protoc_insertion_point(destructor:google.protobuf.SourceContext)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void SourceContext::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
file_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
+void SourceContext::ArenaDtor(void* object) {
+ SourceContext* _this = reinterpret_cast< SourceContext* >(object);
+ (void)_this;
+}
+void SourceContext::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
void SourceContext::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
@@ -134,12 +142,13 @@
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- file_name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
- _internal_metadata_.Clear();
+ file_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* SourceContext::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -160,7 +169,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -192,7 +203,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceContext)
return target;
@@ -240,13 +251,12 @@
void SourceContext::MergeFrom(const SourceContext& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceContext)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.file_name().size() > 0) {
-
- file_name_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.file_name_);
+ _internal_set_file_name(from._internal_file_name());
}
}
@@ -270,9 +280,8 @@
void SourceContext::InternalSwap(SourceContext* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- file_name_.Swap(&other->file_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ file_name_.Swap(&other->file_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
::PROTOBUF_NAMESPACE_ID::Metadata SourceContext::GetMetadata() const {
@@ -284,7 +293,7 @@
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE PROTOBUF_NAMESPACE_ID::SourceContext* Arena::CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::SourceContext >(Arena* arena) {
- return Arena::CreateInternal< PROTOBUF_NAMESPACE_ID::SourceContext >(arena);
+ return Arena::CreateMessageInternal< PROTOBUF_NAMESPACE_ID::SourceContext >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h
index 8a49008..1bc08ce 100644
--- a/src/google/protobuf/source_context.pb.h
+++ b/src/google/protobuf/source_context.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -66,10 +66,10 @@
// ===================================================================
-class PROTOBUF_EXPORT SourceContext :
+class PROTOBUF_EXPORT SourceContext PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ {
public:
- SourceContext();
+ inline SourceContext() : SourceContext(nullptr) {};
virtual ~SourceContext();
SourceContext(const SourceContext& from);
@@ -83,7 +83,7 @@
return *this;
}
inline SourceContext& operator=(SourceContext&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -115,6 +115,15 @@
}
inline void Swap(SourceContext* other) {
if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(SourceContext* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -149,13 +158,11 @@
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.SourceContext";
}
+ protected:
+ explicit SourceContext(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return nullptr;
- }
- inline void* MaybeArenaPtr() const {
- return nullptr;
- }
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -184,6 +191,15 @@
std::string* mutable_file_name();
std::string* release_file_name();
void set_allocated_file_name(std::string* file_name);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_file_name();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_file_name(
+ std::string* file_name);
private:
const std::string& _internal_file_name() const;
void _internal_set_file_name(const std::string& value);
@@ -194,7 +210,9 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr file_name_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto;
@@ -212,7 +230,7 @@
// string file_name = 1;
inline void SourceContext::clear_file_name() {
- file_name_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ file_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& SourceContext::file_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceContext.file_name)
@@ -227,38 +245,39 @@
return _internal_mutable_file_name();
}
inline const std::string& SourceContext::_internal_file_name() const {
- return file_name_.GetNoArena();
+ return file_name_.Get();
}
inline void SourceContext::_internal_set_file_name(const std::string& value) {
- file_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
+ file_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void SourceContext::set_file_name(std::string&& value) {
- file_name_.SetNoArena(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
+ file_name_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceContext.file_name)
}
inline void SourceContext::set_file_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
- file_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ file_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceContext.file_name)
}
-inline void SourceContext::set_file_name(const char* value, size_t size) {
+inline void SourceContext::set_file_name(const char* value,
+ size_t size) {
- file_name_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ file_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceContext.file_name)
}
inline std::string* SourceContext::_internal_mutable_file_name() {
- return file_name_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return file_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* SourceContext::release_file_name() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceContext.file_name)
-
- return file_name_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ return file_name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void SourceContext::set_allocated_file_name(std::string* file_name) {
if (file_name != nullptr) {
@@ -266,9 +285,29 @@
} else {
}
- file_name_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), file_name);
+ file_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), file_name,
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name)
}
+inline std::string* SourceContext::unsafe_arena_release_file_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.SourceContext.file_name)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return file_name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void SourceContext::unsafe_arena_set_allocated_file_name(
+ std::string* file_name) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (file_name != nullptr) {
+
+ } else {
+
+ }
+ file_name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ file_name, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.SourceContext.file_name)
+}
#ifdef __GNUC__
#pragma GCC diagnostic pop
diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc
index 15a889b..027fef6 100644
--- a/src/google/protobuf/struct.pb.cc
+++ b/src/google/protobuf/struct.pb.cc
@@ -148,16 +148,15 @@
&scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fstruct_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fstruct_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fstruct_2eproto = {
- &descriptor_table_google_2fprotobuf_2fstruct_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto, "google/protobuf/struct.proto", 641,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto, "google/protobuf/struct.proto", 641,
&descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, descriptor_table_google_2fprotobuf_2fstruct_2eproto_sccs, descriptor_table_google_2fprotobuf_2fstruct_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fstruct_2eproto, 4, file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto, file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fstruct_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fstruct_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fstruct_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fstruct_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* NullValue_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fstruct_2eproto);
@@ -198,23 +197,16 @@
public:
};
-Struct::Struct()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Struct)
-}
Struct::Struct(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
fields_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Struct)
}
Struct::Struct(const Struct& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
fields_.MergeFrom(from.fields_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Struct)
}
@@ -226,10 +218,11 @@
Struct::~Struct() {
// @@protoc_insertion_point(destructor:google.protobuf.Struct)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Struct::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void Struct::ArenaDtor(void* object) {
@@ -254,12 +247,12 @@
(void) cached_has_bits;
fields_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Struct::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -283,7 +276,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -346,7 +341,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Struct)
return target;
@@ -396,7 +391,7 @@
void Struct::MergeFrom(const Struct& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Struct)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -423,7 +418,7 @@
void Struct::InternalSwap(Struct* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
fields_.Swap(&other->fields_);
}
@@ -460,7 +455,7 @@
return *msg->kind_.list_value_;
}
void Value::set_allocated_struct_value(PROTOBUF_NAMESPACE_ID::Struct* struct_value) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_kind();
if (struct_value) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
@@ -475,7 +470,7 @@
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
}
void Value::set_allocated_list_value(PROTOBUF_NAMESPACE_ID::ListValue* list_value) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
clear_kind();
if (list_value) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
@@ -489,22 +484,15 @@
}
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
}
-Value::Value()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Value)
-}
Value::Value(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Value)
}
Value::Value(const Value& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
clear_has_kind();
switch (from.kind_case()) {
case kNullValue: {
@@ -546,10 +534,11 @@
Value::~Value() {
// @@protoc_insertion_point(destructor:google.protobuf.Value)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Value::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
if (has_kind()) {
clear_kind();
}
@@ -582,8 +571,7 @@
break;
}
case kStringValue: {
- kind_.string_value_.Destroy(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ kind_.string_value_.Destroy(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
break;
}
case kBoolValue: {
@@ -591,13 +579,13 @@
break;
}
case kStructValue: {
- if (GetArenaNoVirtual() == nullptr) {
+ if (GetArena() == nullptr) {
delete kind_.struct_value_;
}
break;
}
case kListValue: {
- if (GetArenaNoVirtual() == nullptr) {
+ if (GetArena() == nullptr) {
delete kind_.list_value_;
}
break;
@@ -617,12 +605,12 @@
(void) cached_has_bits;
clear_kind();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Value::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -631,7 +619,7 @@
// .google.protobuf.NullValue null_value = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_null_value(static_cast<PROTOBUF_NAMESPACE_ID::NullValue>(val));
} else goto handle_unusual;
@@ -655,7 +643,7 @@
// bool bool_value = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
- _internal_set_bool_value(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
+ _internal_set_bool_value(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -679,7 +667,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -746,7 +736,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Value)
return target;
@@ -829,7 +819,7 @@
void Value::MergeFrom(const Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Value)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -884,7 +874,7 @@
void Value::InternalSwap(Value* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(kind_, other->kind_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
@@ -902,14 +892,8 @@
public:
};
-ListValue::ListValue()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.ListValue)
-}
ListValue::ListValue(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
values_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -917,9 +901,8 @@
}
ListValue::ListValue(const ListValue& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
values_(from.values_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue)
}
@@ -930,10 +913,11 @@
ListValue::~ListValue() {
// @@protoc_insertion_point(destructor:google.protobuf.ListValue)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void ListValue::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void ListValue::ArenaDtor(void* object) {
@@ -958,12 +942,12 @@
(void) cached_has_bits;
values_.Clear();
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* ListValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -987,7 +971,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1017,7 +1003,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ListValue)
return target;
@@ -1065,7 +1051,7 @@
void ListValue::MergeFrom(const ListValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ListValue)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1092,7 +1078,7 @@
void ListValue::InternalSwap(ListValue* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
values_.InternalSwap(&other->values_);
}
diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h
index 05a5f74..634b00d 100644
--- a/src/google/protobuf/struct.pb.h
+++ b/src/google/protobuf/struct.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -138,10 +138,10 @@
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Struct :
+class PROTOBUF_EXPORT Struct PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Struct) */ {
public:
- Struct();
+ inline Struct() : Struct(nullptr) {};
virtual ~Struct();
Struct(const Struct& from);
@@ -155,7 +155,7 @@
return *this;
}
inline Struct& operator=(Struct&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -163,12 +163,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -193,7 +187,7 @@
}
inline void Swap(Struct* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -201,7 +195,7 @@
}
void UnsafeArenaSwap(Struct* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -241,13 +235,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -288,7 +275,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -303,10 +289,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Value :
+class PROTOBUF_EXPORT Value PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Value) */ {
public:
- Value();
+ inline Value() : Value(nullptr) {};
virtual ~Value();
Value(const Value& from);
@@ -320,7 +306,7 @@
return *this;
}
inline Value& operator=(Value&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -328,12 +314,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -368,7 +348,7 @@
}
inline void Swap(Value* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -376,7 +356,7 @@
}
void UnsafeArenaSwap(Value* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -416,13 +396,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -561,7 +534,6 @@
inline bool has_kind() const;
inline void clear_has_kind();
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -581,10 +553,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT ListValue :
+class PROTOBUF_EXPORT ListValue PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ListValue) */ {
public:
- ListValue();
+ inline ListValue() : ListValue(nullptr) {};
virtual ~ListValue();
ListValue(const ListValue& from);
@@ -598,7 +570,7 @@
return *this;
}
inline ListValue& operator=(ListValue&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -606,12 +578,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -636,7 +602,7 @@
}
inline void Swap(ListValue* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -644,7 +610,7 @@
}
void UnsafeArenaSwap(ListValue* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -684,13 +650,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -731,7 +690,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -864,8 +822,7 @@
}
inline void Value::clear_string_value() {
if (_internal_has_string_value()) {
- kind_.string_value_.Destroy(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ kind_.string_value_.Destroy(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
clear_has_kind();
}
}
@@ -893,8 +850,7 @@
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value,
- GetArenaNoVirtual());
+ kind_.string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Value::set_string_value(std::string&& value) {
// @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
@@ -904,7 +860,7 @@
kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
kind_.string_value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Value.string_value)
}
inline void Value::set_string_value(const char* value) {
@@ -915,7 +871,7 @@
kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
kind_.string_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- ::std::string(value), GetArenaNoVirtual());
+ ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Value.string_value)
}
inline void Value::set_string_value(const char* value,
@@ -928,7 +884,7 @@
kind_.string_value_.Set(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Value.string_value)
}
inline std::string* Value::_internal_mutable_string_value() {
@@ -937,15 +893,13 @@
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
- return kind_.string_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ return kind_.string_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Value::release_string_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.string_value)
if (_internal_has_string_value()) {
clear_has_kind();
- return kind_.string_value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ return kind_.string_value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
} else {
return nullptr;
}
@@ -957,29 +911,33 @@
if (string_value != nullptr) {
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(string_value);
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena();
+ if (arena != nullptr) {
+ arena->Own(string_value);
+ }
}
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value)
}
inline std::string* Value::unsafe_arena_release_string_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.string_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (_internal_has_string_value()) {
clear_has_kind();
return kind_.string_value_.UnsafeArenaRelease(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
} else {
return nullptr;
}
}
inline void Value::unsafe_arena_set_allocated_string_value(std::string* string_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (!_internal_has_string_value()) {
kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
clear_kind();
if (string_value) {
set_has_string_value();
- kind_.string_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual());
+ kind_.string_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), string_value, GetArena());
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.string_value)
}
@@ -1031,7 +989,7 @@
}
inline void Value::clear_struct_value() {
if (_internal_has_struct_value()) {
- if (GetArenaNoVirtual() == nullptr) {
+ if (GetArena() == nullptr) {
delete kind_.struct_value_;
}
clear_has_kind();
@@ -1042,7 +1000,7 @@
if (_internal_has_struct_value()) {
clear_has_kind();
PROTOBUF_NAMESPACE_ID::Struct* temp = kind_.struct_value_;
- if (GetArenaNoVirtual() != nullptr) {
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
kind_.struct_value_ = nullptr;
@@ -1083,8 +1041,7 @@
if (!_internal_has_struct_value()) {
clear_kind();
set_has_struct_value();
- kind_.struct_value_ = CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Struct >(
- GetArenaNoVirtual());
+ kind_.struct_value_ = CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::Struct >(GetArena());
}
return kind_.struct_value_;
}
@@ -1105,7 +1062,7 @@
}
inline void Value::clear_list_value() {
if (_internal_has_list_value()) {
- if (GetArenaNoVirtual() == nullptr) {
+ if (GetArena() == nullptr) {
delete kind_.list_value_;
}
clear_has_kind();
@@ -1116,7 +1073,7 @@
if (_internal_has_list_value()) {
clear_has_kind();
PROTOBUF_NAMESPACE_ID::ListValue* temp = kind_.list_value_;
- if (GetArenaNoVirtual() != nullptr) {
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
kind_.list_value_ = nullptr;
@@ -1157,8 +1114,7 @@
if (!_internal_has_list_value()) {
clear_kind();
set_has_list_value();
- kind_.list_value_ = CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::ListValue >(
- GetArenaNoVirtual());
+ kind_.list_value_ = CreateMaybeMessage< PROTOBUF_NAMESPACE_ID::ListValue >(GetArena());
}
return kind_.list_value_;
}
diff --git a/src/google/protobuf/stubs/bytestream.h b/src/google/protobuf/stubs/bytestream.h
index 0840386..0193301 100644
--- a/src/google/protobuf/stubs/bytestream.h
+++ b/src/google/protobuf/stubs/bytestream.h
@@ -83,7 +83,7 @@
// Appends the "n" bytes starting at "bytes".
virtual void Append(const char* bytes, size_t n) = 0;
- // Flushes internal buffers. The default implemenation does nothing. ByteSink
+ // Flushes internal buffers. The default implementation does nothing. ByteSink
// subclasses may use internal buffers that require calling Flush() at the end
// of the stream.
virtual void Flush();
diff --git a/src/google/protobuf/stubs/callback.h b/src/google/protobuf/stubs/callback.h
index ab4a3aa..b7a3a82 100644
--- a/src/google/protobuf/stubs/callback.h
+++ b/src/google/protobuf/stubs/callback.h
@@ -68,7 +68,7 @@
// Also note that the arguments cannot be references:
// void Foo(const string& s);
// string my_str;
-// NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes.
+// NewCallback(&Foo, my_str); // WON'T WORK: Can't use references.
// However, correctly-typed pointers will work just fine.
class PROTOBUF_EXPORT Closure {
public:
diff --git a/src/google/protobuf/stubs/casts.h b/src/google/protobuf/stubs/casts.h
index b509f68..83750bd 100644
--- a/src/google/protobuf/stubs/casts.h
+++ b/src/google/protobuf/stubs/casts.h
@@ -31,13 +31,15 @@
#ifndef GOOGLE_PROTOBUF_CASTS_H__
#define GOOGLE_PROTOBUF_CASTS_H__
-#include <type_traits>
-
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+#include <type_traits>
+
namespace google {
namespace protobuf {
namespace internal {
+
// Use implicit_cast as a safe version of static_cast or const_cast
// for upcasting in the type hierarchy (i.e. casting a pointer to Foo
// to a pointer to SuperclassOfFoo or casting a pointer to Foo to
@@ -88,7 +90,7 @@
implicit_cast<From*, To>(0);
}
-#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
+#if !defined(NDEBUG) && PROTOBUF_RTTI
assert(f == nullptr || dynamic_cast<To>(f) != nullptr); // RTTI: debug mode only!
#endif
return static_cast<To>(f);
@@ -105,7 +107,7 @@
implicit_cast<From*, ToAsPointer>(0);
}
-#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
+#if !defined(NDEBUG) && PROTOBUF_RTTI
// RTTI: debug mode only!
assert(dynamic_cast<ToAsPointer>(&f) != nullptr);
#endif
@@ -131,4 +133,7 @@
} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_CASTS_H__
diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h
index 2ee72f5..74fbada 100644
--- a/src/google/protobuf/stubs/common.h
+++ b/src/google/protobuf/stubs/common.h
@@ -81,7 +81,7 @@
// The current version, represented as a single integer to make comparison
// easier: major * 10^6 + minor * 10^3 + micro
-#define GOOGLE_PROTOBUF_VERSION 3011000
+#define GOOGLE_PROTOBUF_VERSION 3012000
// A suffix string for alpha, beta or rc releases. Empty for stable releases.
#define GOOGLE_PROTOBUF_VERSION_SUFFIX ""
@@ -89,15 +89,15 @@
// 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 = 3011000;
+static const int kMinHeaderVersionForLibrary = 3012000;
// The minimum protoc version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3011000
+#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3012000
// The minimum header version which works with the current version of
// protoc. This constant should only be used in VerifyVersion().
-static const int kMinHeaderVersionForProtoc = 3011000;
+static const int kMinHeaderVersionForProtoc = 3012000;
// Verifies that the headers and libraries are compatible. Use the macro
// below to call this.
@@ -133,7 +133,7 @@
return IsStructurallyValidUTF8(str.data(), static_cast<int>(str.length()));
}
-// Returns initial number of bytes of structually valid UTF-8.
+// Returns initial number of bytes of structurally valid UTF-8.
PROTOBUF_EXPORT int UTF8SpnStructurallyValid(const StringPiece& str);
// Coerce UTF-8 byte string in src_str to be
diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h
index 31d2a10..c21c28a 100644
--- a/src/google/protobuf/stubs/port.h
+++ b/src/google/protobuf/stubs/port.h
@@ -225,12 +225,6 @@
# define GOOGLE_PROTOBUF_USE_PORTABLE_LOG2
#endif
-#if defined(_MSC_VER)
-#define GOOGLE_THREAD_LOCAL __declspec(thread)
-#else
-#define GOOGLE_THREAD_LOCAL __thread
-#endif
-
// The following guarantees declaration of the byte swap functions.
#ifdef _MSC_VER
#define bswap_16(x) _byteswap_ushort(x)
diff --git a/src/google/protobuf/stubs/statusor.h b/src/google/protobuf/stubs/statusor.h
index 90fd5f0..c02e89a 100644
--- a/src/google/protobuf/stubs/statusor.h
+++ b/src/google/protobuf/stubs/statusor.h
@@ -153,6 +153,7 @@
// If you need to initialize a T object from the stored value,
// ConsumeValueOrDie() may be more efficient.
const T& ValueOrDie() const;
+ const T& value () const;
private:
Status status_;
@@ -204,7 +205,7 @@
template<typename T>
inline StatusOr<T>::StatusOr(const T& value) {
if (internal::StatusOrHelper::Specialize<T>::IsValueNull(value)) {
- status_ = Status(error::INTERNAL, "nullptr is not a vaild argument.");
+ status_ = Status(error::INTERNAL, "nullptr is not a valid argument.");
} else {
status_ = Status::OK;
value_ = value;
@@ -254,6 +255,14 @@
}
return value_;
}
+
+template<typename T>
+inline const T& StatusOr<T>::value() const {
+ if (!status_.ok()) {
+ internal::StatusOrHelper::Crash(status_);
+ }
+ return value_;
+}
} // namespace util
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/structurally_valid.cc b/src/google/protobuf/stubs/structurally_valid.cc
index 788b224..4d424a1 100644
--- a/src/google/protobuf/stubs/structurally_valid.cc
+++ b/src/google/protobuf/stubs/structurally_valid.cc
@@ -456,8 +456,7 @@
}
//----------------------------
-
- // Exit posibilities:
+ // Exit possibilities:
// Some exit code, !state0, back up over last char
// Some exit code, state0, back up one byte exactly
// source consumed, !state0, back up over partial char
diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc
index 62b3f0a..24ae286 100644
--- a/src/google/protobuf/stubs/strutil.cc
+++ b/src/google/protobuf/stubs/strutil.cc
@@ -1435,32 +1435,44 @@
// after the area just overwritten. It comes in multiple flavors to minimize
// call overhead.
static char *Append1(char *out, const AlphaNum &x) {
- memcpy(out, x.data(), x.size());
- return out + x.size();
+ if (x.size() > 0) {
+ memcpy(out, x.data(), x.size());
+ out += x.size();
+ }
+ return out;
}
static char *Append2(char *out, const AlphaNum &x1, const AlphaNum &x2) {
- memcpy(out, x1.data(), x1.size());
- out += x1.size();
-
- memcpy(out, x2.data(), x2.size());
- return out + x2.size();
+ if (x1.size() > 0) {
+ memcpy(out, x1.data(), x1.size());
+ out += x1.size();
+ }
+ if (x2.size() > 0) {
+ memcpy(out, x2.data(), x2.size());
+ out += x2.size();
+ }
+ return out;
}
-static char *Append4(char *out,
- const AlphaNum &x1, const AlphaNum &x2,
+static char *Append4(char *out, const AlphaNum &x1, const AlphaNum &x2,
const AlphaNum &x3, const AlphaNum &x4) {
- memcpy(out, x1.data(), x1.size());
- out += x1.size();
-
- memcpy(out, x2.data(), x2.size());
- out += x2.size();
-
- memcpy(out, x3.data(), x3.size());
- out += x3.size();
-
- memcpy(out, x4.data(), x4.size());
- return out + x4.size();
+ if (x1.size() > 0) {
+ memcpy(out, x1.data(), x1.size());
+ out += x1.size();
+ }
+ if (x2.size() > 0) {
+ memcpy(out, x2.data(), x2.size());
+ out += x2.size();
+ }
+ if (x3.size() > 0) {
+ memcpy(out, x3.data(), x3.size());
+ out += x3.size();
+ }
+ if (x4.size() > 0) {
+ memcpy(out, x4.data(), x4.size());
+ out += x4.size();
+ }
+ return out;
}
string StrCat(const AlphaNum &a, const AlphaNum &b) {
@@ -2272,16 +2284,19 @@
// Table of UTF-8 character lengths, based on first byte
static const unsigned char kUTF8LenTbl[256] = {
- 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,
+ 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,
- 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,
- 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, 4,4,4,4,4,4,4,4
-};
+ 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
// Return length of a single UTF-8 source character
int UTF8FirstLetterNumBytes(const char* src, int len) {
diff --git a/src/google/protobuf/stubs/strutil.h b/src/google/protobuf/stubs/strutil.h
index e688c8e..981cb6e 100644
--- a/src/google/protobuf/stubs/strutil.h
+++ b/src/google/protobuf/stubs/strutil.h
@@ -33,12 +33,13 @@
#ifndef GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
#define GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
-#include <stdlib.h>
-#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <stdlib.h>
+#include <cstring>
#include <google/protobuf/port_def.inc>
+#include <vector>
namespace google {
namespace protobuf {
@@ -118,6 +119,11 @@
str.compare(0, prefix.size(), prefix) == 0;
}
+inline bool HasPrefixString(StringPiece str, StringPiece prefix) {
+ return str.size() >= prefix.size() &&
+ memcmp(str.data(), prefix.data(), prefix.size()) == 0;
+}
+
inline string StripPrefixString(const string& str, const string& prefix) {
if (HasPrefixString(str, prefix)) {
return str.substr(prefix.size());
@@ -188,6 +194,8 @@
}
}
+inline void ToUpper(string* s) { UpperString(s); }
+
inline string ToUpper(const string& s) {
string out = s;
UpperString(&out);
diff --git a/src/google/protobuf/stubs/time.cc b/src/google/protobuf/stubs/time.cc
index a1e5e1e..64f3ceb 100644
--- a/src/google/protobuf/stubs/time.cc
+++ b/src/google/protobuf/stubs/time.cc
@@ -212,7 +212,7 @@
if (seconds < kMinTime || seconds > kMaxTime) {
return false;
}
- // It's easier to calcuate the DateTime starting from 0001-01-01T00:00:00
+ // It's easier to calculate the DateTime starting from 0001-01-01T00:00:00
seconds = seconds + kSecondsFromEraToEpoch;
int year = 1;
if (seconds >= kSecondsPer400Years) {
diff --git a/src/google/protobuf/stubs/time.h b/src/google/protobuf/stubs/time.h
index 12091de..b52f3f9 100644
--- a/src/google/protobuf/stubs/time.h
+++ b/src/google/protobuf/stubs/time.h
@@ -58,7 +58,7 @@
void PROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos);
-// Formats a time string in RFC3339 fromat.
+// Formats a time string in RFC3339 format.
//
// For example, "2015-05-20T13:29:35.120Z". For nanos, 0, 3, 6 or 9 fractional
// digits will be used depending on how many are required to represent the exact
diff --git a/src/google/protobuf/stubs/time_test.cc b/src/google/protobuf/stubs/time_test.cc
index 4dd06a6..fc72925 100644
--- a/src/google/protobuf/stubs/time_test.cc
+++ b/src/google/protobuf/stubs/time_test.cc
@@ -223,7 +223,7 @@
EXPECT_EQ("0001-01-01T00:00:00Z", FormatTime(start_time, 0));
EXPECT_EQ("9999-12-31T23:59:59Z", FormatTime(end_time, 0));
- // Make sure the nanoseconds part is formated correctly.
+ // Make sure the nanoseconds part is formatted correctly.
EXPECT_EQ("1970-01-01T00:00:00.010Z", FormatTime(0, 10000000));
EXPECT_EQ("1970-01-01T00:00:00.000010Z", FormatTime(0, 10000));
EXPECT_EQ("1970-01-01T00:00:00.000000010Z", FormatTime(0, 10));
diff --git a/src/google/protobuf/test_messages_proto2.proto b/src/google/protobuf/test_messages_proto2.proto
index f820743..1d0c33f 100644
--- a/src/google/protobuf/test_messages_proto2.proto
+++ b/src/google/protobuf/test_messages_proto2.proto
@@ -27,36 +27,6 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Test schema for proto2 messages. This test schema is used by:
//
diff --git a/src/google/protobuf/test_messages_proto3.proto b/src/google/protobuf/test_messages_proto3.proto
index 803e2c3..a10f44d 100644
--- a/src/google/protobuf/test_messages_proto3.proto
+++ b/src/google/protobuf/test_messages_proto3.proto
@@ -27,36 +27,6 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Test schema for proto3 messages. This test schema is used by:
//
diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc
index 6b33088..be1f594 100644
--- a/src/google/protobuf/text_format.cc
+++ b/src/google/protobuf/text_format.cc
@@ -101,7 +101,7 @@
printer.PrintToString(*this, &debug_string);
// Single line mode currently might have an extra space at the end.
- if (debug_string.size() > 0 && debug_string[debug_string.size() - 1] == ' ') {
+ if (!debug_string.empty() && debug_string[debug_string.size() - 1] == ' ') {
debug_string.resize(debug_string.size() - 1);
}
@@ -258,6 +258,7 @@
allow_unknown_enum_(allow_unknown_enum),
allow_field_number_(allow_field_number),
allow_partial_(allow_partial),
+ initial_recursion_limit_(recursion_limit),
recursion_limit_(recursion_limit),
had_errors_(false) {
// For backwards-compatibility with proto1, we need to allow the 'f' suffix
@@ -636,7 +637,10 @@
bool ConsumeFieldMessage(Message* message, const Reflection* reflection,
const FieldDescriptor* field) {
if (--recursion_limit_ < 0) {
- ReportError("Message is too deep");
+ ReportError(
+ StrCat("Message is too deep, the parser exceeded the "
+ "configured recursion limit of ",
+ initial_recursion_limit_, "."));
return false;
}
// If the parse information tree is not nullptr, create a nested one
@@ -668,12 +672,22 @@
// Skips the whole body of a message including the beginning delimiter and
// the ending delimiter.
bool SkipFieldMessage() {
+ if (--recursion_limit_ < 0) {
+ ReportError(
+ StrCat("Message is too deep, the parser exceeded the "
+ "configured recursion limit of ",
+ initial_recursion_limit_, "."));
+ return false;
+ }
+
std::string delimiter;
DO(ConsumeMessageDelimiter(&delimiter));
while (!LookingAt(">") && !LookingAt("}")) {
DO(SkipField());
}
DO(Consume(delimiter));
+
+ ++recursion_limit_;
return true;
}
@@ -1192,6 +1206,7 @@
const bool allow_unknown_enum_;
const bool allow_field_number_;
const bool allow_partial_;
+ const int initial_recursion_limit_;
int recursion_limit_;
bool had_errors_;
};
@@ -1670,6 +1685,11 @@
generator->PrintLiteral(" {\n");
}
}
+bool TextFormat::FastFieldValuePrinter::PrintMessageContent(
+ const Message& message, int field_index, int field_count,
+ bool single_line_mode, BaseTextGenerator* generator) const {
+ return false; // Use the default printing function.
+}
void TextFormat::FastFieldValuePrinter::PrintMessageEnd(
const Message& message, int field_index, int field_count,
bool single_line_mode, BaseTextGenerator* generator) const {
@@ -1886,12 +1906,16 @@
return !generator.failed();
}
+// Maximum recursion depth for heuristically printing out length-delimited
+// unknown fields as messages.
+static constexpr int kUnknownFieldRecursionLimit = 10;
+
bool TextFormat::Printer::PrintUnknownFields(
const UnknownFieldSet& unknown_fields,
io::ZeroCopyOutputStream* output) const {
TextGenerator generator(output, initial_indent_level_);
- PrintUnknownFields(unknown_fields, &generator);
+ PrintUnknownFields(unknown_fields, &generator, kUnknownFieldRecursionLimit);
// Output false if the generator failed internally.
return !generator.failed();
@@ -1941,7 +1965,8 @@
finder_ ? finder_->FindAnyType(message, url_prefix, full_type_name)
: DefaultFinderFindAnyType(message, url_prefix, full_type_name);
if (value_descriptor == nullptr) {
- GOOGLE_LOG(WARNING) << "Proto type " << type_url << " not found";
+ GOOGLE_LOG(WARNING) << "Can't print proto content: proto type " << type_url
+ << " not found";
return false;
}
DynamicMessageFactory factory;
@@ -1976,7 +2001,7 @@
io::ArrayInputStream input(serialized.data(), serialized.size());
unknown_fields.ParseFromZeroCopyStream(&input);
}
- PrintUnknownFields(unknown_fields, generator);
+ PrintUnknownFields(unknown_fields, generator, kUnknownFieldRecursionLimit);
return;
}
const Descriptor* descriptor = message.GetDescriptor();
@@ -2004,7 +2029,8 @@
PrintField(message, reflection, fields[i], generator);
}
if (!hide_unknown_fields_) {
- PrintUnknownFields(reflection->GetUnknownFields(message), generator);
+ PrintUnknownFields(reflection->GetUnknownFields(message), generator,
+ kUnknownFieldRecursionLimit);
}
}
@@ -2239,7 +2265,10 @@
printer->PrintMessageStart(sub_message, field_index, count,
single_line_mode_, generator);
generator->Indent();
- Print(sub_message, generator);
+ if (!printer->PrintMessageContent(sub_message, field_index, count,
+ single_line_mode_, generator)) {
+ Print(sub_message, generator);
+ }
generator->Outdent();
printer->PrintMessageEnd(sub_message, field_index, count,
single_line_mode_, generator);
@@ -2413,7 +2442,8 @@
}
void TextFormat::Printer::PrintUnknownFields(
- const UnknownFieldSet& unknown_fields, TextGenerator* generator) const {
+ const UnknownFieldSet& unknown_fields, TextGenerator* generator,
+ int recursion_budget) const {
for (int i = 0; i < unknown_fields.field_count(); i++) {
const UnknownField& field = unknown_fields.field(i);
std::string field_number = StrCat(field.number());
@@ -2456,8 +2486,15 @@
case UnknownField::TYPE_LENGTH_DELIMITED: {
generator->PrintString(field_number);
const std::string& value = field.length_delimited();
+ // We create a CodedInputStream so that we can adhere to our recursion
+ // budget when we attempt to parse the data. UnknownFieldSet parsing is
+ // recursive because of groups.
+ io::CodedInputStream input_stream(
+ reinterpret_cast<const uint8*>(value.data()), value.size());
+ input_stream.SetRecursionLimit(recursion_budget);
UnknownFieldSet embedded_unknown_fields;
- if (!value.empty() && embedded_unknown_fields.ParseFromString(value)) {
+ if (!value.empty() && recursion_budget > 0 &&
+ embedded_unknown_fields.ParseFromCodedStream(&input_stream)) {
// This field is parseable as a Message.
// So it is probably an embedded message.
if (single_line_mode_) {
@@ -2466,7 +2503,8 @@
generator->PrintLiteral(" {\n");
generator->Indent();
}
- PrintUnknownFields(embedded_unknown_fields, generator);
+ PrintUnknownFields(embedded_unknown_fields, generator,
+ recursion_budget - 1);
if (single_line_mode_) {
generator->PrintLiteral("} ");
} else {
@@ -2474,8 +2512,8 @@
generator->PrintLiteral("}\n");
}
} else {
- // This field is not parseable as a Message.
- // So it is probably just a plain string.
+ // This field is not parseable as a Message (or we ran out of
+ // recursion budget). So it is probably just a plain string.
generator->PrintLiteral(": \"");
generator->PrintString(CEscape(value));
if (single_line_mode_) {
@@ -2494,7 +2532,10 @@
generator->PrintLiteral(" {\n");
generator->Indent();
}
- PrintUnknownFields(field.group(), generator);
+ // For groups, we recurse without checking the budget. This is OK,
+ // because if the groups were too deeply nested then we would have
+ // already rejected the message when we originally parsed it.
+ PrintUnknownFields(field.group(), generator, recursion_budget - 1);
if (single_line_mode_) {
generator->PrintLiteral("} ");
} else {
diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h
index ab34cd8..26c4afb 100644
--- a/src/google/protobuf/text_format.h
+++ b/src/google/protobuf/text_format.h
@@ -149,6 +149,14 @@
virtual void PrintMessageStart(const Message& message, int field_index,
int field_count, bool single_line_mode,
BaseTextGenerator* generator) const;
+ // Allows to override the logic on how to print the content of a message.
+ // Return false to use the default printing logic. Note that it is legal for
+ // this function to print something and then return false to use the default
+ // content printing (although at that point it would behave similarly to
+ // PrintMessageStart).
+ virtual bool PrintMessageContent(const Message& message, int field_index,
+ int field_count, bool single_line_mode,
+ BaseTextGenerator* generator) const;
virtual void PrintMessageEnd(const Message& message, int field_index,
int field_count, bool single_line_mode,
BaseTextGenerator* generator) const;
@@ -391,9 +399,10 @@
// Print the fields in an UnknownFieldSet. They are printed by tag number
// only. Embedded messages are heuristically identified by attempting to
- // parse them.
+ // parse them (subject to the recursion budget).
void PrintUnknownFields(const UnknownFieldSet& unknown_fields,
- TextGenerator* generator) const;
+ TextGenerator* generator,
+ int recursion_budget) const;
bool PrintAny(const Message& message, TextGenerator* generator) const;
diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc
index 3bb20b7..9e7479e 100644
--- a/src/google/protobuf/text_format_unittest.cc
+++ b/src/google/protobuf/text_format_unittest.cc
@@ -55,9 +55,9 @@
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/port_def.inc>
@@ -356,6 +356,39 @@
text);
}
+TEST_F(TextFormatTest, PrintDeeplyNestedUnknownMessage) {
+ // Create a deeply nested message.
+ static constexpr int kNestingDepth = 25000;
+ static constexpr int kUnknownFieldNumber = 1;
+ std::vector<int> lengths;
+ lengths.reserve(kNestingDepth);
+ lengths.push_back(0);
+ for (int i = 0; i < kNestingDepth - 1; ++i) {
+ lengths.push_back(
+ internal::WireFormatLite::TagSize(
+ kUnknownFieldNumber, internal::WireFormatLite::TYPE_BYTES) +
+ internal::WireFormatLite::LengthDelimitedSize(lengths.back()));
+ }
+ std::string serialized;
+ {
+ io::StringOutputStream zero_copy_stream(&serialized);
+ io::CodedOutputStream coded_stream(&zero_copy_stream);
+ for (int i = kNestingDepth - 1; i >= 0; --i) {
+ internal::WireFormatLite::WriteTag(
+ kUnknownFieldNumber,
+ internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, &coded_stream);
+ coded_stream.WriteVarint32(lengths[i]);
+ }
+ }
+
+ // Parse the data and verify that we can print it without overflowing the
+ // stack.
+ unittest::TestEmptyMessage message;
+ ASSERT_TRUE(message.ParseFromString(serialized));
+ std::string text;
+ EXPECT_TRUE(TextFormat::PrintToString(message, &text));
+}
+
TEST_F(TextFormatTest, PrintMessageWithIndent) {
// Test adding an initial indent to printing.
@@ -539,6 +572,54 @@
text);
}
+class CustomMessageContentFieldValuePrinter
+ : public TextFormat::FastFieldValuePrinter {
+ public:
+ bool PrintMessageContent(
+ const Message& message, int field_index, int field_count,
+ bool single_line_mode,
+ TextFormat::BaseTextGenerator* generator) const override {
+ if (message.ByteSizeLong() > 0) {
+ generator->PrintString(
+ strings::Substitute("# REDACTED, $0 bytes\n", message.ByteSizeLong()));
+ }
+ return true;
+ }
+};
+
+TEST_F(TextFormatTest, CustomPrinterForMessageContent) {
+ protobuf_unittest::TestAllTypes message;
+ message.mutable_optional_nested_message();
+ message.mutable_optional_import_message()->set_d(42);
+ message.add_repeated_nested_message();
+ message.add_repeated_nested_message();
+ message.add_repeated_import_message()->set_d(43);
+ message.add_repeated_import_message()->set_d(44);
+ TextFormat::Printer printer;
+ CustomMessageContentFieldValuePrinter my_field_printer;
+ printer.SetDefaultFieldValuePrinter(
+ new CustomMessageContentFieldValuePrinter());
+ std::string text;
+ printer.PrintToString(message, &text);
+ EXPECT_EQ(
+ "optional_nested_message {\n"
+ "}\n"
+ "optional_import_message {\n"
+ " # REDACTED, 2 bytes\n"
+ "}\n"
+ "repeated_nested_message {\n"
+ "}\n"
+ "repeated_nested_message {\n"
+ "}\n"
+ "repeated_import_message {\n"
+ " # REDACTED, 2 bytes\n"
+ "}\n"
+ "repeated_import_message {\n"
+ " # REDACTED, 2 bytes\n"
+ "}\n",
+ text);
+}
+
class CustomMultilineCommentPrinter : public TextFormat::FieldValuePrinter {
public:
virtual std::string PrintMessageStart(const Message& message, int field_index,
@@ -726,8 +807,8 @@
TEST_F(TextFormatTest, ParseEnumFieldFromNumber) {
// Create a parse string with a numerical value for an enum field.
- std::string parse_string = strings::Substitute("optional_nested_enum: $0",
- unittest::TestAllTypes::BAZ);
+ std::string parse_string =
+ strings::Substitute("optional_nested_enum: $0", unittest::TestAllTypes::BAZ);
EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
EXPECT_TRUE(proto_.has_optional_nested_enum());
EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.optional_nested_enum());
@@ -776,7 +857,7 @@
}
TEST_F(TextFormatTest, ParseStringEscape) {
- // Create a parse string with escpaed characters in it.
+ // Create a parse string with escaped characters in it.
std::string parse_string =
"optional_string: " + kEscapeTestStringEscaped + "\n";
@@ -1365,7 +1446,7 @@
// implements ErrorCollector -------------------------------------
void AddError(int line, int column, const std::string& message) {
strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", line + 1, column + 1,
- message);
+ message);
}
void AddWarning(int line, int column, const std::string& message) {
@@ -1830,7 +1911,33 @@
input = strings::Substitute(format, input);
parser_.SetRecursionLimit(100);
- ExpectMessage(input, "Message is too deep", 1, 908, &message, false);
+ ExpectMessage(input,
+ "Message is too deep, the parser exceeded the configured "
+ "recursion limit of 100.",
+ 1, 908, &message, false);
+
+ parser_.SetRecursionLimit(101);
+ ExpectSuccessAndTree(input, &message, nullptr);
+}
+
+TEST_F(TextFormatParserTest, SetRecursionLimitUnknownField) {
+ const char* format = "unknown_child: { $0 }";
+ std::string input;
+ for (int i = 0; i < 100; ++i) input = strings::Substitute(format, input);
+
+ parser_.AllowUnknownField(true);
+
+ unittest::NestedTestAllTypes message;
+ ExpectSuccessAndTree(input, &message, nullptr);
+
+ input = strings::Substitute(format, input);
+ parser_.SetRecursionLimit(100);
+ ExpectMessage(
+ input,
+ "WARNING:Message type \"protobuf_unittest.NestedTestAllTypes\" has no "
+ "field named \"unknown_child\".\n1:1716: Message is too deep, the parser "
+ "exceeded the configured recursion limit of 100.",
+ 1, 14, &message, false);
parser_.SetRecursionLimit(101);
ExpectSuccessAndTree(input, &message, nullptr);
diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc
index 24a299e..8b27210 100644
--- a/src/google/protobuf/timestamp.pb.cc
+++ b/src/google/protobuf/timestamp.pb.cc
@@ -69,16 +69,15 @@
&scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftimestamp_2eproto = {
- &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto, "google/protobuf/timestamp.proto", 231,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto, "google/protobuf/timestamp.proto", 231,
&descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once, descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_sccs, descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto, file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2ftimestamp_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ftimestamp_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2ftimestamp_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ftimestamp_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -89,22 +88,15 @@
public:
};
-Timestamp::Timestamp()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Timestamp)
-}
Timestamp::Timestamp(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp)
}
Timestamp::Timestamp(const Timestamp& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::memcpy(&seconds_, &from.seconds_,
static_cast<size_t>(reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
@@ -120,10 +112,11 @@
Timestamp::~Timestamp() {
// @@protoc_insertion_point(destructor:google.protobuf.Timestamp)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Timestamp::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void Timestamp::ArenaDtor(void* object) {
@@ -150,12 +143,12 @@
::memset(&seconds_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&nanos_) -
reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_));
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Timestamp::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -164,14 +157,14 @@
// int64 seconds = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// int32 nanos = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
- nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -181,7 +174,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -215,7 +210,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Timestamp)
return target;
@@ -270,7 +265,7 @@
void Timestamp::MergeFrom(const Timestamp& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Timestamp)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -302,9 +297,13 @@
void Timestamp::InternalSwap(Timestamp* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- swap(seconds_, other->seconds_);
- swap(nanos_, other->nanos_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Timestamp, nanos_)
+ + sizeof(Timestamp::nanos_)
+ - PROTOBUF_FIELD_OFFSET(Timestamp, seconds_)>(
+ reinterpret_cast<char*>(&seconds_),
+ reinterpret_cast<char*>(&other->seconds_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Timestamp::GetMetadata() const {
diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h
index 497db63..943c5ac 100644
--- a/src/google/protobuf/timestamp.pb.h
+++ b/src/google/protobuf/timestamp.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -66,10 +66,10 @@
// ===================================================================
-class PROTOBUF_EXPORT Timestamp :
+class PROTOBUF_EXPORT Timestamp PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Timestamp) */ {
public:
- Timestamp();
+ inline Timestamp() : Timestamp(nullptr) {};
virtual ~Timestamp();
Timestamp(const Timestamp& from);
@@ -83,7 +83,7 @@
return *this;
}
inline Timestamp& operator=(Timestamp&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -91,12 +91,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -121,7 +115,7 @@
}
inline void Swap(Timestamp* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -129,7 +123,7 @@
}
void UnsafeArenaSwap(Timestamp* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -169,13 +163,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -217,7 +204,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc
index 0db802c..8da70ec 100644
--- a/src/google/protobuf/type.pb.cc
+++ b/src/google/protobuf/type.pb.cc
@@ -247,16 +247,15 @@
&scc_info_Type_google_2fprotobuf_2ftype_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2ftype_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2ftype_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftype_2eproto = {
- &descriptor_table_google_2fprotobuf_2ftype_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2ftype_2eproto, "google/protobuf/type.proto", 1594,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2ftype_2eproto, "google/protobuf/type.proto", 1594,
&descriptor_table_google_2fprotobuf_2ftype_2eproto_once, descriptor_table_google_2fprotobuf_2ftype_2eproto_sccs, descriptor_table_google_2fprotobuf_2ftype_2eproto_deps, 5, 2,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2ftype_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2ftype_2eproto, 5, file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto, file_level_service_descriptors_google_2fprotobuf_2ftype_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2ftype_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ftype_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2ftype_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ftype_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Field_Kind_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2ftype_2eproto);
@@ -368,33 +367,14 @@
Type::_Internal::source_context(const Type* msg) {
return *msg->source_context_;
}
-void Type::unsafe_arena_set_allocated_source_context(
- PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
- if (GetArenaNoVirtual() == nullptr) {
- delete source_context_;
- }
- source_context_ = source_context;
- if (source_context) {
-
- } else {
-
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.source_context)
-}
void Type::clear_source_context() {
- if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) {
+ if (GetArena() == nullptr && source_context_ != nullptr) {
delete source_context_;
}
source_context_ = nullptr;
}
-Type::Type()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Type)
-}
Type::Type(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
fields_(arena),
oneofs_(arena),
options_(arena) {
@@ -404,15 +384,14 @@
}
Type::Type(const Type& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
fields_(from.fields_),
oneofs_(from.oneofs_),
options_(from.options_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_source_context()) {
source_context_ = new PROTOBUF_NAMESPACE_ID::SourceContext(*from.source_context_);
@@ -434,10 +413,11 @@
Type::~Type() {
// @@protoc_insertion_point(destructor:google.protobuf.Type)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Type::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete source_context_;
}
@@ -466,18 +446,18 @@
fields_.Clear();
oneofs_.Clear();
options_.Clear();
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) {
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ if (GetArena() == nullptr && source_context_ != nullptr) {
delete source_context_;
}
source_context_ = nullptr;
syntax_ = 0;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Type::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -540,7 +520,7 @@
// .google.protobuf.Syntax syntax = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_syntax(static_cast<PROTOBUF_NAMESPACE_ID::Syntax>(val));
} else goto handle_unusual;
@@ -551,7 +531,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -624,7 +606,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Type)
return target;
@@ -707,7 +689,7 @@
void Type::MergeFrom(const Type& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Type)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -745,14 +727,17 @@
void Type::InternalSwap(Type* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
fields_.InternalSwap(&other->fields_);
oneofs_.InternalSwap(&other->oneofs_);
options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(source_context_, other->source_context_);
- swap(syntax_, other->syntax_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Type, syntax_)
+ + sizeof(Type::syntax_)
+ - PROTOBUF_FIELD_OFFSET(Type, source_context_)>(
+ reinterpret_cast<char*>(&source_context_),
+ reinterpret_cast<char*>(&other->source_context_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Type::GetMetadata() const {
@@ -768,14 +753,8 @@
public:
};
-Field::Field()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Field)
-}
Field::Field(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
options_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -783,28 +762,27 @@
}
Field::Field(const Field& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
options_(from.options_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_type_url().empty()) {
type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_type_url(),
- GetArenaNoVirtual());
+ GetArena());
}
json_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_json_name().empty()) {
json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_json_name(),
- GetArenaNoVirtual());
+ GetArena());
}
default_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_default_value().empty()) {
default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_default_value(),
- GetArenaNoVirtual());
+ GetArena());
}
::memcpy(&kind_, &from.kind_,
static_cast<size_t>(reinterpret_cast<char*>(&packed_) -
@@ -826,10 +804,11 @@
Field::~Field() {
// @@protoc_insertion_point(destructor:google.protobuf.Field)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Field::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
json_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
@@ -858,19 +837,19 @@
(void) cached_has_bits;
options_.Clear();
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- json_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- default_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ json_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ default_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
::memset(&kind_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&packed_) -
reinterpret_cast<char*>(&kind_)) + sizeof(packed_));
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Field::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -879,7 +858,7 @@
// .google.protobuf.Field.Kind kind = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_kind(static_cast<PROTOBUF_NAMESPACE_ID::Field_Kind>(val));
} else goto handle_unusual;
@@ -887,7 +866,7 @@
// .google.protobuf.Field.Cardinality cardinality = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_cardinality(static_cast<PROTOBUF_NAMESPACE_ID::Field_Cardinality>(val));
} else goto handle_unusual;
@@ -895,7 +874,7 @@
// int32 number = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
- number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -920,14 +899,14 @@
// int32 oneof_index = 7;
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) {
- oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// bool packed = 8;
case 8:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) {
- packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -967,7 +946,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1069,7 +1050,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Field)
return target;
@@ -1176,7 +1157,7 @@
void Field::MergeFrom(const Field& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Field)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1230,21 +1211,18 @@
void Field::InternalSwap(Field* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- type_url_.Swap(&other->type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- json_name_.Swap(&other->json_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- default_value_.Swap(&other->default_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(kind_, other->kind_);
- swap(cardinality_, other->cardinality_);
- swap(number_, other->number_);
- swap(oneof_index_, other->oneof_index_);
- swap(packed_, other->packed_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ type_url_.Swap(&other->type_url_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ json_name_.Swap(&other->json_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ default_value_.Swap(&other->default_value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Field, packed_)
+ + sizeof(Field::packed_)
+ - PROTOBUF_FIELD_OFFSET(Field, kind_)>(
+ reinterpret_cast<char*>(&kind_),
+ reinterpret_cast<char*>(&other->kind_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Field::GetMetadata() const {
@@ -1267,33 +1245,14 @@
Enum::_Internal::source_context(const Enum* msg) {
return *msg->source_context_;
}
-void Enum::unsafe_arena_set_allocated_source_context(
- PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
- if (GetArenaNoVirtual() == nullptr) {
- delete source_context_;
- }
- source_context_ = source_context;
- if (source_context) {
-
- } else {
-
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.source_context)
-}
void Enum::clear_source_context() {
- if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) {
+ if (GetArena() == nullptr && source_context_ != nullptr) {
delete source_context_;
}
source_context_ = nullptr;
}
-Enum::Enum()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Enum)
-}
Enum::Enum(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
enumvalue_(arena),
options_(arena) {
SharedCtor();
@@ -1302,14 +1261,13 @@
}
Enum::Enum(const Enum& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
enumvalue_(from.enumvalue_),
options_(from.options_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_source_context()) {
source_context_ = new PROTOBUF_NAMESPACE_ID::SourceContext(*from.source_context_);
@@ -1331,10 +1289,11 @@
Enum::~Enum() {
// @@protoc_insertion_point(destructor:google.protobuf.Enum)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Enum::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete source_context_;
}
@@ -1362,18 +1321,18 @@
enumvalue_.Clear();
options_.Clear();
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- if (GetArenaNoVirtual() == nullptr && source_context_ != nullptr) {
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ if (GetArena() == nullptr && source_context_ != nullptr) {
delete source_context_;
}
source_context_ = nullptr;
syntax_ = 0;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Enum::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1422,7 +1381,7 @@
// .google.protobuf.Syntax syntax = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
- ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
_internal_set_syntax(static_cast<PROTOBUF_NAMESPACE_ID::Syntax>(val));
} else goto handle_unusual;
@@ -1433,7 +1392,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1496,7 +1457,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Enum)
return target;
@@ -1571,7 +1532,7 @@
void Enum::MergeFrom(const Enum& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Enum)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1608,13 +1569,16 @@
void Enum::InternalSwap(Enum* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
enumvalue_.InternalSwap(&other->enumvalue_);
options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
- swap(source_context_, other->source_context_);
- swap(syntax_, other->syntax_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ ::PROTOBUF_NAMESPACE_ID::internal::memswap<
+ PROTOBUF_FIELD_OFFSET(Enum, syntax_)
+ + sizeof(Enum::syntax_)
+ - PROTOBUF_FIELD_OFFSET(Enum, source_context_)>(
+ reinterpret_cast<char*>(&source_context_),
+ reinterpret_cast<char*>(&other->source_context_));
}
::PROTOBUF_NAMESPACE_ID::Metadata Enum::GetMetadata() const {
@@ -1630,14 +1594,8 @@
public:
};
-EnumValue::EnumValue()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.EnumValue)
-}
EnumValue::EnumValue(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena),
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
options_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
@@ -1645,13 +1603,12 @@
}
EnumValue::EnumValue(const EnumValue& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr),
options_(from.options_) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
number_ = from.number_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValue)
@@ -1666,10 +1623,11 @@
EnumValue::~EnumValue() {
// @@protoc_insertion_point(destructor:google.protobuf.EnumValue)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void EnumValue::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
@@ -1695,14 +1653,14 @@
(void) cached_has_bits;
options_.Clear();
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
number_ = 0;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* EnumValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1720,7 +1678,7 @@
// int32 number = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
- number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -1742,7 +1700,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1788,7 +1748,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValue)
return target;
@@ -1850,7 +1810,7 @@
void EnumValue::MergeFrom(const EnumValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValue)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1883,10 +1843,9 @@
void EnumValue::InternalSwap(EnumValue* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
options_.InternalSwap(&other->options_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(number_, other->number_);
}
@@ -1910,45 +1869,25 @@
Option::_Internal::value(const Option* msg) {
return *msg->value_;
}
-void Option::unsafe_arena_set_allocated_value(
- PROTOBUF_NAMESPACE_ID::Any* value) {
- if (GetArenaNoVirtual() == nullptr) {
- delete value_;
- }
- value_ = value;
- if (value) {
-
- } else {
-
- }
- // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.value)
-}
void Option::clear_value() {
- if (GetArenaNoVirtual() == nullptr && value_ != nullptr) {
+ if (GetArena() == nullptr && value_ != nullptr) {
delete value_;
}
value_ = nullptr;
}
-Option::Option()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Option)
-}
Option::Option(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Option)
}
Option::Option(const Option& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_name().empty()) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_name(),
- GetArenaNoVirtual());
+ GetArena());
}
if (from._internal_has_value()) {
value_ = new PROTOBUF_NAMESPACE_ID::Any(*from.value_);
@@ -1967,10 +1906,11 @@
Option::~Option() {
// @@protoc_insertion_point(destructor:google.protobuf.Option)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Option::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete value_;
}
@@ -1996,17 +1936,17 @@
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- if (GetArenaNoVirtual() == nullptr && value_ != nullptr) {
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ if (GetArena() == nullptr && value_ != nullptr) {
delete value_;
}
value_ = nullptr;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Option::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -2034,7 +1974,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -2074,7 +2016,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Option)
return target;
@@ -2129,7 +2071,7 @@
void Option::MergeFrom(const Option& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Option)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -2161,9 +2103,8 @@
void Option::InternalSwap(Option* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(value_, other->value_);
}
diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h
index 679e132..0a83069 100644
--- a/src/google/protobuf/type.pb.h
+++ b/src/google/protobuf/type.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -179,10 +179,10 @@
}
// ===================================================================
-class PROTOBUF_EXPORT Type :
+class PROTOBUF_EXPORT Type PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Type) */ {
public:
- Type();
+ inline Type() : Type(nullptr) {};
virtual ~Type();
Type(const Type& from);
@@ -196,7 +196,7 @@
return *this;
}
inline Type& operator=(Type&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -204,12 +204,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -234,7 +228,7 @@
}
inline void Swap(Type* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -242,7 +236,7 @@
}
void UnsafeArenaSwap(Type* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -282,13 +276,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -428,7 +415,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -443,10 +429,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Field :
+class PROTOBUF_EXPORT Field PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Field) */ {
public:
- Field();
+ inline Field() : Field(nullptr) {};
virtual ~Field();
Field(const Field& from);
@@ -460,7 +446,7 @@
return *this;
}
inline Field& operator=(Field&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -468,12 +454,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -498,7 +478,7 @@
}
inline void Swap(Field* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -506,7 +486,7 @@
}
void UnsafeArenaSwap(Field* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -546,13 +526,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -845,7 +818,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -864,10 +836,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Enum :
+class PROTOBUF_EXPORT Enum PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Enum) */ {
public:
- Enum();
+ inline Enum() : Enum(nullptr) {};
virtual ~Enum();
Enum(const Enum& from);
@@ -881,7 +853,7 @@
return *this;
}
inline Enum& operator=(Enum&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -889,12 +861,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -919,7 +885,7 @@
}
inline void Swap(Enum* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -927,7 +893,7 @@
}
void UnsafeArenaSwap(Enum* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -967,13 +933,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1088,7 +1047,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1102,10 +1060,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT EnumValue :
+class PROTOBUF_EXPORT EnumValue PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValue) */ {
public:
- EnumValue();
+ inline EnumValue() : EnumValue(nullptr) {};
virtual ~EnumValue();
EnumValue(const EnumValue& from);
@@ -1119,7 +1077,7 @@
return *this;
}
inline EnumValue& operator=(EnumValue&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1127,12 +1085,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1157,7 +1109,7 @@
}
inline void Swap(EnumValue* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1165,7 +1117,7 @@
}
void UnsafeArenaSwap(EnumValue* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1205,13 +1157,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1288,7 +1233,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1300,10 +1244,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Option :
+class PROTOBUF_EXPORT Option PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Option) */ {
public:
- Option();
+ inline Option() : Option(nullptr) {};
virtual ~Option();
Option(const Option& from);
@@ -1317,7 +1261,7 @@
return *this;
}
inline Option& operator=(Option&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1325,12 +1269,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1355,7 +1293,7 @@
}
inline void Swap(Option* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1363,7 +1301,7 @@
}
void UnsafeArenaSwap(Option* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1403,13 +1341,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1476,7 +1407,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1498,7 +1428,7 @@
// string name = 1;
inline void Type::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Type::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Type.name)
@@ -1517,36 +1447,35 @@
}
inline void Type::_internal_set_name(const std::string& value) {
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Type::set_name(std::string&& value) {
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Type.name)
}
inline void Type::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Type.name)
}
inline void Type::set_name(const char* value,
size_t size) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Type.name)
}
inline std::string* Type::_internal_mutable_name() {
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Type::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Type.name)
-
- return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Type::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -1555,26 +1484,26 @@
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.name)
}
inline std::string* Type::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void Type::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
} else {
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.name)
}
@@ -1746,9 +1675,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.Type.source_context)
return _internal_source_context();
}
+inline void Type::unsafe_arena_set_allocated_source_context(
+ PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_);
+ }
+ source_context_ = source_context;
+ if (source_context) {
+
+ } else {
+
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.source_context)
+}
inline PROTOBUF_NAMESPACE_ID::SourceContext* Type::release_source_context() {
- auto temp = unsafe_arena_release_source_context();
- if (GetArenaNoVirtual() != nullptr) {
+
+ PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_;
+ source_context_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -1763,7 +1707,7 @@
inline PROTOBUF_NAMESPACE_ID::SourceContext* Type::_internal_mutable_source_context() {
if (source_context_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceContext>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceContext>(GetArena());
source_context_ = p;
}
return source_context_;
@@ -1773,12 +1717,13 @@
return _internal_mutable_source_context();
}
inline void Type::set_allocated_source_context(PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_);
}
if (source_context) {
- ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
+ ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
+ reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context)->GetArena();
if (message_arena != submessage_arena) {
source_context = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, source_context, submessage_arena);
@@ -1877,7 +1822,7 @@
// string name = 4;
inline void Field::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Field::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.name)
@@ -1896,36 +1841,35 @@
}
inline void Field::_internal_set_name(const std::string& value) {
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Field::set_name(std::string&& value) {
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.name)
}
inline void Field::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.name)
}
inline void Field::set_name(const char* value,
size_t size) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.name)
}
inline std::string* Field::_internal_mutable_name() {
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Field::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.name)
-
- return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Field::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -1934,32 +1878,32 @@
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.name)
}
inline std::string* Field::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void Field::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
} else {
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.name)
}
// string type_url = 6;
inline void Field::clear_type_url() {
- type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ type_url_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Field::type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.type_url)
@@ -1978,36 +1922,35 @@
}
inline void Field::_internal_set_type_url(const std::string& value) {
- type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Field::set_type_url(std::string&& value) {
type_url_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.type_url)
}
inline void Field::set_type_url(const char* value) {
GOOGLE_DCHECK(value != nullptr);
type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.type_url)
}
inline void Field::set_type_url(const char* value,
size_t size) {
type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.type_url)
}
inline std::string* Field::_internal_mutable_type_url() {
- return type_url_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return type_url_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Field::release_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.type_url)
-
- return type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Field::set_allocated_type_url(std::string* type_url) {
if (type_url != nullptr) {
@@ -2016,26 +1959,26 @@
}
type_url_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_url,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.type_url)
}
inline std::string* Field::unsafe_arena_release_type_url() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.type_url)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return type_url_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void Field::unsafe_arena_set_allocated_type_url(
std::string* type_url) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (type_url != nullptr) {
} else {
}
type_url_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- type_url, GetArenaNoVirtual());
+ type_url, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.type_url)
}
@@ -2120,7 +2063,7 @@
// string json_name = 10;
inline void Field::clear_json_name() {
- json_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ json_name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Field::json_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.json_name)
@@ -2139,36 +2082,35 @@
}
inline void Field::_internal_set_json_name(const std::string& value) {
- json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Field::set_json_name(std::string&& value) {
json_name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.json_name)
}
inline void Field::set_json_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.json_name)
}
inline void Field::set_json_name(const char* value,
size_t size) {
json_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.json_name)
}
inline std::string* Field::_internal_mutable_json_name() {
- return json_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return json_name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Field::release_json_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.json_name)
-
- return json_name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return json_name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Field::set_allocated_json_name(std::string* json_name) {
if (json_name != nullptr) {
@@ -2177,32 +2119,32 @@
}
json_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), json_name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.json_name)
}
inline std::string* Field::unsafe_arena_release_json_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.json_name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return json_name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void Field::unsafe_arena_set_allocated_json_name(
std::string* json_name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (json_name != nullptr) {
} else {
}
json_name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- json_name, GetArenaNoVirtual());
+ json_name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.json_name)
}
// string default_value = 11;
inline void Field::clear_default_value() {
- default_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ default_value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Field::default_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.default_value)
@@ -2221,36 +2163,35 @@
}
inline void Field::_internal_set_default_value(const std::string& value) {
- default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Field::set_default_value(std::string&& value) {
default_value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Field.default_value)
}
inline void Field::set_default_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.default_value)
}
inline void Field::set_default_value(const char* value,
size_t size) {
default_value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.default_value)
}
inline std::string* Field::_internal_mutable_default_value() {
- return default_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return default_value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Field::release_default_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.default_value)
-
- return default_value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return default_value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Field::set_allocated_default_value(std::string* default_value) {
if (default_value != nullptr) {
@@ -2259,26 +2200,26 @@
}
default_value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), default_value,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.default_value)
}
inline std::string* Field::unsafe_arena_release_default_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.default_value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return default_value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void Field::unsafe_arena_set_allocated_default_value(
std::string* default_value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (default_value != nullptr) {
} else {
}
default_value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- default_value, GetArenaNoVirtual());
+ default_value, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.default_value)
}
@@ -2288,7 +2229,7 @@
// string name = 1;
inline void Enum::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Enum::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Enum.name)
@@ -2307,36 +2248,35 @@
}
inline void Enum::_internal_set_name(const std::string& value) {
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Enum::set_name(std::string&& value) {
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Enum.name)
}
inline void Enum::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Enum.name)
}
inline void Enum::set_name(const char* value,
size_t size) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Enum.name)
}
inline std::string* Enum::_internal_mutable_name() {
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Enum::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Enum.name)
-
- return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Enum::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -2345,26 +2285,26 @@
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.name)
}
inline std::string* Enum::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void Enum::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
} else {
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.name)
}
@@ -2462,9 +2402,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.Enum.source_context)
return _internal_source_context();
}
+inline void Enum::unsafe_arena_set_allocated_source_context(
+ PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_);
+ }
+ source_context_ = source_context;
+ if (source_context) {
+
+ } else {
+
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.source_context)
+}
inline PROTOBUF_NAMESPACE_ID::SourceContext* Enum::release_source_context() {
- auto temp = unsafe_arena_release_source_context();
- if (GetArenaNoVirtual() != nullptr) {
+
+ PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_;
+ source_context_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -2479,7 +2434,7 @@
inline PROTOBUF_NAMESPACE_ID::SourceContext* Enum::_internal_mutable_source_context() {
if (source_context_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceContext>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::SourceContext>(GetArena());
source_context_ = p;
}
return source_context_;
@@ -2489,12 +2444,13 @@
return _internal_mutable_source_context();
}
inline void Enum::set_allocated_source_context(PROTOBUF_NAMESPACE_ID::SourceContext* source_context) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_);
}
if (source_context) {
- ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
+ ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
+ reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context)->GetArena();
if (message_arena != submessage_arena) {
source_context = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, source_context, submessage_arena);
@@ -2533,7 +2489,7 @@
// string name = 1;
inline void EnumValue::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& EnumValue::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValue.name)
@@ -2552,36 +2508,35 @@
}
inline void EnumValue::_internal_set_name(const std::string& value) {
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void EnumValue::set_name(std::string&& value) {
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumValue.name)
}
inline void EnumValue::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumValue.name)
}
inline void EnumValue::set_name(const char* value,
size_t size) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValue.name)
}
inline std::string* EnumValue::_internal_mutable_name() {
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* EnumValue::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValue.name)
-
- return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void EnumValue::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -2590,26 +2545,26 @@
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValue.name)
}
inline std::string* EnumValue::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValue.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void EnumValue::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
} else {
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValue.name)
}
@@ -2678,7 +2633,7 @@
// string name = 1;
inline void Option::clear_name() {
- name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ name_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& Option::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Option.name)
@@ -2697,36 +2652,35 @@
}
inline void Option::_internal_set_name(const std::string& value) {
- name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void Option::set_name(std::string&& value) {
name_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Option.name)
}
inline void Option::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.Option.name)
}
inline void Option::set_name(const char* value,
size_t size) {
name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Option.name)
}
inline std::string* Option::_internal_mutable_name() {
- return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* Option::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Option.name)
-
- return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Option::set_allocated_name(std::string* name) {
if (name != nullptr) {
@@ -2735,26 +2689,26 @@
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.name)
}
inline std::string* Option::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.name)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return name_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void Option::unsafe_arena_set_allocated_name(
std::string* name) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (name != nullptr) {
} else {
}
name_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- name, GetArenaNoVirtual());
+ name, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.name)
}
@@ -2774,9 +2728,24 @@
// @@protoc_insertion_point(field_get:google.protobuf.Option.value)
return _internal_value();
}
+inline void Option::unsafe_arena_set_allocated_value(
+ PROTOBUF_NAMESPACE_ID::Any* value) {
+ if (GetArena() == nullptr) {
+ delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(value_);
+ }
+ value_ = value;
+ if (value) {
+
+ } else {
+
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.value)
+}
inline PROTOBUF_NAMESPACE_ID::Any* Option::release_value() {
- auto temp = unsafe_arena_release_value();
- if (GetArenaNoVirtual() != nullptr) {
+
+ PROTOBUF_NAMESPACE_ID::Any* temp = value_;
+ value_ = nullptr;
+ if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
@@ -2791,7 +2760,7 @@
inline PROTOBUF_NAMESPACE_ID::Any* Option::_internal_mutable_value() {
if (value_ == nullptr) {
- auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::Any>(GetArenaNoVirtual());
+ auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::Any>(GetArena());
value_ = p;
}
return value_;
@@ -2801,12 +2770,13 @@
return _internal_mutable_value();
}
inline void Option::set_allocated_value(PROTOBUF_NAMESPACE_ID::Any* value) {
- ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaNoVirtual();
+ ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(value_);
}
if (value) {
- ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = nullptr;
+ ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
+ reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(value)->GetArena();
if (message_arena != submessage_arena) {
value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, value, submessage_arena);
diff --git a/src/google/protobuf/unittest.proto b/src/google/protobuf/unittest.proto
index c92bd30..a4d5045 100644
--- a/src/google/protobuf/unittest.proto
+++ b/src/google/protobuf/unittest.proto
@@ -182,7 +182,7 @@
}
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
optional NestedTestAllTypes child = 1;
optional TestAllTypes payload = 2;
diff --git a/src/google/protobuf/unittest_custom_options.proto b/src/google/protobuf/unittest_custom_options.proto
index 218447e..50bb996 100644
--- a/src/google/protobuf/unittest_custom_options.proto
+++ b/src/google/protobuf/unittest_custom_options.proto
@@ -38,8 +38,8 @@
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
-option cc_generic_services = true; // auto-added
-option java_generic_services = true; // auto-added
+option cc_generic_services = true; // auto-added
+option java_generic_services = true; // auto-added
option py_generic_services = true;
// A custom file option (defined below).
@@ -51,7 +51,6 @@
// that the generated code doesn't depend on being in the proto2 namespace.
package protobuf_unittest;
-
// Some simple test custom options of various types.
extend google.protobuf.FileOptions {
@@ -66,7 +65,7 @@
optional fixed64 field_opt1 = 7740936;
// This is useful for testing that we correctly register default values for
// extension options.
- optional int32 field_opt2 = 7753913 [default=42];
+ optional int32 field_opt2 = 7753913 [default = 42];
}
extend google.protobuf.OneofOptions {
@@ -98,14 +97,13 @@
// regular options, to make sure they interact nicely).
message TestMessageWithCustomOptions {
option message_set_wire_format = false;
-
option (message_opt1) = -56;
- optional string field1 = 1 [ctype=CORD,
- (field_opt1)=8765432109];
+ optional string field1 = 1 [ctype = CORD, (field_opt1) = 8765432109];
oneof AnOneof {
option (oneof_opt1) = -99;
+
int32 oneof_field = 2;
}
@@ -117,20 +115,15 @@
}
}
-
// A test RPC service with custom options at all possible locations (and also
// some regular options, to make sure they interact nicely).
-message CustomOptionFooRequest {
-}
+message CustomOptionFooRequest {}
-message CustomOptionFooResponse {
-}
+message CustomOptionFooResponse {}
-message CustomOptionFooClientMessage {
-}
+message CustomOptionFooClientMessage {}
-message CustomOptionFooServerMessage {
-}
+message CustomOptionFooServerMessage {}
service TestServiceWithCustomOptions {
option (service_opt1) = -9876543210;
@@ -140,8 +133,6 @@
}
}
-
-
// Options of every possible field type, so we can test them all exhaustively.
message DummyMessageContainingEnum {
@@ -151,74 +142,73 @@
}
}
-message DummyMessageInvalidAsOptionType {
-}
+message DummyMessageInvalidAsOptionType {}
extend google.protobuf.MessageOptions {
- optional bool bool_opt = 7706090;
- optional int32 int32_opt = 7705709;
- optional int64 int64_opt = 7705542;
- optional uint32 uint32_opt = 7704880;
- optional uint64 uint64_opt = 7702367;
- optional sint32 sint32_opt = 7701568;
- optional sint64 sint64_opt = 7700863;
- optional fixed32 fixed32_opt = 7700307;
- optional fixed64 fixed64_opt = 7700194;
- optional sfixed32 sfixed32_opt = 7698645;
- optional sfixed64 sfixed64_opt = 7685475;
- optional float float_opt = 7675390;
- optional double double_opt = 7673293;
- optional string string_opt = 7673285;
- optional bytes bytes_opt = 7673238;
+ optional bool bool_opt = 7706090;
+ optional int32 int32_opt = 7705709;
+ optional int64 int64_opt = 7705542;
+ optional uint32 uint32_opt = 7704880;
+ optional uint64 uint64_opt = 7702367;
+ optional sint32 sint32_opt = 7701568;
+ optional sint64 sint64_opt = 7700863;
+ optional fixed32 fixed32_opt = 7700307;
+ optional fixed64 fixed64_opt = 7700194;
+ optional sfixed32 sfixed32_opt = 7698645;
+ optional sfixed64 sfixed64_opt = 7685475;
+ optional float float_opt = 7675390;
+ optional double double_opt = 7673293;
+ optional string string_opt = 7673285;
+ optional bytes bytes_opt = 7673238;
optional DummyMessageContainingEnum.TestEnumType enum_opt = 7673233;
optional DummyMessageInvalidAsOptionType message_type_opt = 7665967;
}
message CustomOptionMinIntegerValues {
- option (bool_opt) = false;
- option (int32_opt) = -0x80000000;
- option (int64_opt) = -0x8000000000000000;
- option (uint32_opt) = 0;
- option (uint64_opt) = 0;
- option (sint32_opt) = -0x80000000;
- option (sint64_opt) = -0x8000000000000000;
- option (fixed32_opt) = 0;
- option (fixed64_opt) = 0;
+ option (bool_opt) = false;
+ option (int32_opt) = -0x80000000;
+ option (int64_opt) = -0x8000000000000000;
+ option (uint32_opt) = 0;
+ option (uint64_opt) = 0;
+ option (sint32_opt) = -0x80000000;
+ option (sint64_opt) = -0x8000000000000000;
+ option (fixed32_opt) = 0;
+ option (fixed64_opt) = 0;
option (sfixed32_opt) = -0x80000000;
option (sfixed64_opt) = -0x8000000000000000;
}
message CustomOptionMaxIntegerValues {
- option (bool_opt) = true;
- option (int32_opt) = 0x7FFFFFFF;
- option (int64_opt) = 0x7FFFFFFFFFFFFFFF;
- option (uint32_opt) = 0xFFFFFFFF;
- option (uint64_opt) = 0xFFFFFFFFFFFFFFFF;
- option (sint32_opt) = 0x7FFFFFFF;
- option (sint64_opt) = 0x7FFFFFFFFFFFFFFF;
- option (fixed32_opt) = 0xFFFFFFFF;
- option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF;
+ option (bool_opt) = true;
+ option (int32_opt) = 0x7FFFFFFF;
+ option (int64_opt) = 0x7FFFFFFFFFFFFFFF;
+ option (uint32_opt) = 0xFFFFFFFF;
+ option (uint64_opt) = 0xFFFFFFFFFFFFFFFF;
+ option (sint32_opt) = 0x7FFFFFFF;
+ option (sint64_opt) = 0x7FFFFFFFFFFFFFFF;
+ option (fixed32_opt) = 0xFFFFFFFF;
+ option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF;
option (sfixed32_opt) = 0x7FFFFFFF;
option (sfixed64_opt) = 0x7FFFFFFFFFFFFFFF;
}
message CustomOptionOtherValues {
- option (int32_opt) = -100; // To test sign-extension.
- option (float_opt) = 12.3456789;
+ option (int32_opt) = -100; // To test sign-extension.
+ option (float_opt) = 12.3456789;
option (double_opt) = 1.234567890123456789;
option (string_opt) = "Hello, \"World\"";
- option (bytes_opt) = "Hello\0World";
- option (enum_opt) = TEST_OPTION_ENUM_TYPE2;
+ option (bytes_opt) = "Hello\0World";
+ option (enum_opt) = TEST_OPTION_ENUM_TYPE2;
}
message SettingRealsFromPositiveInts {
- option (float_opt) = 12;
+ option (float_opt) = 12;
option (double_opt) = 154;
}
message SettingRealsFromNegativeInts {
- option (float_opt) = -12;
- option (double_opt) = -154;
+ option (float_opt) = -12;
+ option (double_opt) = -154;
}
// Options of complex message types, themselves combined and extended in
@@ -295,8 +285,12 @@
option (complex_opt2).(protobuf_unittest.garply).(corge).qux = 2121;
option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971;
option (complex_opt2).fred.waldo = 321;
- option (complex_opt2).barney = { waldo: 101 };
- option (complex_opt2).barney = { waldo: 212 };
+ option (complex_opt2).barney = {
+ waldo: 101
+ };
+ option (complex_opt2).barney = {
+ waldo: 212
+ };
option (protobuf_unittest.complex_opt3).qux = 9;
option (complex_opt3).complexoptiontype5.plugh = 22;
option (complexopt6).xyzzy = 24;
@@ -308,6 +302,7 @@
message AggregateMessageSet {
option message_set_wire_format = true;
+
extensions 4 to max;
}
@@ -337,29 +332,42 @@
}
// Allow Aggregate to be used as an option at all possible locations
-// in the .proto grammer.
-extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
-extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
-extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
-extend google.protobuf.EnumOptions { optional Aggregate enumopt = 15483218; }
-extend google.protobuf.EnumValueOptions { optional Aggregate enumvalopt = 15486921; }
-extend google.protobuf.ServiceOptions { optional Aggregate serviceopt = 15497145; }
-extend google.protobuf.MethodOptions { optional Aggregate methodopt = 15512713; }
+// in the .proto grammar.
+extend google.protobuf.FileOptions {
+ optional Aggregate fileopt = 15478479;
+}
+extend google.protobuf.MessageOptions {
+ optional Aggregate msgopt = 15480088;
+}
+extend google.protobuf.FieldOptions {
+ optional Aggregate fieldopt = 15481374;
+}
+extend google.protobuf.EnumOptions {
+ optional Aggregate enumopt = 15483218;
+}
+extend google.protobuf.EnumValueOptions {
+ optional Aggregate enumvalopt = 15486921;
+}
+extend google.protobuf.ServiceOptions {
+ optional Aggregate serviceopt = 15497145;
+}
+extend google.protobuf.MethodOptions {
+ optional Aggregate methodopt = 15512713;
+}
// Try using AggregateOption at different points in the proto grammar
option (fileopt) = {
s: 'FileAnnotation'
// Also test the handling of comments
- /* of both types */ i: 100
+ /* of both types */
+ i: 100
sub { s: 'NestedFileAnnotation' }
// Include a google.protobuf.FileOptions and recursively extend it with
// another fileopt.
file {
- [protobuf_unittest.fileopt] {
- s:'FileExtensionAnnotation'
- }
+ [protobuf_unittest.fileopt] { s: 'FileExtensionAnnotation' }
}
// A message set inside an option value
@@ -371,30 +379,44 @@
};
message AggregateMessage {
- option (msgopt) = { i:101 s:'MessageAnnotation' };
- optional int32 fieldname = 1 [(fieldopt) = { s:'FieldAnnotation' }];
+ option (msgopt) = {
+ i: 101
+ s: 'MessageAnnotation'
+ };
+
+ optional int32 fieldname = 1 [(fieldopt) = { s: 'FieldAnnotation' }];
}
service AggregateService {
- option (serviceopt) = { s:'ServiceAnnotation' };
- rpc Method (AggregateMessage) returns (AggregateMessage) {
- option (methodopt) = { s:'MethodAnnotation' };
+ option (serviceopt) = {
+ s: 'ServiceAnnotation'
+ };
+
+ rpc Method(AggregateMessage) returns (AggregateMessage) {
+ option (methodopt) = {
+ s: 'MethodAnnotation'
+ };
}
}
enum AggregateEnum {
- option (enumopt) = { s:'EnumAnnotation' };
- VALUE = 1 [(enumvalopt) = { s:'EnumValueAnnotation' }];
+ option (enumopt) = {
+ s: 'EnumAnnotation'
+ };
+
+ VALUE = 1 [(enumvalopt) = { s: 'EnumValueAnnotation' }];
}
// Test custom options for nested type.
message NestedOptionType {
message NestedMessage {
option (message_opt1) = 1001;
+
optional int32 nested_field = 1 [(field_opt1) = 1002];
}
enum NestedEnum {
option (enum_opt1) = 1003;
+
NESTED_ENUM_VALUE = 1 [(enum_value_opt1) = 1004];
}
extend google.protobuf.FileOptions {
@@ -405,9 +427,7 @@
// Custom message option that has a required enum field.
// WARNING: this is strongly discouraged!
message OldOptionType {
- enum TestEnum {
- OLD_VALUE = 0;
- }
+ enum TestEnum { OLD_VALUE = 0; }
required TestEnum value = 1;
}
@@ -426,5 +446,7 @@
// Test message using the "required_enum_opt" option defined above.
message TestMessageWithRequiredEnumOption {
- option (required_enum_opt) = { value: OLD_VALUE };
+ option (required_enum_opt) = {
+ value: OLD_VALUE
+ };
}
diff --git a/src/google/protobuf/unittest_lite.proto b/src/google/protobuf/unittest_lite.proto
index 979c841..652966b 100644
--- a/src/google/protobuf/unittest_lite.proto
+++ b/src/google/protobuf/unittest_lite.proto
@@ -38,6 +38,7 @@
import "google/protobuf/unittest_import_lite.proto";
+option cc_enable_arenas = true;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
diff --git a/src/google/protobuf/unittest_no_arena_import.proto b/src/google/protobuf/unittest_no_arena_import.proto
index 072af49..6f3f04f 100644
--- a/src/google/protobuf/unittest_no_arena_import.proto
+++ b/src/google/protobuf/unittest_no_arena_import.proto
@@ -32,6 +32,8 @@
package proto2_arena_unittest;
+option cc_enable_arenas = false;
+
message ImportNoArenaNestedMessage {
optional int32 d = 1;
-};
+}
diff --git a/src/google/protobuf/unittest_no_arena_lite.proto b/src/google/protobuf/unittest_no_arena_lite.proto
index 34c7b7c..58d8553 100644
--- a/src/google/protobuf/unittest_no_arena_lite.proto
+++ b/src/google/protobuf/unittest_no_arena_lite.proto
@@ -37,6 +37,8 @@
// In test_util.h we do "using namespace unittest = protobuf_unittest".
package protobuf_unittest_no_arena;
+option cc_enable_arenas = false;
+
message ForeignMessageLite {
optional int32 c = 1;
}
diff --git a/src/google/protobuf/unittest_proto3.proto b/src/google/protobuf/unittest_proto3.proto
index e93622a..89c8799 100644
--- a/src/google/protobuf/unittest_proto3.proto
+++ b/src/google/protobuf/unittest_proto3.proto
@@ -183,7 +183,7 @@
repeated TestAllTypes.NestedEnum repeated_nested_enum = 14 [packed = false];
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
NestedTestAllTypes child = 1;
TestAllTypes payload = 2;
diff --git a/src/google/protobuf/unittest_proto3_arena.proto b/src/google/protobuf/unittest_proto3_arena.proto
index 30031f9..fa26488 100644
--- a/src/google/protobuf/unittest_proto3_arena.proto
+++ b/src/google/protobuf/unittest_proto3_arena.proto
@@ -183,7 +183,7 @@
repeated TestAllTypes.NestedEnum repeated_nested_enum = 14 [packed = false];
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
NestedTestAllTypes child = 1;
TestAllTypes payload = 2;
diff --git a/src/google/protobuf/unittest_proto3_arena_lite.proto b/src/google/protobuf/unittest_proto3_arena_lite.proto
index 5a60b90..0d4218b 100644
--- a/src/google/protobuf/unittest_proto3_arena_lite.proto
+++ b/src/google/protobuf/unittest_proto3_arena_lite.proto
@@ -30,12 +30,12 @@
syntax = "proto3";
-option cc_enable_arenas = true;
-option optimize_for = LITE_RUNTIME;
+package proto3_arena_lite_unittest;
import "google/protobuf/unittest_import.proto";
-package proto3_arena_lite_unittest;
+option cc_enable_arenas = true;
+option optimize_for = LITE_RUNTIME;
// This proto includes every type of field in both singular and repeated
// forms.
@@ -56,86 +56,86 @@
}
// 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;
+ 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;
+ float optional_float = 11;
+ double optional_double = 12;
+ bool optional_bool = 13;
+ string optional_string = 14;
+ bytes optional_bytes = 15;
// Groups are not allowed in proto3.
// optional group OptionalGroup = 16 {
// optional int32 a = 17;
// }
- NestedMessage optional_nested_message = 18;
- ForeignMessage optional_foreign_message = 19;
- protobuf_unittest_import.ImportMessage optional_import_message = 20;
+ NestedMessage optional_nested_message = 18;
+ ForeignMessage optional_foreign_message = 19;
+ protobuf_unittest_import.ImportMessage optional_import_message = 20;
- NestedEnum optional_nested_enum = 21;
- ForeignEnum optional_foreign_enum = 22;
+ NestedEnum optional_nested_enum = 21;
+ ForeignEnum optional_foreign_enum = 22;
// Omitted (compared to unittest.proto) because proto2 enums are not allowed
// inside proto2 messages.
//
// optional protobuf_unittest_import.ImportEnum optional_import_enum = 23;
- string optional_string_piece = 24 [ctype=STRING_PIECE];
- string optional_cord = 25 [ctype=CORD];
+ string optional_string_piece = 24 [ctype = STRING_PIECE];
+ string optional_cord = 25 [ctype = CORD];
// Defined in unittest_import_public.proto
- protobuf_unittest_import.PublicImportMessage
- optional_public_import_message = 26;
+ protobuf_unittest_import.PublicImportMessage optional_public_import_message =
+ 26;
- NestedMessage optional_lazy_message = 27 [lazy=true];
+ NestedMessage optional_lazy_message = 27 [lazy = true];
// Repeated
- repeated int32 repeated_int32 = 31;
- repeated int64 repeated_int64 = 32;
- repeated uint32 repeated_uint32 = 33;
- repeated uint64 repeated_uint64 = 34;
- repeated sint32 repeated_sint32 = 35;
- repeated sint64 repeated_sint64 = 36;
- repeated fixed32 repeated_fixed32 = 37;
- repeated fixed64 repeated_fixed64 = 38;
+ repeated 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 float repeated_float = 41;
+ repeated double repeated_double = 42;
+ repeated bool repeated_bool = 43;
+ repeated string repeated_string = 44;
+ repeated bytes repeated_bytes = 45;
// Groups are not allowed in proto3.
// repeated group RepeatedGroup = 46 {
// optional int32 a = 47;
// }
- repeated NestedMessage repeated_nested_message = 48;
- repeated ForeignMessage repeated_foreign_message = 49;
- repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50;
+ repeated NestedMessage repeated_nested_message = 48;
+ repeated ForeignMessage repeated_foreign_message = 49;
+ repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50;
- repeated NestedEnum repeated_nested_enum = 51;
- repeated ForeignEnum repeated_foreign_enum = 52;
+ repeated NestedEnum repeated_nested_enum = 51;
+ repeated ForeignEnum repeated_foreign_enum = 52;
// Omitted (compared to unittest.proto) because proto2 enums are not allowed
// inside proto2 messages.
//
// repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53;
- repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
- repeated string repeated_cord = 55 [ctype=CORD];
+ repeated string repeated_string_piece = 54 [ctype = STRING_PIECE];
+ repeated string repeated_cord = 55 [ctype = CORD];
- repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
+ repeated NestedMessage repeated_lazy_message = 57 [lazy = true];
oneof oneof_field {
uint32 oneof_uint32 = 111;
@@ -148,41 +148,41 @@
// Test messages for packed fields
message TestPackedTypes {
- repeated int32 packed_int32 = 90 [packed = true];
- repeated int64 packed_int64 = 91 [packed = true];
- repeated uint32 packed_uint32 = 92 [packed = true];
- repeated uint64 packed_uint64 = 93 [packed = true];
- repeated sint32 packed_sint32 = 94 [packed = true];
- repeated sint64 packed_sint64 = 95 [packed = true];
- repeated fixed32 packed_fixed32 = 96 [packed = true];
- repeated fixed64 packed_fixed64 = 97 [packed = true];
- repeated sfixed32 packed_sfixed32 = 98 [packed = true];
- repeated sfixed64 packed_sfixed64 = 99 [packed = true];
- repeated float packed_float = 100 [packed = true];
- repeated double packed_double = 101 [packed = true];
- repeated bool packed_bool = 102 [packed = true];
- repeated ForeignEnum packed_enum = 103 [packed = true];
+ repeated int32 packed_int32 = 90 [packed = true];
+ repeated int64 packed_int64 = 91 [packed = true];
+ repeated uint32 packed_uint32 = 92 [packed = true];
+ repeated uint64 packed_uint64 = 93 [packed = true];
+ repeated sint32 packed_sint32 = 94 [packed = true];
+ repeated sint64 packed_sint64 = 95 [packed = true];
+ repeated fixed32 packed_fixed32 = 96 [packed = true];
+ repeated fixed64 packed_fixed64 = 97 [packed = true];
+ repeated sfixed32 packed_sfixed32 = 98 [packed = true];
+ repeated sfixed64 packed_sfixed64 = 99 [packed = true];
+ repeated float packed_float = 100 [packed = true];
+ repeated double packed_double = 101 [packed = true];
+ repeated bool packed_bool = 102 [packed = true];
+ repeated ForeignEnum packed_enum = 103 [packed = true];
}
// Explicitly set packed to false
message TestUnpackedTypes {
- repeated int32 repeated_int32 = 1 [packed = false];
- repeated int64 repeated_int64 = 2 [packed = false];
- repeated uint32 repeated_uint32 = 3 [packed = false];
- repeated uint64 repeated_uint64 = 4 [packed = false];
- repeated sint32 repeated_sint32 = 5 [packed = false];
- repeated sint64 repeated_sint64 = 6 [packed = false];
- repeated fixed32 repeated_fixed32 = 7 [packed = false];
- repeated fixed64 repeated_fixed64 = 8 [packed = false];
- repeated sfixed32 repeated_sfixed32 = 9 [packed = false];
+ repeated int32 repeated_int32 = 1 [packed = false];
+ repeated int64 repeated_int64 = 2 [packed = false];
+ repeated uint32 repeated_uint32 = 3 [packed = false];
+ repeated uint64 repeated_uint64 = 4 [packed = false];
+ repeated sint32 repeated_sint32 = 5 [packed = false];
+ repeated sint64 repeated_sint64 = 6 [packed = false];
+ repeated fixed32 repeated_fixed32 = 7 [packed = false];
+ repeated fixed64 repeated_fixed64 = 8 [packed = false];
+ repeated sfixed32 repeated_sfixed32 = 9 [packed = false];
repeated sfixed64 repeated_sfixed64 = 10 [packed = false];
- repeated float repeated_float = 11 [packed = false];
- repeated double repeated_double = 12 [packed = false];
- repeated bool repeated_bool = 13 [packed = false];
+ repeated float repeated_float = 11 [packed = false];
+ repeated double repeated_double = 12 [packed = false];
+ repeated bool repeated_bool = 13 [packed = false];
repeated TestAllTypes.NestedEnum repeated_nested_enum = 14 [packed = false];
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
NestedTestAllTypes child = 1;
TestAllTypes payload = 2;
@@ -202,6 +202,4 @@
}
// TestEmptyMessage is used to test behavior of unknown fields.
-message TestEmptyMessage {
-}
-
+message TestEmptyMessage {}
diff --git a/src/google/protobuf/unittest_proto3_lite.proto b/src/google/protobuf/unittest_proto3_lite.proto
index 874ade6..837bb03 100644
--- a/src/google/protobuf/unittest_proto3_lite.proto
+++ b/src/google/protobuf/unittest_proto3_lite.proto
@@ -30,11 +30,11 @@
syntax = "proto3";
-option optimize_for = LITE_RUNTIME;
+package proto3_lite_unittest;
import "google/protobuf/unittest_import.proto";
-package proto3_lite_unittest;
+option optimize_for = LITE_RUNTIME;
// This proto includes every type of field in both singular and repeated
// forms.
@@ -55,86 +55,86 @@
}
// 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;
+ 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;
+ float optional_float = 11;
+ double optional_double = 12;
+ bool optional_bool = 13;
+ string optional_string = 14;
+ bytes optional_bytes = 15;
// Groups are not allowed in proto3.
// optional group OptionalGroup = 16 {
// optional int32 a = 17;
// }
- NestedMessage optional_nested_message = 18;
- ForeignMessage optional_foreign_message = 19;
- protobuf_unittest_import.ImportMessage optional_import_message = 20;
+ NestedMessage optional_nested_message = 18;
+ ForeignMessage optional_foreign_message = 19;
+ protobuf_unittest_import.ImportMessage optional_import_message = 20;
- NestedEnum optional_nested_enum = 21;
- ForeignEnum optional_foreign_enum = 22;
+ NestedEnum optional_nested_enum = 21;
+ ForeignEnum optional_foreign_enum = 22;
// Omitted (compared to unittest.proto) because proto2 enums are not allowed
// inside proto2 messages.
//
// optional protobuf_unittest_import.ImportEnum optional_import_enum = 23;
- string optional_string_piece = 24 [ctype=STRING_PIECE];
- string optional_cord = 25 [ctype=CORD];
+ string optional_string_piece = 24 [ctype = STRING_PIECE];
+ string optional_cord = 25 [ctype = CORD];
// Defined in unittest_import_public.proto
- protobuf_unittest_import.PublicImportMessage
- optional_public_import_message = 26;
+ protobuf_unittest_import.PublicImportMessage optional_public_import_message =
+ 26;
- NestedMessage optional_lazy_message = 27 [lazy=true];
+ NestedMessage optional_lazy_message = 27 [lazy = true];
// Repeated
- repeated int32 repeated_int32 = 31;
- repeated int64 repeated_int64 = 32;
- repeated uint32 repeated_uint32 = 33;
- repeated uint64 repeated_uint64 = 34;
- repeated sint32 repeated_sint32 = 35;
- repeated sint64 repeated_sint64 = 36;
- repeated fixed32 repeated_fixed32 = 37;
- repeated fixed64 repeated_fixed64 = 38;
+ repeated 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 float repeated_float = 41;
+ repeated double repeated_double = 42;
+ repeated bool repeated_bool = 43;
+ repeated string repeated_string = 44;
+ repeated bytes repeated_bytes = 45;
// Groups are not allowed in proto3.
// repeated group RepeatedGroup = 46 {
// optional int32 a = 47;
// }
- repeated NestedMessage repeated_nested_message = 48;
- repeated ForeignMessage repeated_foreign_message = 49;
- repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50;
+ repeated NestedMessage repeated_nested_message = 48;
+ repeated ForeignMessage repeated_foreign_message = 49;
+ repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50;
- repeated NestedEnum repeated_nested_enum = 51;
- repeated ForeignEnum repeated_foreign_enum = 52;
+ repeated NestedEnum repeated_nested_enum = 51;
+ repeated ForeignEnum repeated_foreign_enum = 52;
// Omitted (compared to unittest.proto) because proto2 enums are not allowed
// inside proto2 messages.
//
// repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53;
- repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
- repeated string repeated_cord = 55 [ctype=CORD];
+ repeated string repeated_string_piece = 54 [ctype = STRING_PIECE];
+ repeated string repeated_cord = 55 [ctype = CORD];
- repeated NestedMessage repeated_lazy_message = 57 [lazy=true];
+ repeated NestedMessage repeated_lazy_message = 57 [lazy = true];
oneof oneof_field {
uint32 oneof_uint32 = 111;
@@ -147,41 +147,41 @@
// Test messages for packed fields
message TestPackedTypes {
- repeated int32 packed_int32 = 90 [packed = true];
- repeated int64 packed_int64 = 91 [packed = true];
- repeated uint32 packed_uint32 = 92 [packed = true];
- repeated uint64 packed_uint64 = 93 [packed = true];
- repeated sint32 packed_sint32 = 94 [packed = true];
- repeated sint64 packed_sint64 = 95 [packed = true];
- repeated fixed32 packed_fixed32 = 96 [packed = true];
- repeated fixed64 packed_fixed64 = 97 [packed = true];
- repeated sfixed32 packed_sfixed32 = 98 [packed = true];
- repeated sfixed64 packed_sfixed64 = 99 [packed = true];
- repeated float packed_float = 100 [packed = true];
- repeated double packed_double = 101 [packed = true];
- repeated bool packed_bool = 102 [packed = true];
- repeated ForeignEnum packed_enum = 103 [packed = true];
+ repeated int32 packed_int32 = 90 [packed = true];
+ repeated int64 packed_int64 = 91 [packed = true];
+ repeated uint32 packed_uint32 = 92 [packed = true];
+ repeated uint64 packed_uint64 = 93 [packed = true];
+ repeated sint32 packed_sint32 = 94 [packed = true];
+ repeated sint64 packed_sint64 = 95 [packed = true];
+ repeated fixed32 packed_fixed32 = 96 [packed = true];
+ repeated fixed64 packed_fixed64 = 97 [packed = true];
+ repeated sfixed32 packed_sfixed32 = 98 [packed = true];
+ repeated sfixed64 packed_sfixed64 = 99 [packed = true];
+ repeated float packed_float = 100 [packed = true];
+ repeated double packed_double = 101 [packed = true];
+ repeated bool packed_bool = 102 [packed = true];
+ repeated ForeignEnum packed_enum = 103 [packed = true];
}
// Explicitly set packed to false
message TestUnpackedTypes {
- repeated int32 repeated_int32 = 1 [packed = false];
- repeated int64 repeated_int64 = 2 [packed = false];
- repeated uint32 repeated_uint32 = 3 [packed = false];
- repeated uint64 repeated_uint64 = 4 [packed = false];
- repeated sint32 repeated_sint32 = 5 [packed = false];
- repeated sint64 repeated_sint64 = 6 [packed = false];
- repeated fixed32 repeated_fixed32 = 7 [packed = false];
- repeated fixed64 repeated_fixed64 = 8 [packed = false];
- repeated sfixed32 repeated_sfixed32 = 9 [packed = false];
+ repeated int32 repeated_int32 = 1 [packed = false];
+ repeated int64 repeated_int64 = 2 [packed = false];
+ repeated uint32 repeated_uint32 = 3 [packed = false];
+ repeated uint64 repeated_uint64 = 4 [packed = false];
+ repeated sint32 repeated_sint32 = 5 [packed = false];
+ repeated sint64 repeated_sint64 = 6 [packed = false];
+ repeated fixed32 repeated_fixed32 = 7 [packed = false];
+ repeated fixed64 repeated_fixed64 = 8 [packed = false];
+ repeated sfixed32 repeated_sfixed32 = 9 [packed = false];
repeated sfixed64 repeated_sfixed64 = 10 [packed = false];
- repeated float repeated_float = 11 [packed = false];
- repeated double repeated_double = 12 [packed = false];
- repeated bool repeated_bool = 13 [packed = false];
+ repeated float repeated_float = 11 [packed = false];
+ repeated double repeated_double = 12 [packed = false];
+ repeated bool repeated_bool = 13 [packed = false];
repeated TestAllTypes.NestedEnum repeated_nested_enum = 14 [packed = false];
}
-// This proto includes a recusively nested message.
+// This proto includes a recursively nested message.
message NestedTestAllTypes {
NestedTestAllTypes child = 1;
TestAllTypes payload = 2;
@@ -201,6 +201,4 @@
}
// TestEmptyMessage is used to test behavior of unknown fields.
-message TestEmptyMessage {
-}
-
+message TestEmptyMessage {}
diff --git a/src/google/protobuf/unittest_proto3_optional.proto b/src/google/protobuf/unittest_proto3_optional.proto
new file mode 100644
index 0000000..3c47f12
--- /dev/null
+++ b/src/google/protobuf/unittest_proto3_optional.proto
@@ -0,0 +1,79 @@
+// 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 protobuf_unittest;
+
+option java_multiple_files = true;
+option java_package = "com.google.protobuf.testing.proto";
+
+message TestProto3Optional {
+ message NestedMessage {
+ // The field name "b" fails to compile in proto1 because it conflicts with
+ // a local variable named "b" in one of the generated methods. Doh.
+ // This file needs to compile in proto1 to test backwards-compatibility.
+ optional int32 bb = 1;
+ }
+
+ enum NestedEnum {
+ UNSPECIFIED = 0;
+ FOO = 1;
+ BAR = 2;
+ BAZ = 3;
+ NEG = -1; // Intentionally negative.
+ }
+
+ // Singular
+ optional int32 optional_int32 = 1;
+ optional int64 optional_int64 = 2;
+ optional uint32 optional_uint32 = 3;
+ optional uint64 optional_uint64 = 4;
+ optional sint32 optional_sint32 = 5;
+ optional sint64 optional_sint64 = 6;
+ optional fixed32 optional_fixed32 = 7;
+ optional fixed64 optional_fixed64 = 8;
+ optional sfixed32 optional_sfixed32 = 9;
+ optional sfixed64 optional_sfixed64 = 10;
+ optional float optional_float = 11;
+ optional double optional_double = 12;
+ optional bool optional_bool = 13;
+ optional string optional_string = 14;
+ optional bytes optional_bytes = 15;
+ optional string optional_cord = 16 [ctype = CORD];
+
+ optional NestedMessage optional_nested_message = 18;
+ optional NestedMessage lazy_nested_message = 19 [lazy = true];
+ optional NestedEnum optional_nested_enum = 21;
+
+ // Add some non-optional fields to verify we can mix them.
+ int32 singular_int32 = 22;
+ int64 singular_int64 = 23;
+}
diff --git a/src/google/protobuf/unknown_field_set.cc b/src/google/protobuf/unknown_field_set.cc
index fcffe85..451209c 100644
--- a/src/google/protobuf/unknown_field_set.cc
+++ b/src/google/protobuf/unknown_field_set.cc
@@ -41,7 +41,6 @@
#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>
@@ -50,9 +49,9 @@
namespace google {
namespace protobuf {
-const UnknownFieldSet* UnknownFieldSet::default_instance() {
+const UnknownFieldSet& UnknownFieldSet::default_instance() {
static auto instance = internal::OnShutdownDelete(new UnknownFieldSet());
- return instance;
+ return *instance;
}
void UnknownFieldSet::ClearFallback() {
@@ -99,10 +98,9 @@
other->fields_.clear();
}
-void UnknownFieldSet::MergeToInternalMetdata(
- const UnknownFieldSet& other,
- internal::InternalMetadataWithArena* metadata) {
- metadata->mutable_unknown_fields()->MergeFrom(other);
+void UnknownFieldSet::MergeToInternalMetadata(
+ const UnknownFieldSet& other, internal::InternalMetadata* metadata) {
+ metadata->mutable_unknown_fields<UnknownFieldSet>()->MergeFrom(other);
}
size_t UnknownFieldSet::SpaceUsedExcludingSelfLong() const {
@@ -279,34 +277,6 @@
}
namespace internal {
-const char* PackedEnumParser(void* object, const char* ptr, ParseContext* ctx,
- bool (*is_valid)(int),
- InternalMetadataWithArena* metadata,
- int field_num) {
- return ctx->ReadPackedVarint(
- ptr, [object, is_valid, metadata, field_num](uint64 val) {
- if (is_valid(val)) {
- static_cast<RepeatedField<int>*>(object)->Add(val);
- } else {
- WriteVarint(field_num, val, metadata->mutable_unknown_fields());
- }
- });
-}
-const char* PackedEnumParserArg(void* object, const char* ptr,
- ParseContext* ctx,
- bool (*is_valid)(const void*, int),
- const void* data,
- InternalMetadataWithArena* metadata,
- int field_num) {
- return ctx->ReadPackedVarint(
- ptr, [object, is_valid, data, metadata, field_num](uint64 val) {
- if (is_valid(data, val)) {
- static_cast<RepeatedField<int>*>(object)->Add(val);
- } else {
- WriteVarint(field_num, val, metadata->mutable_unknown_fields());
- }
- });
-}
class UnknownFieldParserHelper {
public:
@@ -352,11 +322,6 @@
return FieldParser(tag, field_parser, ptr, ctx);
}
-const char* UnknownFieldParse(uint32 tag, InternalMetadataWithArena* metadata,
- const char* ptr, ParseContext* ctx) {
- return UnknownFieldParse(tag, metadata->mutable_unknown_fields(), ptr, ctx);
-}
-
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/unknown_field_set.h b/src/google/protobuf/unknown_field_set.h
index b613469..ab3633d 100644
--- a/src/google/protobuf/unknown_field_set.h
+++ b/src/google/protobuf/unknown_field_set.h
@@ -60,7 +60,7 @@
namespace google {
namespace protobuf {
namespace internal {
-class InternalMetadataWithArena; // metadata.h
+class InternalMetadata; // metadata_lite.h
class WireFormat; // wire_format.h
class MessageSetFieldSkipperUsingCord;
// extension_set_heavy.cc
@@ -104,9 +104,8 @@
// 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);
+ static void MergeToInternalMetadata(const UnknownFieldSet& other,
+ internal::InternalMetadata* metadata);
// Swaps the contents of some other UnknownFieldSet with this one.
inline void Swap(UnknownFieldSet* x);
@@ -173,7 +172,7 @@
template <typename MessageType>
bool MergeFromMessage(const MessageType& message);
- static const UnknownFieldSet* default_instance();
+ static const UnknownFieldSet& default_instance();
private:
// For InternalMergeFrom
@@ -219,26 +218,11 @@
}
PROTOBUF_EXPORT
-const char* PackedEnumParser(void* object, const char* ptr, ParseContext* ctx,
- bool (*is_valid)(int),
- InternalMetadataWithArena* unknown, int field_num);
-PROTOBUF_EXPORT
-const char* PackedEnumParserArg(void* object, const char* ptr,
- ParseContext* ctx,
- bool (*is_valid)(const void*, int),
- const void* data,
- InternalMetadataWithArena* unknown,
- int field_num);
-
-PROTOBUF_EXPORT
const char* UnknownGroupParse(UnknownFieldSet* unknown, const char* ptr,
ParseContext* ctx);
PROTOBUF_EXPORT
const char* UnknownFieldParse(uint64 tag, UnknownFieldSet* unknown,
const char* ptr, ParseContext* ctx);
-PROTOBUF_EXPORT
-const char* UnknownFieldParse(uint32 tag, InternalMetadataWithArena* metadata,
- const char* ptr, ParseContext* ctx);
} // namespace internal
diff --git a/src/google/protobuf/unknown_field_set_unittest.cc b/src/google/protobuf/unknown_field_set_unittest.cc
index b1ccb5c..0083208 100644
--- a/src/google/protobuf/unknown_field_set_unittest.cc
+++ b/src/google/protobuf/unknown_field_set_unittest.cc
@@ -50,6 +50,7 @@
#include <google/protobuf/wire_format.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/time.h>
#include <google/protobuf/stubs/stl_util.h>
namespace google {
diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc
index d3f347e..547a4dc 100644
--- a/src/google/protobuf/util/field_mask_util.cc
+++ b/src/google/protobuf/util/field_mask_util.cc
@@ -30,6 +30,7 @@
#include <google/protobuf/util/field_mask_util.h>
+#include <google/protobuf/message.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/map_util.h>
diff --git a/src/google/protobuf/util/field_mask_util.h b/src/google/protobuf/util/field_mask_util.h
index 75ea520..cc2148d 100644
--- a/src/google/protobuf/util/field_mask_util.h
+++ b/src/google/protobuf/util/field_mask_util.h
@@ -55,6 +55,21 @@
static std::string ToString(const FieldMask& mask);
static void FromString(StringPiece str, FieldMask* out);
+ // Populates the FieldMask with the paths corresponding to the fields with the
+ // given numbers, after checking that all field numbers are valid.
+ template <typename T>
+ static void FromFieldNumbers(const std::vector<int64>& field_numbers,
+ FieldMask* out) {
+ for (const auto field_number : field_numbers) {
+ const FieldDescriptor* field_desc =
+ T::descriptor()->FindFieldByNumber(field_number);
+ GOOGLE_CHECK(field_desc != nullptr)
+ << "Invalid field number for " << T::descriptor()->full_name() << ": "
+ << field_number;
+ AddPathToFieldMask<T>(field_desc->lowercase_name(), out);
+ }
+ }
+
// Converts FieldMask to/from string, formatted according to proto3 JSON
// spec for FieldMask (e.g., "fooBar,baz.quz"). If the field name is not
// style conforming (i.e., not snake_case when converted to string, or not
@@ -90,7 +105,7 @@
// This method check-fails if the path is not a valid path for type T.
template <typename T>
static void AddPathToFieldMask(StringPiece path, FieldMask* mask) {
- GOOGLE_CHECK(IsValidPath<T>(path));
+ GOOGLE_CHECK(IsValidPath<T>(path)) << path;
mask->add_paths(path);
}
@@ -180,8 +195,8 @@
static bool SnakeCaseToCamelCase(StringPiece input,
std::string* output);
// Converts a field name from camelCase to snake_case:
- // 1. Every uppercase letter is converted to lowercase with a additional
- // preceding "-".
+ // 1. Every uppercase letter is converted to lowercase with an additional
+ // preceding "_".
// The conversion will fail if:
// 1. The field name contains "_"s.
// If the conversion succeeds, it's guaranteed that the resulted
diff --git a/src/google/protobuf/util/field_mask_util_test.cc b/src/google/protobuf/util/field_mask_util_test.cc
index 401a56a..5fe9f65 100644
--- a/src/google/protobuf/util/field_mask_util_test.cc
+++ b/src/google/protobuf/util/field_mask_util_test.cc
@@ -31,6 +31,7 @@
#include <google/protobuf/util/field_mask_util.h>
#include <algorithm>
+#include <vector>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -161,6 +162,20 @@
EXPECT_EQ("baz_quz", mask.paths(1));
}
+TEST(FieldMaskUtilTest, FromFieldNumbers) {
+ FieldMask mask;
+ std::vector<int64> field_numbers = {
+ TestAllTypes::kOptionalInt64FieldNumber,
+ TestAllTypes::kOptionalBoolFieldNumber,
+ TestAllTypes::kRepeatedStringFieldNumber,
+ };
+ FieldMaskUtil::FromFieldNumbers<TestAllTypes>(field_numbers, &mask);
+ ASSERT_EQ(3, mask.paths_size());
+ EXPECT_EQ("optional_int64", mask.paths(0));
+ EXPECT_EQ("optional_bool", mask.paths(1));
+ EXPECT_EQ("repeated_string", mask.paths(2));
+}
+
TEST(FieldMaskUtilTest, GetFieldDescriptors) {
std::vector<const FieldDescriptor*> field_descriptors;
EXPECT_TRUE(FieldMaskUtil::GetFieldDescriptors(
@@ -752,7 +767,7 @@
// Field mask on optional field.
FieldMaskUtil::FromString("optional_int32", &mask);
- // Verify that if a message is updted by FieldMaskUtil::TrimMessage(), the
+ // Verify that if a message is updated by FieldMaskUtil::TrimMessage(), the
// function returns true.
// Test on primary field.
trimed_msg.set_optional_string("abc");
@@ -793,7 +808,7 @@
EXPECT_EQ(trimed_msg.optional_int32(), 123);
trimed_msg.Clear();
- // Field mask on repated field.
+ // Field mask on repeated field.
FieldMaskUtil::FromString("repeated_string", &mask);
trimed_msg.add_repeated_string("abc");
trimed_msg.add_repeated_string("def");
diff --git a/src/google/protobuf/util/internal/datapiece.cc b/src/google/protobuf/util/internal/datapiece.cc
index 041ff7b..6ce7dbc 100644
--- a/src/google/protobuf/util/internal/datapiece.cc
+++ b/src/google/protobuf/util/internal/datapiece.cc
@@ -173,7 +173,7 @@
if (str_ == "-Infinity") return -std::numeric_limits<double>::infinity();
if (str_ == "NaN") return std::numeric_limits<double>::quiet_NaN();
StatusOr<double> value = StringToNumber<double>(safe_strtod);
- if (value.ok() && !std::isfinite(value.ValueOrDie())) {
+ if (value.ok() && !std::isfinite(value.value())) {
// safe_strtod converts out-of-range values to +inf/-inf, but we want
// to report them as errors.
return InvalidArgument(StrCat("\"", str_, "\""));
@@ -289,7 +289,7 @@
StatusOr<int32> int_value = ToInt32();
if (int_value.ok()) {
if (const google::protobuf::EnumValue* enum_value =
- FindEnumValueByNumberOrNull(enum_type, int_value.ValueOrDie())) {
+ FindEnumValueByNumberOrNull(enum_type, int_value.value())) {
return enum_value->number();
}
}
@@ -317,7 +317,9 @@
// If ignore_unknown_enum_values is true an unknown enum value is ignored.
if (ignore_unknown_enum_values) {
*is_unknown_enum_value = true;
- return enum_type->enumvalue(0).number();
+ if (enum_type->enumvalue_size() > 0) {
+ return enum_type->enumvalue(0).number();
+ }
}
} else {
// We don't need to check whether the value is actually declared in the
@@ -382,9 +384,8 @@
if (Base64Unescape(src, dest)) {
if (use_strict_base64_decoding_) {
std::string encoded;
- Base64Escape(
- reinterpret_cast<const unsigned char*>(dest->data()), dest->length(),
- &encoded, false);
+ Base64Escape(reinterpret_cast<const unsigned char*>(dest->data()),
+ dest->length(), &encoded, false);
StringPiece src_no_padding = StringPiece(src).substr(
0, HasSuffixString(src, "=") ? src.find_last_not_of('=') + 1
: src.length());
diff --git a/src/google/protobuf/util/internal/datapiece.h b/src/google/protobuf/util/internal/datapiece.h
index cc5553d..1b0ccfa 100644
--- a/src/google/protobuf/util/internal/datapiece.h
+++ b/src/google/protobuf/util/internal/datapiece.h
@@ -54,7 +54,7 @@
//
// For string, a StringPiece is stored. For Cord, a pointer to Cord is stored.
// Just like StringPiece, the DataPiece class does not own the storage for
-// the actual string or Cord, so it is the user's responsiblity to guarantee
+// the actual string or Cord, so it is the user's responsibility to guarantee
// that the underlying storage is still valid when the DataPiece is accessed.
class PROTOBUF_EXPORT DataPiece {
public:
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc
index 828c868..a78a862 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.cc
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc
@@ -52,7 +52,7 @@
StatusOr<T> (DataPiece::*converter_fn)() const, T default_value) {
if (value.empty()) return default_value;
StatusOr<T> result = (DataPiece(value, true).*converter_fn)();
- return result.ok() ? result.ValueOrDie() : default_value;
+ return result.ok() ? result.value() : default_value;
}
} // namespace
@@ -290,7 +290,7 @@
if (!sub_type.ok()) {
GOOGLE_LOG(WARNING) << "Cannot resolve type '" << sub_field.type_url() << "'.";
} else {
- return sub_type.ValueOrDie();
+ return sub_type.value();
}
break;
}
@@ -354,7 +354,7 @@
// "field" is of an unknown type.
GOOGLE_LOG(WARNING) << "Cannot resolve type '" << field.type_url() << "'.";
} else {
- const google::protobuf::Type* found_type = found_result.ValueOrDie();
+ const google::protobuf::Type* found_type = found_result.value();
is_map = IsMap(field, *found_type);
if (!is_map) {
@@ -587,7 +587,7 @@
name == "@type") {
util::StatusOr<std::string> data_string = data.ToString();
if (data_string.ok()) {
- const std::string& string_value = data_string.ValueOrDie();
+ const std::string& string_value = data_string.value();
// 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".
@@ -596,7 +596,7 @@
if (!found_type.ok()) {
GOOGLE_LOG(WARNING) << "Failed to resolve type '" << string_value << "'.";
} else {
- current_->set_type(found_type.ValueOrDie());
+ current_->set_type(found_type.value());
}
current_->set_is_any(true);
// If the "@type" field is placed after other fields, we should populate
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.h b/src/google/protobuf/util/internal/default_value_objectwriter.h
index 30c0304..08793fc 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.h
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.h
@@ -201,7 +201,7 @@
// Returns the Value Type of a map given the Type of the map entry and a
// TypeInfo instance.
const google::protobuf::Type* GetMapValueType(
- const google::protobuf::Type& entry_type, const TypeInfo* typeinfo);
+ const google::protobuf::Type& found_type, const TypeInfo* typeinfo);
// Calls WriteTo() on every child in children_.
void WriteChildren(ObjectWriter* ow);
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter_test.cc b/src/google/protobuf/util/internal/default_value_objectwriter_test.cc
index 6236d5b..7af3579 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/default_value_objectwriter_test.cc
@@ -29,6 +29,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/util/internal/default_value_objectwriter.h>
+
#include <google/protobuf/util/internal/expecting_objectwriter.h>
#include <google/protobuf/util/internal/testdata/default_value_test.pb.h>
#include <google/protobuf/util/internal/type_info_test_helper.h>
@@ -166,7 +167,7 @@
testing::USE_TYPE_RESOLVER));
TEST_P(DefaultValueObjectWriterSuppressListTest, Empty) {
- // Set expectation. Emtpy lists should be suppressed.
+ // Set expectation. Empty lists should be suppressed.
expects_.StartObject("")
->RenderDouble("doubleValue", 0.0)
->RenderFloat("floatValue", 0.0)
diff --git a/src/google/protobuf/util/internal/expecting_objectwriter.h b/src/google/protobuf/util/internal/expecting_objectwriter.h
index 65961ad..71ecb1d 100644
--- a/src/google/protobuf/util/internal/expecting_objectwriter.h
+++ b/src/google/protobuf/util/internal/expecting_objectwriter.h
@@ -71,21 +71,27 @@
public:
MockObjectWriter() {}
- MOCK_METHOD1(StartObject, ObjectWriter*(StringPiece));
- MOCK_METHOD0(EndObject, ObjectWriter*());
- MOCK_METHOD1(StartList, ObjectWriter*(StringPiece));
- MOCK_METHOD0(EndList, ObjectWriter*());
- MOCK_METHOD2(RenderBool, ObjectWriter*(StringPiece, bool));
- MOCK_METHOD2(RenderInt32, ObjectWriter*(StringPiece, int32));
- MOCK_METHOD2(RenderUint32, ObjectWriter*(StringPiece, uint32));
- MOCK_METHOD2(RenderInt64, ObjectWriter*(StringPiece, int64));
- MOCK_METHOD2(RenderUint64, ObjectWriter*(StringPiece, uint64));
- MOCK_METHOD2(RenderDouble, ObjectWriter*(StringPiece, double));
- MOCK_METHOD2(RenderFloat, ObjectWriter*(StringPiece, float));
- MOCK_METHOD2(RenderString,
- ObjectWriter*(StringPiece, StringPiece));
- MOCK_METHOD2(RenderBytes, ObjectWriter*(StringPiece, StringPiece));
- MOCK_METHOD1(RenderNull, ObjectWriter*(StringPiece));
+ MOCK_METHOD(ObjectWriter*, StartObject, (StringPiece), (override));
+ MOCK_METHOD(ObjectWriter*, EndObject, (), (override));
+ MOCK_METHOD(ObjectWriter*, StartList, (StringPiece), (override));
+ MOCK_METHOD(ObjectWriter*, EndList, (), (override));
+ MOCK_METHOD(ObjectWriter*, RenderBool, (StringPiece, bool), (override));
+ MOCK_METHOD(ObjectWriter*, RenderInt32, (StringPiece, int32),
+ (override));
+ MOCK_METHOD(ObjectWriter*, RenderUint32, (StringPiece, uint32),
+ (override));
+ MOCK_METHOD(ObjectWriter*, RenderInt64, (StringPiece, int64),
+ (override));
+ MOCK_METHOD(ObjectWriter*, RenderUint64, (StringPiece, uint64),
+ (override));
+ MOCK_METHOD(ObjectWriter*, RenderDouble, (StringPiece, double),
+ (override));
+ MOCK_METHOD(ObjectWriter*, RenderFloat, (StringPiece, float),
+ (override));
+ MOCK_METHOD(ObjectWriter*, RenderString,
+ (StringPiece, StringPiece), (override));
+ MOCK_METHOD(ObjectWriter*, RenderBytes, (StringPiece, StringPiece));
+ MOCK_METHOD(ObjectWriter*, RenderNull, (StringPiece), (override));
};
class ExpectingObjectWriter : public ObjectWriter {
diff --git a/src/google/protobuf/util/internal/field_mask_utility.cc b/src/google/protobuf/util/internal/field_mask_utility.cc
index 74586d4..40e193e 100644
--- a/src/google/protobuf/util/internal/field_mask_utility.cc
+++ b/src/google/protobuf/util/internal/field_mask_utility.cc
@@ -186,7 +186,7 @@
// Builds a prefix and save it into the stack.
prefix.push(AppendPathSegmentToPrefix(current_prefix, segment));
} else if (!segment.empty()) {
- // When the current charactor is ')', ',' or the current position has
+ // When the current character is ')', ',' or the current position has
// passed the end of the input, builds and outputs a new paths by
// concatenating the last prefix with the current segment.
RETURN_IF_ERROR(
diff --git a/src/google/protobuf/util/internal/json_escaping.h b/src/google/protobuf/util/internal/json_escaping.h
index 4ba765c..d05c335 100644
--- a/src/google/protobuf/util/internal/json_escaping.h
+++ b/src/google/protobuf/util/internal/json_escaping.h
@@ -44,34 +44,34 @@
// The minimum value of a unicode high-surrogate code unit in the utf-16
// encoding. A high-surrogate is also known as a leading-surrogate.
// See http://www.unicode.org/glossary/#high_surrogate_code_unit
- static const uint16 kMinHighSurrogate = 0xd800;
+ static constexpr uint16 kMinHighSurrogate = 0xd800;
// The maximum value of a unicide high-surrogate code unit in the utf-16
// encoding. A high-surrogate is also known as a leading-surrogate.
// See http://www.unicode.org/glossary/#high_surrogate_code_unit
- static const uint16 kMaxHighSurrogate = 0xdbff;
+ static constexpr uint16 kMaxHighSurrogate = 0xdbff;
// The minimum value of a unicode low-surrogate code unit in the utf-16
// encoding. A low-surrogate is also known as a trailing-surrogate.
// See http://www.unicode.org/glossary/#low_surrogate_code_unit
- static const uint16 kMinLowSurrogate = 0xdc00;
+ static constexpr uint16 kMinLowSurrogate = 0xdc00;
// The maximum value of a unicode low-surrogate code unit in the utf-16
// encoding. A low-surrogate is also known as a trailing surrogate.
// See http://www.unicode.org/glossary/#low_surrogate_code_unit
- static const uint16 kMaxLowSurrogate = 0xdfff;
+ static constexpr uint16 kMaxLowSurrogate = 0xdfff;
// The minimum value of a unicode supplementary code point.
// See http://www.unicode.org/glossary/#supplementary_code_point
- static const uint32 kMinSupplementaryCodePoint = 0x010000;
+ static constexpr uint32 kMinSupplementaryCodePoint = 0x010000;
// The minimum value of a unicode code point.
// See http://www.unicode.org/glossary/#code_point
- static const uint32 kMinCodePoint = 0x000000;
+ static constexpr uint32 kMinCodePoint = 0x000000;
// The maximum value of a unicode code point.
// See http://www.unicode.org/glossary/#code_point
- static const uint32 kMaxCodePoint = 0x10ffff;
+ static constexpr uint32 kMaxCodePoint = 0x10ffff;
JsonEscaping() {}
virtual ~JsonEscaping() {}
diff --git a/src/google/protobuf/util/internal/json_stream_parser.cc b/src/google/protobuf/util/internal/json_stream_parser.cc
index a221b98..b94e3c2 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser.cc
@@ -86,6 +86,26 @@
c == '[' || c == ']' || c == ':' || c == ',');
}
+inline void ReplaceInvalidCodePoints(StringPiece str,
+ const std::string& replacement,
+ std::string* dst) {
+ while (!str.empty()) {
+ int n_valid_bytes = internal::UTF8SpnStructurallyValid(str);
+ StringPiece valid_part = str.substr(0, n_valid_bytes);
+ StrAppend(dst, valid_part);
+
+ if (n_valid_bytes == str.size()) {
+ break;
+ }
+
+ // Append replacement value.
+ StrAppend(dst, replacement);
+
+ // Move past valid bytes + one invalid byte.
+ str.remove_prefix(n_valid_bytes + 1);
+ }
+}
+
static bool ConsumeKey(StringPiece* input, StringPiece* key) {
if (input->empty() || !IsLetter((*input)[0])) return false;
int len = 1;
@@ -132,6 +152,7 @@
string_open_(0),
chunk_storage_(),
coerce_to_utf8_(false),
+ utf8_replacement_character_(" "),
allow_empty_null_(false),
allow_permissive_key_naming_(false),
loose_float_number_conversion_(false),
@@ -180,15 +201,20 @@
return util::Status();
}
- // Storage for UTF8-coerced string.
- std::unique_ptr<char[]> utf8;
- if (coerce_to_utf8_) {
- utf8.reset(new char[leftover_.size()]);
- char* coerced = internal::UTF8CoerceToStructurallyValid(leftover_, utf8.get(), ' ');
- p_ = json_ = StringPiece(coerced, leftover_.size());
+ // Lifetime needs to last until RunParser returns, so keep this variable
+ // outside of the coerce_to_utf8 block.
+ std::unique_ptr<std::string> scratch;
+
+ bool is_valid_utf8 = internal::IsStructurallyValidUTF8(leftover_);
+ if (coerce_to_utf8_ && !is_valid_utf8) {
+ scratch.reset(new std::string);
+ scratch->reserve(leftover_.size() * utf8_replacement_character_.size());
+ ReplaceInvalidCodePoints(leftover_, utf8_replacement_character_,
+ scratch.get());
+ p_ = json_ = *scratch;
} else {
p_ = json_ = leftover_;
- if (!internal::IsStructurallyValidUTF8(leftover_)) {
+ if (!is_valid_utf8) {
return ReportFailure("Encountered non UTF-8 code points.");
}
}
diff --git a/src/google/protobuf/util/internal/json_stream_parser.h b/src/google/protobuf/util/internal/json_stream_parser.h
index 0292bf2..2eb3532 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.h
+++ b/src/google/protobuf/util/internal/json_stream_parser.h
@@ -130,7 +130,7 @@
};
// Parses a single chunk of JSON, returning an error if the JSON was invalid.
- util::Status ParseChunk(StringPiece json);
+ util::Status ParseChunk(StringPiece chunk);
// Runs the parser based on stack_ and p_, until the stack is empty or p_ runs
// out of data. If we unexpectedly run out of p_ we push the latest back onto
@@ -269,6 +269,9 @@
// Whether to allow non UTF-8 encoded input and replace invalid code points.
bool coerce_to_utf8_;
+ // Replacement character for invalid UTF-8 code points.
+ std::string utf8_replacement_character_;
+
// Whether allows empty string represented null array value or object entry
// value.
bool allow_empty_null_;
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 6bb22a6..e4341fa 100644
--- a/src/google/protobuf/util/internal/json_stream_parser_test.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser_test.cc
@@ -32,10 +32,10 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/time.h>
#include <google/protobuf/util/internal/expecting_objectwriter.h>
#include <google/protobuf/util/internal/object_writer.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/time.h>
#include <google/protobuf/stubs/status.h>
@@ -235,7 +235,7 @@
TEST_F(JsonStreamParserTest, SimpleNegativeInt) {
StringPiece str = "-79497823553162765";
for (int i = 0; i <= str.length(); ++i) {
- ow_.RenderInt64("", -79497823553162765LL);
+ ow_.RenderInt64("", int64{-79497823553162765});
DoTest(str, i);
}
}
@@ -243,7 +243,7 @@
TEST_F(JsonStreamParserTest, SimpleUnsignedInt) {
StringPiece str = "11779497823553162765";
for (int i = 0; i <= str.length(); ++i) {
- ow_.RenderUint64("", 11779497823553162765ULL);
+ ow_.RenderUint64("", uint64{11779497823553162765u});
DoTest(str, i);
}
}
@@ -378,7 +378,7 @@
->RenderInt64("", -127)
->RenderDouble("", 45.3)
->RenderDouble("", -1056.4)
- ->RenderUint64("", 11779497823553162765ULL)
+ ->RenderUint64("", uint64{11779497823553162765u})
->EndList()
->StartObject("")
->RenderBool("key", true)
@@ -406,7 +406,7 @@
->RenderInt64("ni", -127)
->RenderDouble("pd", 45.3)
->RenderDouble("nd", -1056.4)
- ->RenderUint64("pl", 11779497823553162765ULL)
+ ->RenderUint64("pl", uint64{11779497823553162765u})
->StartList("l")
->StartList("")
->EndList()
diff --git a/src/google/protobuf/util/internal/mock_error_listener.h b/src/google/protobuf/util/internal/mock_error_listener.h
index 53e5876..4f5b0a2 100644
--- a/src/google/protobuf/util/internal/mock_error_listener.h
+++ b/src/google/protobuf/util/internal/mock_error_listener.h
@@ -46,14 +46,18 @@
MockErrorListener() {}
virtual ~MockErrorListener() {}
- MOCK_METHOD3(InvalidName,
- void(const LocationTrackerInterface& loc,
- StringPiece unknown_name, StringPiece message));
- MOCK_METHOD3(InvalidValue,
- void(const LocationTrackerInterface& loc,
- StringPiece type_name, StringPiece value));
- MOCK_METHOD2(MissingField, void(const LocationTrackerInterface& loc,
- StringPiece missing_name));
+ MOCK_METHOD(void, InvalidName,
+ (const LocationTrackerInterface& loc,
+ StringPiece unknown_name, StringPiece message),
+ (override));
+ MOCK_METHOD(void, InvalidValue,
+ (const LocationTrackerInterface& loc, StringPiece type_name,
+ StringPiece value),
+ (override));
+ MOCK_METHOD(void, MissingField,
+ (const LocationTrackerInterface& loc,
+ StringPiece missing_name),
+ (override));
};
} // namespace converter
diff --git a/src/google/protobuf/util/internal/object_writer.cc b/src/google/protobuf/util/internal/object_writer.cc
index bb1b3e5..b7667b6 100644
--- a/src/google/protobuf/util/internal/object_writer.cc
+++ b/src/google/protobuf/util/internal/object_writer.cc
@@ -42,35 +42,35 @@
StringPiece name, ObjectWriter* ow) {
switch (data.type()) {
case DataPiece::TYPE_INT32: {
- ow->RenderInt32(name, data.ToInt32().ValueOrDie());
+ ow->RenderInt32(name, data.ToInt32().value());
break;
}
case DataPiece::TYPE_INT64: {
- ow->RenderInt64(name, data.ToInt64().ValueOrDie());
+ ow->RenderInt64(name, data.ToInt64().value());
break;
}
case DataPiece::TYPE_UINT32: {
- ow->RenderUint32(name, data.ToUint32().ValueOrDie());
+ ow->RenderUint32(name, data.ToUint32().value());
break;
}
case DataPiece::TYPE_UINT64: {
- ow->RenderUint64(name, data.ToUint64().ValueOrDie());
+ ow->RenderUint64(name, data.ToUint64().value());
break;
}
case DataPiece::TYPE_DOUBLE: {
- ow->RenderDouble(name, data.ToDouble().ValueOrDie());
+ ow->RenderDouble(name, data.ToDouble().value());
break;
}
case DataPiece::TYPE_FLOAT: {
- ow->RenderFloat(name, data.ToFloat().ValueOrDie());
+ ow->RenderFloat(name, data.ToFloat().value());
break;
}
case DataPiece::TYPE_BOOL: {
- ow->RenderBool(name, data.ToBool().ValueOrDie());
+ ow->RenderBool(name, data.ToBool().value());
break;
}
case DataPiece::TYPE_STRING: {
- ow->RenderString(name, data.ToString().ValueOrDie());
+ ow->RenderString(name, data.ToString().value());
break;
}
case DataPiece::TYPE_BYTES: {
@@ -86,6 +86,7 @@
}
}
+
} // namespace converter
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/internal/object_writer.h b/src/google/protobuf/util/internal/object_writer.h
index 856d77d..29b05c1 100644
--- a/src/google/protobuf/util/internal/object_writer.h
+++ b/src/google/protobuf/util/internal/object_writer.h
@@ -42,6 +42,7 @@
namespace util {
namespace converter {
+
class DataPiece;
// An ObjectWriter is an interface for writing a stream of events
@@ -92,7 +93,6 @@
// Renders a double value.
virtual ObjectWriter* RenderDouble(StringPiece name, double value) = 0;
-
// Renders a float value.
virtual ObjectWriter* RenderFloat(StringPiece name, float value) = 0;
@@ -111,6 +111,7 @@
static void RenderDataPieceTo(const DataPiece& data, StringPiece name,
ObjectWriter* ow);
+
// Indicates whether this ObjectWriter has completed writing the root message,
// usually this means writing of one complete object. Subclasses must override
// this behavior appropriately.
diff --git a/src/google/protobuf/util/internal/proto_writer.cc b/src/google/protobuf/util/internal/proto_writer.cc
index 31288b3..ea95932 100644
--- a/src/google/protobuf/util/internal/proto_writer.cc
+++ b/src/google/protobuf/util/internal/proto_writer.cc
@@ -34,13 +34,13 @@
#include <stack>
#include <google/protobuf/stubs/once.h>
-#include <google/protobuf/stubs/time.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/util/internal/field_mask_utility.h>
#include <google/protobuf/util/internal/object_location_tracker.h>
#include <google/protobuf/util/internal/constants.h>
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/time.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/statusor.h>
@@ -124,7 +124,7 @@
CodedOutputStream* stream) {
StatusOr<int32> i32 = data.ToInt32();
if (i32.ok()) {
- WireFormatLite::WriteInt32(field_number, i32.ValueOrDie(), stream);
+ WireFormatLite::WriteInt32(field_number, i32.value(), stream);
}
return i32.status();
}
@@ -134,7 +134,7 @@
CodedOutputStream* stream) {
StatusOr<int32> i32 = data.ToInt32();
if (i32.ok()) {
- WireFormatLite::WriteSFixed32(field_number, i32.ValueOrDie(), stream);
+ WireFormatLite::WriteSFixed32(field_number, i32.value(), stream);
}
return i32.status();
}
@@ -144,7 +144,7 @@
CodedOutputStream* stream) {
StatusOr<int32> i32 = data.ToInt32();
if (i32.ok()) {
- WireFormatLite::WriteSInt32(field_number, i32.ValueOrDie(), stream);
+ WireFormatLite::WriteSInt32(field_number, i32.value(), stream);
}
return i32.status();
}
@@ -154,7 +154,7 @@
CodedOutputStream* stream) {
StatusOr<uint32> u32 = data.ToUint32();
if (u32.ok()) {
- WireFormatLite::WriteFixed32(field_number, u32.ValueOrDie(), stream);
+ WireFormatLite::WriteFixed32(field_number, u32.value(), stream);
}
return u32.status();
}
@@ -164,7 +164,7 @@
CodedOutputStream* stream) {
StatusOr<uint32> u32 = data.ToUint32();
if (u32.ok()) {
- WireFormatLite::WriteUInt32(field_number, u32.ValueOrDie(), stream);
+ WireFormatLite::WriteUInt32(field_number, u32.value(), stream);
}
return u32.status();
}
@@ -174,7 +174,7 @@
CodedOutputStream* stream) {
StatusOr<int64> i64 = data.ToInt64();
if (i64.ok()) {
- WireFormatLite::WriteInt64(field_number, i64.ValueOrDie(), stream);
+ WireFormatLite::WriteInt64(field_number, i64.value(), stream);
}
return i64.status();
}
@@ -184,7 +184,7 @@
CodedOutputStream* stream) {
StatusOr<int64> i64 = data.ToInt64();
if (i64.ok()) {
- WireFormatLite::WriteSFixed64(field_number, i64.ValueOrDie(), stream);
+ WireFormatLite::WriteSFixed64(field_number, i64.value(), stream);
}
return i64.status();
}
@@ -194,7 +194,7 @@
CodedOutputStream* stream) {
StatusOr<int64> i64 = data.ToInt64();
if (i64.ok()) {
- WireFormatLite::WriteSInt64(field_number, i64.ValueOrDie(), stream);
+ WireFormatLite::WriteSInt64(field_number, i64.value(), stream);
}
return i64.status();
}
@@ -204,7 +204,7 @@
CodedOutputStream* stream) {
StatusOr<uint64> u64 = data.ToUint64();
if (u64.ok()) {
- WireFormatLite::WriteFixed64(field_number, u64.ValueOrDie(), stream);
+ WireFormatLite::WriteFixed64(field_number, u64.value(), stream);
}
return u64.status();
}
@@ -214,7 +214,7 @@
CodedOutputStream* stream) {
StatusOr<uint64> u64 = data.ToUint64();
if (u64.ok()) {
- WireFormatLite::WriteUInt64(field_number, u64.ValueOrDie(), stream);
+ WireFormatLite::WriteUInt64(field_number, u64.value(), stream);
}
return u64.status();
}
@@ -224,7 +224,7 @@
CodedOutputStream* stream) {
StatusOr<double> d = data.ToDouble();
if (d.ok()) {
- WireFormatLite::WriteDouble(field_number, d.ValueOrDie(), stream);
+ WireFormatLite::WriteDouble(field_number, d.value(), stream);
}
return d.status();
}
@@ -234,7 +234,7 @@
CodedOutputStream* stream) {
StatusOr<float> f = data.ToFloat();
if (f.ok()) {
- WireFormatLite::WriteFloat(field_number, f.ValueOrDie(), stream);
+ WireFormatLite::WriteFloat(field_number, f.value(), stream);
}
return f.status();
}
@@ -244,7 +244,7 @@
CodedOutputStream* stream) {
StatusOr<bool> b = data.ToBool();
if (b.ok()) {
- WireFormatLite::WriteBool(field_number, b.ValueOrDie(), stream);
+ WireFormatLite::WriteBool(field_number, b.value(), stream);
}
return b.status();
}
@@ -264,7 +264,7 @@
CodedOutputStream* stream) {
StatusOr<std::string> s = data.ToString();
if (s.ok()) {
- WireFormatLite::WriteString(field_number, s.ValueOrDie(), stream);
+ WireFormatLite::WriteString(field_number, s.value(), stream);
}
return s.status();
}
@@ -449,7 +449,8 @@
listener_->MissingField(location(), missing_name);
}
-ProtoWriter* ProtoWriter::StartObject(StringPiece name) {
+ProtoWriter* ProtoWriter::StartObject(
+ StringPiece name) {
// Starting the root message. Create the root ProtoElement and return.
if (element_ == nullptr) {
if (!name.empty()) {
@@ -459,8 +460,8 @@
return this;
}
- const google::protobuf::Field* field = nullptr;
- field = BeginNamed(name, false);
+ const google::protobuf::Field* field = BeginNamed(name, false);
+
if (field == nullptr) return this;
// Check to see if this field is a oneof and that no oneof in that group has
@@ -481,6 +482,7 @@
return StartObjectField(*field, *type);
}
+
ProtoWriter* ProtoWriter::EndObject() {
if (invalid_depth_ > 0) {
--invalid_depth_;
@@ -500,8 +502,11 @@
return this;
}
-ProtoWriter* ProtoWriter::StartList(StringPiece name) {
+ProtoWriter* ProtoWriter::StartList(
+ StringPiece name) {
+
const google::protobuf::Field* field = BeginNamed(name, true);
+
if (field == nullptr) return this;
if (!ValidOneof(*field, name)) {
@@ -520,6 +525,7 @@
return StartListField(*field, *type);
}
+
ProtoWriter* ProtoWriter::EndList() {
if (invalid_depth_ > 0) {
--invalid_depth_;
@@ -529,12 +535,13 @@
return this;
}
-ProtoWriter* ProtoWriter::RenderDataPiece(StringPiece name,
- const DataPiece& data) {
+ProtoWriter* ProtoWriter::RenderDataPiece(
+ StringPiece name, const DataPiece& data) {
Status status;
if (invalid_depth_ > 0) return this;
const google::protobuf::Field* field = Lookup(name);
+
if (field == nullptr) return this;
if (!ValidOneof(*field, name)) return this;
@@ -595,7 +602,7 @@
case_insensitive_enum_parsing,
ignore_unknown_values, &is_unknown_enum_value);
if (e.ok() && !is_unknown_enum_value) {
- WireFormatLite::WriteEnum(field_number, e.ValueOrDie(), stream);
+ WireFormatLite::WriteEnum(field_number, e.value(), stream);
}
return e.status();
}
@@ -697,8 +704,8 @@
break;
}
default: // TYPE_GROUP or TYPE_MESSAGE
- status = Status(util::error::INVALID_ARGUMENT,
- data.ToString().ValueOrDie());
+ status =
+ Status(util::error::INVALID_ARGUMENT, data.ToString().value());
}
if (!status.ok()) {
diff --git a/src/google/protobuf/util/internal/proto_writer.h b/src/google/protobuf/util/internal/proto_writer.h
index 51d17a3..7e79ce3 100644
--- a/src/google/protobuf/util/internal/proto_writer.h
+++ b/src/google/protobuf/util/internal/proto_writer.h
@@ -49,6 +49,7 @@
#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/stubs/status.h>
+// Must be included last.
#include <google/protobuf/port_def.inc>
namespace google {
@@ -56,6 +57,7 @@
namespace util {
namespace converter {
+
class ObjectLocationTracker;
// An ObjectWriter that can write protobuf bytes directly from writer events.
@@ -102,10 +104,12 @@
return RenderDataPiece(name,
DataPiece(value, use_strict_base64_decoding()));
}
+
ProtoWriter* RenderBytes(StringPiece name, StringPiece value) override {
return RenderDataPiece(
name, DataPiece(value, false, use_strict_base64_decoding()));
}
+
ProtoWriter* RenderNull(StringPiece name) override {
return RenderDataPiece(name, DataPiece::NullData());
}
@@ -114,7 +118,8 @@
// Renders a DataPiece 'value' into a field whose wire type is determined
// from the given field 'name'.
virtual ProtoWriter* RenderDataPiece(StringPiece name,
- const DataPiece& value);
+ const DataPiece& data);
+
// Returns the location tracker to use for tracking locations for errors.
const LocationTrackerInterface& location() {
@@ -296,10 +301,10 @@
ProtoWriter* StartListField(const google::protobuf::Field& field,
const google::protobuf::Type& type);
- // Renders a primitve field given the field and the enclosing type.
+ // Renders a primitive field given the field and the enclosing type.
ProtoWriter* RenderPrimitiveField(const google::protobuf::Field& field,
const google::protobuf::Type& type,
- const DataPiece& value);
+ const DataPiece& data);
private:
// Writes an ENUM field, including tag, to the stream.
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.cc b/src/google/protobuf/util/internal/protostream_objectsource.cc
index 4fc026f..71e2d2e 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource.cc
@@ -36,7 +36,6 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
-#include <google/protobuf/stubs/time.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.h>
@@ -49,6 +48,7 @@
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/casts.h>
+#include <google/protobuf/stubs/time.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/status_macros.h>
@@ -201,14 +201,14 @@
uint32 tag = stream_->ReadTag(), last_tag = tag + 1;
UnknownFieldSet unknown_fields;
- if (tag == end_tag && suppress_empty_object_) {
+ if (!name.empty() && tag == end_tag && suppress_empty_object_) {
return util::Status();
}
if (include_start_and_end) {
ow->StartObject(name);
}
- while (tag != end_tag) {
+ while (tag != end_tag && tag != 0) {
if (tag != last_tag) { // Update field only if tag is changed.
last_tag = tag;
field = FindAndVerifyField(type, tag);
@@ -537,6 +537,11 @@
ow->StartObject(field_name);
while (tag != 0) {
field = os->FindAndVerifyField(type, tag);
+ if (field == nullptr) {
+ WireFormat::SkipField(os->stream_, tag, nullptr);
+ tag = os->stream_->ReadTag();
+ continue;
+ }
// google.protobuf.Struct has only one field that is a map. Hence we use
// RenderMap to render that field.
if (os->IsMap(*field)) {
@@ -647,7 +652,7 @@
resolved_type.status().message());
}
// nested_type cannot be null at this time.
- const google::protobuf::Type* nested_type = resolved_type.ValueOrDie();
+ const google::protobuf::Type* nested_type = resolved_type.value();
io::ArrayInputStream zero_copy_stream(value.data(), value.size());
io::CodedInputStream in_stream(&zero_copy_stream);
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.h b/src/google/protobuf/util/internal/protostream_objectsource.h
index a83031d..1343d9b 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.h
+++ b/src/google/protobuf/util/internal/protostream_objectsource.h
@@ -131,7 +131,7 @@
// nested messages (end with 0) and nested groups (end with group end tag).
// The include_start_and_end parameter allows this method to be called when
// already inside of an object, and skip calling StartObject and EndObject.
- virtual util::Status WriteMessage(const google::protobuf::Type& descriptor,
+ virtual util::Status WriteMessage(const google::protobuf::Type& type,
StringPiece name,
const uint32 end_tag,
bool include_start_and_end,
@@ -160,6 +160,9 @@
const google::protobuf::Field& field) const;
+ // Returns the input stream.
+ io::CodedInputStream* stream() const { return stream_; }
+
private:
ProtoStreamObjectSource(io::CodedInputStream* stream,
const TypeInfo* typeinfo,
@@ -281,7 +284,7 @@
StringPiece field_name) const;
// Input stream to read from. Ownership rests with the caller.
- io::CodedInputStream* stream_;
+ mutable io::CodedInputStream* stream_;
// Type information for all the types used in the descriptor. Used to find
// google::protobuf::Type of nested messages/enums.
diff --git a/src/google/protobuf/util/internal/protostream_objectsource_test.cc b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
index 22fc3f6..b2daf3a 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
@@ -152,13 +152,13 @@
->RenderInt32("", 3208)
->EndList()
->StartList("repFix64")
- ->RenderUint64("", bit_cast<uint64>(6401LL))
- ->RenderUint64("", bit_cast<uint64>(0LL))
+ ->RenderUint64("", bit_cast<uint64>(int64{6401}))
+ ->RenderUint64("", bit_cast<uint64>(int64{0}))
->EndList()
->StartList("repU64")
- ->RenderUint64("", bit_cast<uint64>(0LL))
- ->RenderUint64("", bit_cast<uint64>(6402LL))
- ->RenderUint64("", bit_cast<uint64>(6403LL))
+ ->RenderUint64("", bit_cast<uint64>(int64{0}))
+ ->RenderUint64("", bit_cast<uint64>(int64{6402}))
+ ->RenderUint64("", bit_cast<uint64>(int64{6403}))
->EndList()
->StartList("repI64")
->RenderInt64("", 6404L)
@@ -325,8 +325,8 @@
->RenderInt32("i32", 3203)
->RenderInt32("sf32", 3204)
->RenderInt32("s32", 3205)
- ->RenderUint64("fix64", bit_cast<uint64>(6401LL))
- ->RenderUint64("u64", bit_cast<uint64>(6402LL))
+ ->RenderUint64("fix64", bit_cast<uint64>(int64{6401}))
+ ->RenderUint64("u64", bit_cast<uint64>(int64{6402}))
->RenderInt64("i64", 6403L)
->RenderInt64("sf64", 6404L)
->RenderInt64("s64", 6405L)
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.cc b/src/google/protobuf/util/internal/protostream_objectwriter.cc
index 0b89ae2..527d5e7 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.cc
@@ -35,7 +35,6 @@
#include <unordered_map>
#include <unordered_set>
-#include <google/protobuf/stubs/time.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/util/internal/field_mask_utility.h>
@@ -43,6 +42,7 @@
#include <google/protobuf/util/internal/constants.h>
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/time.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/statusor.h>
@@ -334,7 +334,7 @@
invalid_ = true;
return;
}
- type_url_ = s.ValueOrDie();
+ type_url_ = s.value();
}
// Resolve the type url, and report an error if we failed to resolve it.
StatusOr<const google::protobuf::Type*> resolved_type =
@@ -345,7 +345,7 @@
return;
}
// At this point, type is never null.
- const google::protobuf::Type* type = resolved_type.ValueOrDie();
+ const google::protobuf::Type* type = resolved_type.value();
well_known_type_render_ = FindTypeRenderer(type_url_);
if (well_known_type_render_ != nullptr ||
@@ -480,6 +480,7 @@
return InsertIfNotPresent(map_keys_.get(), std::string(map_key));
}
+
ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
StringPiece name) {
if (invalid_depth() > 0) {
@@ -583,6 +584,7 @@
}
const google::protobuf::Field* field = BeginNamed(name, false);
+
if (field == nullptr) return this;
if (IsStruct(*field)) {
@@ -648,6 +650,7 @@
return this;
}
+
ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(
StringPiece name) {
if (invalid_depth() > 0) {
@@ -796,6 +799,7 @@
// name is not empty
const google::protobuf::Field* field = Lookup(name);
+
if (field == nullptr) {
IncrementInvalidDepth();
return this;
@@ -893,7 +897,7 @@
if (int_value.ok()) {
ow->ProtoWriter::RenderDataPiece(
"string_value",
- DataPiece(SimpleDtoa(int_value.ValueOrDie()), true));
+ DataPiece(SimpleDtoa(int_value.value()), true));
return Status();
}
}
@@ -906,7 +910,7 @@
if (int_value.ok()) {
ow->ProtoWriter::RenderDataPiece(
"string_value",
- DataPiece(SimpleDtoa(int_value.ValueOrDie()), true));
+ DataPiece(SimpleDtoa(int_value.value()), true));
return Status();
}
}
@@ -920,8 +924,7 @@
StatusOr<int64> int_value = data.ToInt64();
if (int_value.ok()) {
ow->ProtoWriter::RenderDataPiece(
- "string_value",
- DataPiece(StrCat(int_value.ValueOrDie()), true));
+ "string_value", DataPiece(StrCat(int_value.value()), true));
return Status();
}
}
@@ -935,8 +938,7 @@
StatusOr<uint64> int_value = data.ToUint64();
if (int_value.ok()) {
ow->ProtoWriter::RenderDataPiece(
- "string_value",
- DataPiece(StrCat(int_value.ValueOrDie()), true));
+ "string_value", DataPiece(StrCat(int_value.value()), true));
return Status();
}
}
@@ -949,7 +951,7 @@
if (float_value.ok()) {
ow->ProtoWriter::RenderDataPiece(
"string_value",
- DataPiece(SimpleDtoa(float_value.ValueOrDie()), true));
+ DataPiece(SimpleDtoa(float_value.value()), true));
return Status();
}
}
@@ -962,7 +964,7 @@
if (double_value.ok()) {
ow->ProtoWriter::RenderDataPiece(
"string_value",
- DataPiece(SimpleDtoa(double_value.ValueOrDie()), true));
+ DataPiece(SimpleDtoa(double_value.value()), true));
return Status();
}
}
@@ -1217,7 +1219,7 @@
// Map of functions that are responsible for rendering well known type
// represented by the key.
std::unordered_map<std::string, ProtoStreamObjectWriter::TypeRenderer>*
- ProtoStreamObjectWriter::renderers_ = NULL;
+ ProtoStreamObjectWriter::renderers_ = nullptr;
PROTOBUF_NAMESPACE_ID::internal::once_flag writer_renderers_init_;
void ProtoStreamObjectWriter::InitRendererMap() {
@@ -1272,7 +1274,7 @@
void ProtoStreamObjectWriter::DeleteRendererMap() {
delete ProtoStreamObjectWriter::renderers_;
- renderers_ = NULL;
+ renderers_ = nullptr;
}
ProtoStreamObjectWriter::TypeRenderer*
@@ -1296,9 +1298,9 @@
return true;
}
-void ProtoStreamObjectWriter::Push(StringPiece name,
- Item::ItemType item_type,
- bool is_placeholder, bool is_list) {
+void ProtoStreamObjectWriter::Push(
+ StringPiece name, Item::ItemType item_type, bool is_placeholder,
+ bool is_list) {
is_list ? ProtoWriter::StartList(name) : ProtoWriter::StartObject(name);
// invalid_depth == 0 means it is a successful StartObject or StartList.
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.h b/src/google/protobuf/util/internal/protostream_objectwriter.h
index fc015c6..f3aeb61 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.h
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.h
@@ -116,7 +116,7 @@
}
};
-// Constructor. Does not take ownership of any parameter passed in.
+ // Constructor. Does not take ownership of any parameter passed in.
ProtoStreamObjectWriter(TypeResolver* type_resolver,
const google::protobuf::Type& type,
strings::ByteSink* output, ErrorListener* listener,
@@ -241,7 +241,7 @@
int depth_;
// True if the type is a well-known type. Well-known types in Any
- // has a special formating:
+ // has a special formatting:
// {
// "@type": "type.googleapis.com/google.protobuf.XXX",
// "value": <JSON representation of the type>,
@@ -347,24 +347,24 @@
// Renders google.protobuf.Value in struct.proto. It picks the right oneof
// type based on value's type.
static util::Status RenderStructValue(ProtoStreamObjectWriter* ow,
- const DataPiece& value);
+ const DataPiece& data);
// Renders google.protobuf.Timestamp value.
static util::Status RenderTimestamp(ProtoStreamObjectWriter* ow,
- const DataPiece& value);
+ const DataPiece& data);
// Renders google.protobuf.FieldMask value.
static util::Status RenderFieldMask(ProtoStreamObjectWriter* ow,
- const DataPiece& value);
+ const DataPiece& data);
// Renders google.protobuf.Duration value.
static util::Status RenderDuration(ProtoStreamObjectWriter* ow,
- const DataPiece& value);
+ const DataPiece& data);
// Renders wrapper message types for primitive types in
// google/protobuf/wrappers.proto.
static util::Status RenderWrapperType(ProtoStreamObjectWriter* ow,
- const DataPiece& value);
+ const DataPiece& data);
static void InitRendererMap();
static void DeleteRendererMap();
@@ -382,11 +382,12 @@
// on the underlying ObjectWriter depending on whether is_list is false or
// not.
// is_placeholder conveys whether the item is a placeholder item or not.
- // Placeholder items are pushed when adding auxillary types' StartObject or
+ // Placeholder items are pushed when adding auxiliary types' StartObject or
// StartList calls.
void Push(StringPiece name, Item::ItemType item_type,
bool is_placeholder, bool is_list);
+
// Pops items from the stack. All placeholder items are popped until a
// non-placeholder item is found.
void Pop();
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
index 6b22b52..983043f 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
@@ -34,6 +34,7 @@
#include <google/protobuf/field_mask.pb.h>
#include <google/protobuf/timestamp.pb.h>
+#include <google/protobuf/type.pb.h>
#include <google/protobuf/wrappers.pb.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/descriptor.pb.h>
@@ -53,6 +54,7 @@
#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/util/type_resolver_util.h>
#include <google/protobuf/stubs/bytestream.h>
#include <google/protobuf/stubs/strutil.h>
#include <gtest/gtest.h>
@@ -63,6 +65,7 @@
namespace util {
namespace converter {
+
using proto_util_converter::testing::AnyM;
using proto_util_converter::testing::AnyOut;
using proto_util_converter::testing::Author;
@@ -169,7 +172,7 @@
MATCHER_P(HasObjectLocation, expected,
"Verifies the expected object location") {
std::string actual = get<0>(arg).ToString();
- if (actual.compare(expected) == 0) return true;
+ if (actual == expected) return true;
*result_listener << "actual location is: " << actual;
return false;
}
@@ -278,6 +281,7 @@
CheckOutput(message2);
}
+
TEST_P(ProtoStreamObjectWriterTest, IntEnumValuesAreAccepted) {
Book book;
book.set_title("Some Book");
@@ -2537,7 +2541,7 @@
CheckOutput(expected);
}
-TEST_P(ProtoStreamObjectWriterFieldMaskTest, MutipleMasksInCompactForm) {
+TEST_P(ProtoStreamObjectWriterFieldMaskTest, MultipleMasksInCompactForm) {
FieldMaskTest expected;
expected.set_id("1");
expected.mutable_single_mask()->add_paths("camel_case1");
diff --git a/src/google/protobuf/util/internal/testdata/books.proto b/src/google/protobuf/util/internal/testdata/books.proto
index 4f02ae1..328c5ce 100644
--- a/src/google/protobuf/util/internal/testdata/books.proto
+++ b/src/google/protobuf/util/internal/testdata/books.proto
@@ -34,6 +34,7 @@
// Some of the older enums don't use CAPITALS_WITH_UNDERSCORES for testing.
// LINT: LEGACY_NAMES
+// LINT: ALLOW_GROUPS
syntax = "proto2";
@@ -212,3 +213,39 @@
message TestJsonName2 {
optional int32 another_value = 1 [json_name = "value"];
}
+
+message TestPrimitiveFieldsWithSameJsonName {
+ optional string val_str1 = 1;
+ optional string val_str_1 = 2;
+
+ optional int32 val_int321 = 3;
+ optional int32 val_int32_1 = 4;
+
+ optional uint32 val_uint321 = 5;
+ optional uint32 val_uint32_1 = 6;
+
+ optional int64 val_int641 = 7;
+ optional int64 val_int64_1 = 8;
+
+ optional uint64 val_uint641 = 9;
+ optional uint64 val_uint64_1 = 10;
+
+ optional bool val_bool1 = 11;
+ optional bool val_bool_1 = 12;
+
+ optional double val_double1 = 13;
+ optional double val_double_1 = 14;
+
+ optional float val_float1 = 15;
+ optional float val_float_1 = 16;
+}
+
+message TestRepeatedFieldsWithSameJsonName {
+ repeated string rep_str1 = 1;
+ repeated string rep_str_1 = 2;
+}
+
+message TestMessageFieldsWithSameJsonName {
+ optional Primitive prim1 = 1;
+ optional Primitive prim_1 = 2;
+}
diff --git a/src/google/protobuf/util/internal/type_info.cc b/src/google/protobuf/util/internal/type_info.cc
index 818df64..e8b2103 100644
--- a/src/google/protobuf/util/internal/type_info.cc
+++ b/src/google/protobuf/util/internal/type_info.cc
@@ -81,7 +81,7 @@
const google::protobuf::Type* GetTypeByTypeUrl(
StringPiece type_url) const override {
StatusOrType result = ResolveTypeUrl(type_url);
- return result.ok() ? result.ValueOrDie() : NULL;
+ return result.ok() ? result.value() : NULL;
}
const google::protobuf::Enum* GetEnumByTypeUrl(
@@ -89,7 +89,7 @@
std::map<StringPiece, StatusOrEnum>::iterator it =
cached_enums_.find(type_url);
if (it != cached_enums_.end()) {
- return it->second.ok() ? it->second.ValueOrDie() : NULL;
+ return it->second.ok() ? it->second.value() : NULL;
}
// Stores the string value so it can be referenced using StringPiece in the
// cached_enums_ map.
@@ -102,7 +102,7 @@
StatusOrEnum result =
status.ok() ? StatusOrEnum(enum_type.release()) : StatusOrEnum(status);
cached_enums_[string_type_url] = result;
- return result.ok() ? result.ValueOrDie() : NULL;
+ return result.ok() ? result.value() : NULL;
}
const google::protobuf::Field* FindField(
@@ -134,7 +134,7 @@
cached_types->begin();
it != cached_types->end(); ++it) {
if (it->second.ok()) {
- delete it->second.ValueOrDie();
+ delete it->second.value();
}
}
}
diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc
index e13bdb7..9851cc5 100644
--- a/src/google/protobuf/util/json_util_test.cc
+++ b/src/google/protobuf/util/json_util_test.cc
@@ -241,7 +241,7 @@
}
TEST_F(JsonUtilTest, ParseMessage) {
- // Some random message but good enough to verify that the parsing warpper
+ // Some random message but good enough to verify that the parsing wrapper
// functions are working properly.
std::string input =
"{\n"
diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc
index c9f10ba..f5e0860 100644
--- a/src/google/protobuf/util/message_differencer.cc
+++ b/src/google/protobuf/util/message_differencer.cc
@@ -576,12 +576,12 @@
bool unknown_compare_result = true;
// Ignore unknown fields in EQUIVALENT mode
if (message_field_comparison_ != EQUIVALENT) {
- const UnknownFieldSet* unknown_field_set1 =
- &reflection1->GetUnknownFields(message1);
- const UnknownFieldSet* unknown_field_set2 =
- &reflection2->GetUnknownFields(message2);
- if (!CompareUnknownFields(message1, message2, *unknown_field_set1,
- *unknown_field_set2, parent_fields)) {
+ const UnknownFieldSet& unknown_field_set1 =
+ reflection1->GetUnknownFields(message1);
+ const UnknownFieldSet& unknown_field_set2 =
+ reflection2->GetUnknownFields(message2);
+ if (!CompareUnknownFields(message1, message2, unknown_field_set1,
+ unknown_field_set2, parent_fields)) {
if (reporter_ == NULL) {
return false;
}
@@ -813,7 +813,7 @@
continue;
}
- // By this point, field1 and field2 are guarenteed to point to the same
+ // By this point, field1 and field2 are guaranteed to point to the same
// field, so we can now compare the values.
if (IsIgnored(message1, message2, field1, *parent_fields)) {
// Ignore this field. Report and move on.
@@ -1243,7 +1243,7 @@
}
data->reset(dynamic_message_factory_->GetPrototype(desc)->New());
std::string serialized_value = reflection->GetString(any, value_field);
- if (!(*data)->ParseFromString(serialized_value)) {
+ if (!(*data)->ParsePartialFromString(serialized_value)) {
GOOGLE_DLOG(ERROR) << "Failed to parse value for " << full_type_name;
return false;
}
@@ -1549,7 +1549,7 @@
bool MaximumMatcher::FindArgumentPathDFS(int v, std::vector<bool>* visited) {
(*visited)[v] = true;
// We try to match those un-matched nodes on the right side first. This is
- // the step that the navie greedy matching algorithm uses. In the best cases
+ // the step that the naive greedy matching algorithm uses. In the best cases
// where the greedy algorithm can find a maximum matching, we will always
// find a match in this step and the performance will be identical to the
// greedy algorithm.
@@ -1561,7 +1561,7 @@
}
}
// Then we try those already matched nodes and see if we can find an
- // alternaive match for the node matched to them.
+ // alternative match for the node matched to them.
// The greedy algorithm will stop before this and fail to produce the
// correct result.
for (int i = 0; i < count2_; ++i) {
diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h
index 21cf374..f7317c8 100644
--- a/src/google/protobuf/util/message_differencer.h
+++ b/src/google/protobuf/util/message_differencer.h
@@ -225,6 +225,19 @@
// FieldDescriptors. The first will be the field of the embedded message
// itself and the second will be the actual field in the embedded message
// that was added/deleted/modified.
+ // Fields will be reported in PostTraversalOrder.
+ // For example, given following proto, if both baz and quux are changed.
+ // foo {
+ // bar {
+ // baz: 1
+ // quux: 2
+ // }
+ // }
+ // ReportModified will be invoked with following order:
+ // 1. foo.bar.baz or foo.bar.quux
+ // 2. foo.bar.quux or foo.bar.baz
+ // 2. foo.bar
+ // 3. foo
class PROTOBUF_EXPORT Reporter {
public:
Reporter();
diff --git a/src/google/protobuf/util/message_differencer_unittest.cc b/src/google/protobuf/util/message_differencer_unittest.cc
index b57062a..637d4d3 100644
--- a/src/google/protobuf/util/message_differencer_unittest.cc
+++ b/src/google/protobuf/util/message_differencer_unittest.cc
@@ -3444,6 +3444,7 @@
RunWithResult(&differencer, msg1, msg2, true));
}
+
TEST_F(MatchingTest, MatchesAppearInPostTraversalOrderForMovedFields) {
protobuf_unittest::TestDiffMessage msg1, msg2;
protobuf_unittest::TestDiffMessage::Item* item;
diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc
index e615627..4b80e7c 100644
--- a/src/google/protobuf/util/time_util.cc
+++ b/src/google/protobuf/util/time_util.cc
@@ -30,13 +30,14 @@
#include <google/protobuf/util/time_util.h>
-#include <google/protobuf/stubs/int128.h>
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/time.h>
#include <google/protobuf/duration.pb.h>
#include <google/protobuf/timestamp.pb.h>
+#include <google/protobuf/stubs/int128.h>
+#include <google/protobuf/stubs/time.h>
+// Must go after other includes.
#include <google/protobuf/port_def.inc>
namespace google {
diff --git a/src/google/protobuf/util/time_util_test.cc b/src/google/protobuf/util/time_util_test.cc
index 9d6c564..b6d3813 100644
--- a/src/google/protobuf/util/time_util_test.cc
+++ b/src/google/protobuf/util/time_util_test.cc
@@ -83,7 +83,7 @@
EXPECT_TRUE(TimeUtil::FromString("1970-01-01T00:00:00.0000001Z", &time));
EXPECT_EQ(100, TimeUtil::TimestampToNanoseconds(time));
- // Also accpets offsets.
+ // Also accepts offsets.
EXPECT_TRUE(TimeUtil::FromString("1970-01-01T00:00:00-08:00", &time));
EXPECT_EQ(8 * 3600, TimeUtil::TimestampToSeconds(time));
}
@@ -119,10 +119,10 @@
// Duration must support range from -315,576,000,000s to +315576000000s
// which includes negative values.
EXPECT_TRUE(TimeUtil::FromString("315576000000.999999999s", &d));
- EXPECT_EQ(315576000000LL, d.seconds());
+ EXPECT_EQ(int64{315576000000}, d.seconds());
EXPECT_EQ(999999999, d.nanos());
EXPECT_TRUE(TimeUtil::FromString("-315576000000.999999999s", &d));
- EXPECT_EQ(-315576000000LL, d.seconds());
+ EXPECT_EQ(int64{-315576000000}, d.seconds());
EXPECT_EQ(-999999999, d.nanos());
}
@@ -278,20 +278,22 @@
// Multiplication should not overflow if the result fits into the supported
// range of Duration (intermediate result may be larger than int64).
EXPECT_EQ("315575999684.424s",
- TimeUtil::ToString((one_second - one_nano) * 315576000000LL));
+ TimeUtil::ToString((one_second - one_nano) * int64{315576000000}));
EXPECT_EQ("-315575999684.424s",
- TimeUtil::ToString((one_nano - one_second) * 315576000000LL));
- EXPECT_EQ("-315575999684.424s",
- TimeUtil::ToString((one_second - one_nano) * (-315576000000LL)));
+ TimeUtil::ToString((one_nano - one_second) * int64{315576000000}));
+ EXPECT_EQ("-315575999684.424s", TimeUtil::ToString((one_second - one_nano) *
+ (int64{-315576000000})));
// Test / and %
EXPECT_EQ("0.999999999s", TimeUtil::ToString(a / 2));
EXPECT_EQ("-0.999999999s", TimeUtil::ToString(b / 2));
- Duration large = TimeUtil::SecondsToDuration(315576000000LL) - one_nano;
+ Duration large = TimeUtil::SecondsToDuration(int64{315576000000}) - one_nano;
// We have to handle division with values beyond 64 bits.
- EXPECT_EQ("0.999999999s", TimeUtil::ToString(large / 315576000000LL));
- EXPECT_EQ("-0.999999999s", TimeUtil::ToString((-large) / 315576000000LL));
- EXPECT_EQ("-0.999999999s", TimeUtil::ToString(large / (-315576000000LL)));
+ EXPECT_EQ("0.999999999s", TimeUtil::ToString(large / int64{315576000000}));
+ EXPECT_EQ("-0.999999999s",
+ TimeUtil::ToString((-large) / int64{315576000000}));
+ EXPECT_EQ("-0.999999999s",
+ TimeUtil::ToString(large / (int64{-315576000000})));
Duration large2 = large + one_nano;
EXPECT_EQ(large, large % large2);
EXPECT_EQ(-large, (-large) % large2);
diff --git a/src/google/protobuf/util/type_resolver.h b/src/google/protobuf/util/type_resolver.h
index 732d390..698441b 100644
--- a/src/google/protobuf/util/type_resolver.h
+++ b/src/google/protobuf/util/type_resolver.h
@@ -46,7 +46,7 @@
class DescriptorPool;
namespace util {
-// Abstract interface for a type resovler.
+// Abstract interface for a type resolver.
//
// Implementations of this interface must be thread-safe.
class PROTOBUF_EXPORT TypeResolver {
diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc
index f60b774..444510c 100644
--- a/src/google/protobuf/wire_format.cc
+++ b/src/google/protobuf/wire_format.cc
@@ -42,6 +42,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/parse_context.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
@@ -49,6 +50,7 @@
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/map_field_inl.h>
+#include <google/protobuf/message.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/unknown_field_set.h>
@@ -653,6 +655,379 @@
input, MSReflective{message->GetReflection(), message});
}
+struct WireFormat::MessageSetParser {
+ const char* _InternalParse(const char* ptr, internal::ParseContext* ctx) {
+ // Parse a MessageSetItem
+ auto metadata = reflection->MutableInternalMetadata(msg);
+ std::string payload;
+ uint32 type_id = 0;
+ while (!ctx->Done(&ptr)) {
+ // We use 64 bit tags in order to allow typeid's that span the whole
+ // range of 32 bit numbers.
+ uint32 tag = static_cast<uint8>(*ptr++);
+ if (tag == WireFormatLite::kMessageSetTypeIdTag) {
+ uint64 tmp;
+ ptr = ParseBigVarint(ptr, &tmp);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ type_id = tmp;
+ if (!payload.empty()) {
+ const FieldDescriptor* field;
+ if (ctx->data().pool == nullptr) {
+ field = reflection->FindKnownExtensionByNumber(type_id);
+ } else {
+ field =
+ ctx->data().pool->FindExtensionByNumber(descriptor, type_id);
+ }
+ if (field == nullptr || field->message_type() == nullptr) {
+ WriteLengthDelimited(
+ type_id, payload,
+ metadata->mutable_unknown_fields<UnknownFieldSet>());
+ } else {
+ Message* value =
+ field->is_repeated()
+ ? reflection->AddMessage(msg, field, ctx->data().factory)
+ : reflection->MutableMessage(msg, field,
+ ctx->data().factory);
+ const char* p;
+ // We can't use regular parse from string as we have to track
+ // proper recursion depth and descriptor pools.
+ ParseContext tmp_ctx(ctx->depth(), false, &p, payload);
+ tmp_ctx.data().pool = ctx->data().pool;
+ tmp_ctx.data().factory = ctx->data().factory;
+ GOOGLE_PROTOBUF_PARSER_ASSERT(value->_InternalParse(p, &tmp_ctx) &&
+ tmp_ctx.EndedAtLimit());
+ }
+ type_id = 0;
+ }
+ continue;
+ } else if (tag == WireFormatLite::kMessageSetMessageTag) {
+ if (type_id == 0) {
+ int32 size = ReadSize(&ptr);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ptr = ctx->ReadString(ptr, size, &payload);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ } else {
+ // We're now parsing the payload
+ const FieldDescriptor* field = nullptr;
+ if (descriptor->IsExtensionNumber(type_id)) {
+ if (ctx->data().pool == nullptr) {
+ field = reflection->FindKnownExtensionByNumber(type_id);
+ } else {
+ field =
+ ctx->data().pool->FindExtensionByNumber(descriptor, type_id);
+ }
+ }
+ ptr = WireFormat::_InternalParseAndMergeField(
+ msg, ptr, ctx, static_cast<uint64>(type_id) * 8 + 2, reflection,
+ field);
+ type_id = 0;
+ }
+ } else {
+ // An unknown field in MessageSetItem.
+ ptr = ReadTag(ptr - 1, &tag);
+ if (tag == 0 || (tag & 7) == WireFormatLite::WIRETYPE_END_GROUP) {
+ ctx->SetLastTag(tag);
+ return ptr;
+ }
+ // Skip field.
+ ptr = internal::UnknownFieldParse(
+ tag, static_cast<std::string*>(nullptr), ptr, ctx);
+ }
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ }
+ return ptr;
+ }
+
+ const char* ParseMessageSet(const char* ptr, internal::ParseContext* ctx) {
+ while (!ctx->Done(&ptr)) {
+ uint32 tag;
+ ptr = ReadTag(ptr, &tag);
+ if (PROTOBUF_PREDICT_FALSE(ptr == nullptr)) return nullptr;
+ if (tag == 0 || (tag & 7) == WireFormatLite::WIRETYPE_END_GROUP) {
+ ctx->SetLastTag(tag);
+ break;
+ }
+ if (tag == WireFormatLite::kMessageSetItemStartTag) {
+ // A message set item starts
+ ptr = ctx->ParseGroup(this, ptr, tag);
+ } else {
+ // Parse other fields as normal extensions.
+ int field_number = WireFormatLite::GetTagFieldNumber(tag);
+ const FieldDescriptor* field = nullptr;
+ if (descriptor->IsExtensionNumber(field_number)) {
+ if (ctx->data().pool == nullptr) {
+ field = reflection->FindKnownExtensionByNumber(field_number);
+ } else {
+ field = ctx->data().pool->FindExtensionByNumber(descriptor,
+ field_number);
+ }
+ }
+ ptr = WireFormat::_InternalParseAndMergeField(msg, ptr, ctx, tag,
+ reflection, field);
+ }
+ if (PROTOBUF_PREDICT_FALSE(ptr == nullptr)) return nullptr;
+ }
+ return ptr;
+ }
+
+ Message* msg;
+ const Descriptor* descriptor;
+ const Reflection* reflection;
+};
+
+const char* WireFormat::_InternalParse(Message* msg, const char* ptr,
+ internal::ParseContext* ctx) {
+ const Descriptor* descriptor = msg->GetDescriptor();
+ const Reflection* reflection = msg->GetReflection();
+ GOOGLE_DCHECK(descriptor);
+ GOOGLE_DCHECK(reflection);
+ if (descriptor->options().message_set_wire_format()) {
+ MessageSetParser message_set{msg, descriptor, reflection};
+ return message_set.ParseMessageSet(ptr, ctx);
+ }
+ while (!ctx->Done(&ptr)) {
+ uint32 tag;
+ ptr = ReadTag(ptr, &tag);
+ if (PROTOBUF_PREDICT_FALSE(ptr == nullptr)) return nullptr;
+ if (tag == 0 || (tag & 7) == WireFormatLite::WIRETYPE_END_GROUP) {
+ ctx->SetLastTag(tag);
+ break;
+ }
+ const FieldDescriptor* field = nullptr;
+
+ int field_number = WireFormatLite::GetTagFieldNumber(tag);
+ field = descriptor->FindFieldByNumber(field_number);
+
+ // If that failed, check if the field is an extension.
+ if (field == nullptr && descriptor->IsExtensionNumber(field_number)) {
+ if (ctx->data().pool == nullptr) {
+ field = reflection->FindKnownExtensionByNumber(field_number);
+ } else {
+ field =
+ ctx->data().pool->FindExtensionByNumber(descriptor, field_number);
+ }
+ }
+
+ ptr = _InternalParseAndMergeField(msg, ptr, ctx, tag, reflection, field);
+ if (PROTOBUF_PREDICT_FALSE(ptr == nullptr)) return nullptr;
+ }
+ return ptr;
+}
+
+const char* WireFormat::_InternalParseAndMergeField(
+ Message* msg, const char* ptr, internal::ParseContext* ctx, uint64 tag,
+ const Reflection* reflection, const FieldDescriptor* field) {
+ if (field == nullptr) {
+ // unknown field set parser takes 64bit tags, because message set type ids
+ // span the full 32 bit range making the tag span [0, 2^35) range.
+ return internal::UnknownFieldParse(
+ tag, reflection->MutableUnknownFields(msg), ptr, ctx);
+ }
+ if (WireFormatLite::GetTagWireType(tag) !=
+ WireTypeForFieldType(field->type())) {
+ if (field->is_packable() && WireFormatLite::GetTagWireType(tag) ==
+ WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
+ switch (field->type()) {
+#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
+ case FieldDescriptor::TYPE_##TYPE: { \
+ ptr = internal::Packed##CPPTYPE_METHOD##Parser( \
+ reflection->MutableRepeatedFieldInternal<CPPTYPE>(msg, field), ptr, \
+ ctx); \
+ return ptr; \
+ }
+
+ HANDLE_PACKED_TYPE(INT32, int32, Int32)
+ HANDLE_PACKED_TYPE(INT64, int64, Int64)
+ HANDLE_PACKED_TYPE(SINT32, int32, SInt32)
+ HANDLE_PACKED_TYPE(SINT64, int64, SInt64)
+ HANDLE_PACKED_TYPE(UINT32, uint32, UInt32)
+ HANDLE_PACKED_TYPE(UINT64, uint64, UInt64)
+
+ HANDLE_PACKED_TYPE(FIXED32, uint32, Fixed32)
+ HANDLE_PACKED_TYPE(FIXED64, uint64, Fixed64)
+ HANDLE_PACKED_TYPE(SFIXED32, int32, SFixed32)
+ HANDLE_PACKED_TYPE(SFIXED64, int64, SFixed64)
+
+ HANDLE_PACKED_TYPE(FLOAT, float, Float)
+ HANDLE_PACKED_TYPE(DOUBLE, double, Double)
+
+ HANDLE_PACKED_TYPE(BOOL, bool, Bool)
+#undef HANDLE_PACKED_TYPE
+
+ case FieldDescriptor::TYPE_ENUM: {
+ auto rep_enum =
+ reflection->MutableRepeatedFieldInternal<int>(msg, field);
+ bool open_enum = false;
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ||
+ open_enum) {
+ ptr = internal::PackedEnumParser(rep_enum, ptr, ctx);
+ } else {
+ return ctx->ReadPackedVarint(
+ ptr, [rep_enum, field, reflection, msg](uint64 val) {
+ if (field->enum_type()->FindValueByNumber(val) != nullptr) {
+ rep_enum->Add(val);
+ } else {
+ WriteVarint(field->number(), val,
+ reflection->MutableUnknownFields(msg));
+ }
+ });
+ }
+ return ptr;
+ }
+
+ case FieldDescriptor::TYPE_STRING:
+ case FieldDescriptor::TYPE_GROUP:
+ case FieldDescriptor::TYPE_MESSAGE:
+ case FieldDescriptor::TYPE_BYTES:
+ GOOGLE_LOG(FATAL) << "Can't reach";
+ return nullptr;
+ }
+ } else {
+ // mismatched wiretype;
+ return internal::UnknownFieldParse(
+ tag, reflection->MutableUnknownFields(msg), ptr, ctx);
+ }
+ }
+
+ // Non-packed value
+ bool utf8_check = false;
+ bool strict_utf8_check = false;
+ switch (field->type()) {
+#define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
+ case FieldDescriptor::TYPE_##TYPE: { \
+ CPPTYPE value; \
+ ptr = VarintParse(ptr, &value); \
+ if (ptr == nullptr) return nullptr; \
+ if (field->is_repeated()) { \
+ reflection->Add##CPPTYPE_METHOD(msg, field, value); \
+ } else { \
+ reflection->Set##CPPTYPE_METHOD(msg, field, value); \
+ } \
+ return ptr; \
+ }
+
+ HANDLE_TYPE(BOOL, uint64, Bool)
+ HANDLE_TYPE(INT32, uint32, Int32)
+ HANDLE_TYPE(INT64, uint64, Int64)
+ HANDLE_TYPE(UINT32, uint32, UInt32)
+ HANDLE_TYPE(UINT64, uint64, UInt64)
+
+ case FieldDescriptor::TYPE_SINT32: {
+ int32 value = ReadVarintZigZag32(&ptr);
+ if (ptr == nullptr) return nullptr;
+ if (field->is_repeated()) {
+ reflection->AddInt32(msg, field, value);
+ } else {
+ reflection->SetInt32(msg, field, value);
+ }
+ return ptr;
+ }
+ case FieldDescriptor::TYPE_SINT64: {
+ int64 value = ReadVarintZigZag64(&ptr);
+ if (ptr == nullptr) return nullptr;
+ if (field->is_repeated()) {
+ reflection->AddInt64(msg, field, value);
+ } else {
+ reflection->SetInt64(msg, field, value);
+ }
+ return ptr;
+ }
+#undef HANDLE_TYPE
+#define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
+ case FieldDescriptor::TYPE_##TYPE: { \
+ CPPTYPE value; \
+ value = UnalignedLoad<CPPTYPE>(ptr); \
+ ptr += sizeof(CPPTYPE); \
+ if (field->is_repeated()) { \
+ reflection->Add##CPPTYPE_METHOD(msg, field, value); \
+ } else { \
+ reflection->Set##CPPTYPE_METHOD(msg, field, value); \
+ } \
+ return ptr; \
+ }
+
+ HANDLE_TYPE(FIXED32, uint32, UInt32)
+ HANDLE_TYPE(FIXED64, uint64, UInt64)
+ HANDLE_TYPE(SFIXED32, int32, Int32)
+ HANDLE_TYPE(SFIXED64, int64, Int64)
+
+ HANDLE_TYPE(FLOAT, float, Float)
+ HANDLE_TYPE(DOUBLE, double, Double)
+
+#undef HANDLE_TYPE
+
+ case FieldDescriptor::TYPE_ENUM: {
+ uint32 value;
+ ptr = VarintParse(ptr, &value);
+ if (ptr == nullptr) return nullptr;
+ if (field->is_repeated()) {
+ reflection->AddEnumValue(msg, field, value);
+ } else {
+ reflection->SetEnumValue(msg, field, value);
+ }
+ return ptr;
+ }
+
+ // Handle strings separately so that we can optimize the ctype=CORD case.
+ case FieldDescriptor::TYPE_STRING:
+ utf8_check = true;
+ strict_utf8_check = StrictUtf8Check(field);
+ PROTOBUF_FALLTHROUGH_INTENDED;
+ case FieldDescriptor::TYPE_BYTES: {
+ int size = ReadSize(&ptr);
+ if (ptr == nullptr) return nullptr;
+ std::string value;
+ ptr = ctx->ReadString(ptr, size, &value);
+ if (ptr == nullptr) return nullptr;
+ if (utf8_check) {
+ if (strict_utf8_check) {
+ if (!WireFormatLite::VerifyUtf8String(value.data(), value.length(),
+ WireFormatLite::PARSE,
+ field->full_name().c_str())) {
+ return nullptr;
+ }
+ } else {
+ VerifyUTF8StringNamedField(value.data(), value.length(), PARSE,
+ field->full_name().c_str());
+ }
+ }
+ if (field->is_repeated()) {
+ reflection->AddString(msg, field, value);
+ } else {
+ reflection->SetString(msg, field, value);
+ }
+ return ptr;
+ }
+
+ case FieldDescriptor::TYPE_GROUP: {
+ Message* sub_message;
+ if (field->is_repeated()) {
+ sub_message = reflection->AddMessage(msg, field, ctx->data().factory);
+ } else {
+ sub_message =
+ reflection->MutableMessage(msg, field, ctx->data().factory);
+ }
+
+ return ctx->ParseGroup(sub_message, ptr, tag);
+ }
+
+ case FieldDescriptor::TYPE_MESSAGE: {
+ Message* sub_message;
+ if (field->is_repeated()) {
+ sub_message = reflection->AddMessage(msg, field, ctx->data().factory);
+ } else {
+ sub_message =
+ reflection->MutableMessage(msg, field, ctx->data().factory);
+ }
+ return ctx->ParseMessage(sub_message, ptr);
+ }
+ }
+
+ // GCC 8 complains about control reaching end of non-void function here.
+ // Let's keep it happy by returning a nullptr.
+ return nullptr;
+}
+
// ===================================================================
uint8* WireFormat::_InternalSerialize(const Message& message, uint8* target,
@@ -1359,9 +1734,11 @@
}
// Compute the size of the UnknownFieldSet on the wire.
-size_t ComputeUnknownFieldsSize(const InternalMetadataWithArena& metadata,
+size_t ComputeUnknownFieldsSize(const InternalMetadata& metadata,
size_t total_size, CachedSize* cached_size) {
- total_size += WireFormat::ComputeUnknownFieldsSize(metadata.unknown_fields());
+ total_size += WireFormat::ComputeUnknownFieldsSize(
+ metadata.unknown_fields<UnknownFieldSet>(
+ UnknownFieldSet::default_instance));
cached_size->Set(ToCachedSize(total_size));
return total_size;
}
diff --git a/src/google/protobuf/wire_format.h b/src/google/protobuf/wire_format.h
index 57582e3..d42cefb 100644
--- a/src/google/protobuf/wire_format.h
+++ b/src/google/protobuf/wire_format.h
@@ -42,9 +42,12 @@
#include <string>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/parse_context.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/stubs/casts.h>
@@ -65,7 +68,7 @@
namespace internal {
// This class is for internal use by the protocol buffer library and by
-// protocol-complier-generated message classes. It must not be called
+// protocol-compiler-generated message classes. It must not be called
// directly by clients.
//
// This class contains code for implementing the binary protocol buffer
@@ -106,6 +109,11 @@
static bool ParseAndMergePartial(io::CodedInputStream* input,
Message* message);
+ // This is meant for internal protobuf use (WireFormat is an internal class).
+ // This is the reflective implementation of the _InternalParse functionality.
+ static const char* _InternalParse(Message* msg, const char* ptr,
+ internal::ParseContext* ctx);
+
// Serialize a message in protocol buffer wire format.
//
// Any embedded messages within the message must have their correct sizes
@@ -237,7 +245,7 @@
const Message& message);
// Parse/serialize a MessageSet::Item group. Used with messages that use
- // opion message_set_wire_format = true.
+ // option message_set_wire_format = true.
static bool ParseAndMergeMessageSetItem(io::CodedInputStream* input,
Message* message);
static void SerializeMessageSetItemWithCachedSizes(
@@ -275,6 +283,7 @@
Operation op, const char* field_name);
private:
+ struct MessageSetParser;
// Skip a MessageSet field.
static bool SkipMessageSetField(io::CodedInputStream* input,
uint32 field_number,
@@ -285,6 +294,12 @@
const FieldDescriptor* field,
Message* message,
io::CodedInputStream* input);
+ // Parses the value from the wire that belongs to tag.
+ static const char* _InternalParseAndMergeField(Message* msg, const char* ptr,
+ internal::ParseContext* ctx,
+ uint64 tag,
+ const Reflection* reflection,
+ const FieldDescriptor* field);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WireFormat);
};
@@ -380,8 +395,8 @@
// Compute the size of the UnknownFieldSet on the wire.
PROTOBUF_EXPORT
-size_t ComputeUnknownFieldsSize(const InternalMetadataWithArena& metadata,
- size_t size, CachedSize* cached_size);
+size_t ComputeUnknownFieldsSize(const InternalMetadata& metadata, size_t size,
+ CachedSize* cached_size);
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h
index 449517a..c742fe8 100644
--- a/src/google/protobuf/wire_format_lite.h
+++ b/src/google/protobuf/wire_format_lite.h
@@ -49,6 +49,7 @@
#include <google/protobuf/message_lite.h>
#include <google/protobuf/port.h>
#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/stubs/casts.h>
// Do UTF-8 validation on string type in Debug build only
#ifndef NDEBUG
@@ -73,7 +74,7 @@
#include <google/protobuf/port_def.inc>
// This class is for internal use by the protocol buffer library and by
-// protocol-complier-generated message classes. It must not be called
+// protocol-compiler-generated message classes. It must not be called
// directly by clients.
//
// This class contains helpers for implementing the binary protocol buffer
@@ -155,9 +156,9 @@
}
// Number of bits in a tag which identify the wire type.
- static const int kTagTypeBits = 3;
+ static constexpr int kTagTypeBits = 3;
// Mask for those bits.
- static const uint32 kTagTypeMask = (1 << kTagTypeBits) - 1;
+ static constexpr uint32 kTagTypeMask = (1 << kTagTypeBits) - 1;
// Helper functions for encoding and decoding tags. (Inlined below and in
// _inl.h)
@@ -209,9 +210,9 @@
// required string message = 3;
// }
// }
- static const int kMessageSetItemNumber = 1;
- static const int kMessageSetTypeIdNumber = 2;
- static const int kMessageSetMessageNumber = 3;
+ static constexpr int kMessageSetItemNumber = 1;
+ static constexpr int kMessageSetTypeIdNumber = 2;
+ static constexpr int kMessageSetMessageNumber = 3;
static const int kMessageSetItemStartTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
kMessageSetItemNumber, WireFormatLite::WIRETYPE_START_GROUP);
static const int kMessageSetItemEndTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
@@ -684,13 +685,13 @@
static size_t EnumSize(const RepeatedField<int>& value);
// These types always have the same size.
- static const size_t kFixed32Size = 4;
- static const size_t kFixed64Size = 8;
- static const size_t 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 constexpr size_t kFixed32Size = 4;
+ static constexpr size_t kFixed64Size = 8;
+ static constexpr size_t kSFixed32Size = 4;
+ static constexpr size_t kSFixed64Size = 8;
+ static constexpr size_t kFloatSize = 4;
+ static constexpr size_t kDoubleSize = 8;
+ static constexpr size_t kBoolSize = 1;
static inline size_t StringSize(const std::string& value);
static inline size_t BytesSize(const std::string& value);
@@ -806,39 +807,19 @@
}
inline uint32 WireFormatLite::EncodeFloat(float value) {
- union {
- float f;
- uint32 i;
- };
- f = value;
- return i;
+ return bit_cast<uint32>(value);
}
inline float WireFormatLite::DecodeFloat(uint32 value) {
- union {
- float f;
- uint32 i;
- };
- i = value;
- return f;
+ return bit_cast<float>(value);
}
inline uint64 WireFormatLite::EncodeDouble(double value) {
- union {
- double f;
- uint64 i;
- };
- f = value;
- return i;
+ return bit_cast<uint64>(value);
}
inline double WireFormatLite::DecodeDouble(uint64 value) {
- union {
- double f;
- uint64 i;
- };
- i = value;
- return f;
+ return bit_cast<double>(value);
}
// ZigZag Transform: Encodes signed integers so that they can be
diff --git a/src/google/protobuf/wire_format_unittest.cc b/src/google/protobuf/wire_format_unittest.cc
index ff502d6..24cb58f 100644
--- a/src/google/protobuf/wire_format_unittest.cc
+++ b/src/google/protobuf/wire_format_unittest.cc
@@ -33,6 +33,10 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/wire_format.h>
+
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_mset.pb.h>
@@ -40,11 +44,9 @@
#include <google/protobuf/unittest_proto3_arena.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/descriptor.h>
-
-#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
#include <google/protobuf/stubs/casts.h>
diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc
index 8c8ce68..be039b4 100644
--- a/src/google/protobuf/wrappers.pb.cc
+++ b/src/google/protobuf/wrappers.pb.cc
@@ -290,16 +290,15 @@
&scc_info_UInt64Value_google_2fprotobuf_2fwrappers_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once;
-static bool descriptor_table_google_2fprotobuf_2fwrappers_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fwrappers_2eproto = {
- &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fwrappers_2eproto, "google/protobuf/wrappers.proto", 447,
+ false, false, descriptor_table_protodef_google_2fprotobuf_2fwrappers_2eproto, "google/protobuf/wrappers.proto", 447,
&descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, descriptor_table_google_2fprotobuf_2fwrappers_2eproto_sccs, descriptor_table_google_2fprotobuf_2fwrappers_2eproto_deps, 9, 0,
schemas, file_default_instances, TableStruct_google_2fprotobuf_2fwrappers_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fwrappers_2eproto, 9, file_level_enum_descriptors_google_2fprotobuf_2fwrappers_2eproto, file_level_service_descriptors_google_2fprotobuf_2fwrappers_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
-static bool dynamic_init_dummy_google_2fprotobuf_2fwrappers_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fwrappers_2eproto), true);
+static bool dynamic_init_dummy_google_2fprotobuf_2fwrappers_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fwrappers_2eproto)), true);
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
@@ -310,22 +309,15 @@
public:
};
-DoubleValue::DoubleValue()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.DoubleValue)
-}
DoubleValue::DoubleValue(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DoubleValue)
}
DoubleValue::DoubleValue(const DoubleValue& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.DoubleValue)
}
@@ -337,10 +329,11 @@
DoubleValue::~DoubleValue() {
// @@protoc_insertion_point(destructor:google.protobuf.DoubleValue)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void DoubleValue::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void DoubleValue::ArenaDtor(void* object) {
@@ -365,12 +358,12 @@
(void) cached_has_bits;
value_ = 0;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* DoubleValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -389,7 +382,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -417,7 +412,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DoubleValue)
return target;
@@ -463,7 +458,7 @@
void DoubleValue::MergeFrom(const DoubleValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DoubleValue)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -492,7 +487,7 @@
void DoubleValue::InternalSwap(DoubleValue* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(value_, other->value_);
}
@@ -509,22 +504,15 @@
public:
};
-FloatValue::FloatValue()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.FloatValue)
-}
FloatValue::FloatValue(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FloatValue)
}
FloatValue::FloatValue(const FloatValue& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.FloatValue)
}
@@ -536,10 +524,11 @@
FloatValue::~FloatValue() {
// @@protoc_insertion_point(destructor:google.protobuf.FloatValue)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void FloatValue::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void FloatValue::ArenaDtor(void* object) {
@@ -564,12 +553,12 @@
(void) cached_has_bits;
value_ = 0;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* FloatValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -588,7 +577,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -616,7 +607,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FloatValue)
return target;
@@ -662,7 +653,7 @@
void FloatValue::MergeFrom(const FloatValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FloatValue)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -691,7 +682,7 @@
void FloatValue::InternalSwap(FloatValue* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(value_, other->value_);
}
@@ -708,22 +699,15 @@
public:
};
-Int64Value::Int64Value()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Int64Value)
-}
Int64Value::Int64Value(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int64Value)
}
Int64Value::Int64Value(const Int64Value& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.Int64Value)
}
@@ -735,10 +719,11 @@
Int64Value::~Int64Value() {
// @@protoc_insertion_point(destructor:google.protobuf.Int64Value)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Int64Value::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void Int64Value::ArenaDtor(void* object) {
@@ -763,12 +748,12 @@
(void) cached_has_bits;
value_ = PROTOBUF_LONGLONG(0);
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Int64Value::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -777,7 +762,7 @@
// int64 value = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -787,7 +772,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -815,7 +802,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Int64Value)
return target;
@@ -863,7 +850,7 @@
void Int64Value::MergeFrom(const Int64Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Int64Value)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -892,7 +879,7 @@
void Int64Value::InternalSwap(Int64Value* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(value_, other->value_);
}
@@ -909,22 +896,15 @@
public:
};
-UInt64Value::UInt64Value()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.UInt64Value)
-}
UInt64Value::UInt64Value(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt64Value)
}
UInt64Value::UInt64Value(const UInt64Value& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.UInt64Value)
}
@@ -936,10 +916,11 @@
UInt64Value::~UInt64Value() {
// @@protoc_insertion_point(destructor:google.protobuf.UInt64Value)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void UInt64Value::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void UInt64Value::ArenaDtor(void* object) {
@@ -964,12 +945,12 @@
(void) cached_has_bits;
value_ = PROTOBUF_ULONGLONG(0);
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* UInt64Value::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -978,7 +959,7 @@
// uint64 value = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -988,7 +969,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1016,7 +999,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UInt64Value)
return target;
@@ -1064,7 +1047,7 @@
void UInt64Value::MergeFrom(const UInt64Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UInt64Value)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1093,7 +1076,7 @@
void UInt64Value::InternalSwap(UInt64Value* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(value_, other->value_);
}
@@ -1110,22 +1093,15 @@
public:
};
-Int32Value::Int32Value()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.Int32Value)
-}
Int32Value::Int32Value(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int32Value)
}
Int32Value::Int32Value(const Int32Value& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.Int32Value)
}
@@ -1137,10 +1113,11 @@
Int32Value::~Int32Value() {
// @@protoc_insertion_point(destructor:google.protobuf.Int32Value)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void Int32Value::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void Int32Value::ArenaDtor(void* object) {
@@ -1165,12 +1142,12 @@
(void) cached_has_bits;
value_ = 0;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* Int32Value::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1179,7 +1156,7 @@
// int32 value = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -1189,7 +1166,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1217,7 +1196,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Int32Value)
return target;
@@ -1265,7 +1244,7 @@
void Int32Value::MergeFrom(const Int32Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Int32Value)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1294,7 +1273,7 @@
void Int32Value::InternalSwap(Int32Value* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(value_, other->value_);
}
@@ -1311,22 +1290,15 @@
public:
};
-UInt32Value::UInt32Value()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.UInt32Value)
-}
UInt32Value::UInt32Value(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt32Value)
}
UInt32Value::UInt32Value(const UInt32Value& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.UInt32Value)
}
@@ -1338,10 +1310,11 @@
UInt32Value::~UInt32Value() {
// @@protoc_insertion_point(destructor:google.protobuf.UInt32Value)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void UInt32Value::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void UInt32Value::ArenaDtor(void* object) {
@@ -1366,12 +1339,12 @@
(void) cached_has_bits;
value_ = 0u;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* UInt32Value::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1380,7 +1353,7 @@
// uint32 value = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -1390,7 +1363,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1418,7 +1393,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UInt32Value)
return target;
@@ -1466,7 +1441,7 @@
void UInt32Value::MergeFrom(const UInt32Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UInt32Value)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1495,7 +1470,7 @@
void UInt32Value::InternalSwap(UInt32Value* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(value_, other->value_);
}
@@ -1512,22 +1487,15 @@
public:
};
-BoolValue::BoolValue()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.BoolValue)
-}
BoolValue::BoolValue(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BoolValue)
}
BoolValue::BoolValue(const BoolValue& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_ = from.value_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.BoolValue)
}
@@ -1539,10 +1507,11 @@
BoolValue::~BoolValue() {
// @@protoc_insertion_point(destructor:google.protobuf.BoolValue)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void BoolValue::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
}
void BoolValue::ArenaDtor(void* object) {
@@ -1567,12 +1536,12 @@
(void) cached_has_bits;
value_ = false;
- _internal_metadata_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* BoolValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1581,7 +1550,7 @@
// bool value = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
- value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
+ value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
@@ -1591,7 +1560,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1619,7 +1590,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.BoolValue)
return target;
@@ -1665,7 +1636,7 @@
void BoolValue::MergeFrom(const BoolValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.BoolValue)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1694,7 +1665,7 @@
void BoolValue::InternalSwap(BoolValue* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(value_, other->value_);
}
@@ -1711,26 +1682,19 @@
public:
};
-StringValue::StringValue()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.StringValue)
-}
StringValue::StringValue(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.StringValue)
}
StringValue::StringValue(const StringValue& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_value().empty()) {
value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_value(),
- GetArenaNoVirtual());
+ GetArena());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.StringValue)
}
@@ -1743,10 +1707,11 @@
StringValue::~StringValue() {
// @@protoc_insertion_point(destructor:google.protobuf.StringValue)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void StringValue::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
@@ -1771,13 +1736,13 @@
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- _internal_metadata_.Clear();
+ value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* StringValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -1798,7 +1763,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -1830,7 +1797,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.StringValue)
return target;
@@ -1878,7 +1845,7 @@
void StringValue::MergeFrom(const StringValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.StringValue)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -1907,9 +1874,8 @@
void StringValue::InternalSwap(StringValue* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
::PROTOBUF_NAMESPACE_ID::Metadata StringValue::GetMetadata() const {
@@ -1925,26 +1891,19 @@
public:
};
-BytesValue::BytesValue()
- : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
- SharedCtor();
- // @@protoc_insertion_point(constructor:google.protobuf.BytesValue)
-}
BytesValue::BytesValue(::PROTOBUF_NAMESPACE_ID::Arena* arena)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(arena) {
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BytesValue)
}
BytesValue::BytesValue(const BytesValue& from)
- : ::PROTOBUF_NAMESPACE_ID::Message(),
- _internal_metadata_(nullptr) {
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ : ::PROTOBUF_NAMESPACE_ID::Message() {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from._internal_value().empty()) {
value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_value(),
- GetArenaNoVirtual());
+ GetArena());
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.BytesValue)
}
@@ -1957,10 +1916,11 @@
BytesValue::~BytesValue() {
// @@protoc_insertion_point(destructor:google.protobuf.BytesValue)
SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void BytesValue::SharedDtor() {
- GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
+ GOOGLE_DCHECK(GetArena() == nullptr);
value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
@@ -1985,13 +1945,13 @@
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- _internal_metadata_.Clear();
+ value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* BytesValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
- ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
@@ -2011,7 +1971,9 @@
ctx->SetLastTag(tag);
goto success;
}
- ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
@@ -2039,7 +2001,7 @@
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
- _internal_metadata_.unknown_fields(), target, stream);
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.BytesValue)
return target;
@@ -2087,7 +2049,7 @@
void BytesValue::MergeFrom(const BytesValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.BytesValue)
GOOGLE_DCHECK_NE(&from, this);
- _internal_metadata_.MergeFrom(from._internal_metadata_);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -2116,9 +2078,8 @@
void BytesValue::InternalSwap(BytesValue* other) {
using std::swap;
- _internal_metadata_.Swap(&other->_internal_metadata_);
- value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
::PROTOBUF_NAMESPACE_ID::Metadata BytesValue::GetMetadata() const {
diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h
index 4ee66db..1baa8f2 100644
--- a/src/google/protobuf/wrappers.pb.h
+++ b/src/google/protobuf/wrappers.pb.h
@@ -8,12 +8,12 @@
#include <string>
#include <google/protobuf/port_def.inc>
-#if PROTOBUF_VERSION < 3011000
+#if PROTOBUF_VERSION < 3012000
#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 3011000 < PROTOBUF_MIN_PROTOC_VERSION
+#if 3012000 < 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.
@@ -26,7 +26,7 @@
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
-#include <google/protobuf/metadata.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -98,10 +98,10 @@
// ===================================================================
-class PROTOBUF_EXPORT DoubleValue :
+class PROTOBUF_EXPORT DoubleValue PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DoubleValue) */ {
public:
- DoubleValue();
+ inline DoubleValue() : DoubleValue(nullptr) {};
virtual ~DoubleValue();
DoubleValue(const DoubleValue& from);
@@ -115,7 +115,7 @@
return *this;
}
inline DoubleValue& operator=(DoubleValue&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -123,12 +123,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -153,7 +147,7 @@
}
inline void Swap(DoubleValue* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -161,7 +155,7 @@
}
void UnsafeArenaSwap(DoubleValue* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -201,13 +195,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -239,7 +226,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -249,10 +235,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT FloatValue :
+class PROTOBUF_EXPORT FloatValue PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FloatValue) */ {
public:
- FloatValue();
+ inline FloatValue() : FloatValue(nullptr) {};
virtual ~FloatValue();
FloatValue(const FloatValue& from);
@@ -266,7 +252,7 @@
return *this;
}
inline FloatValue& operator=(FloatValue&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -274,12 +260,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -304,7 +284,7 @@
}
inline void Swap(FloatValue* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -312,7 +292,7 @@
}
void UnsafeArenaSwap(FloatValue* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -352,13 +332,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -390,7 +363,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -400,10 +372,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Int64Value :
+class PROTOBUF_EXPORT Int64Value PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int64Value) */ {
public:
- Int64Value();
+ inline Int64Value() : Int64Value(nullptr) {};
virtual ~Int64Value();
Int64Value(const Int64Value& from);
@@ -417,7 +389,7 @@
return *this;
}
inline Int64Value& operator=(Int64Value&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -425,12 +397,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -455,7 +421,7 @@
}
inline void Swap(Int64Value* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -463,7 +429,7 @@
}
void UnsafeArenaSwap(Int64Value* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -503,13 +469,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -541,7 +500,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -551,10 +509,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT UInt64Value :
+class PROTOBUF_EXPORT UInt64Value PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt64Value) */ {
public:
- UInt64Value();
+ inline UInt64Value() : UInt64Value(nullptr) {};
virtual ~UInt64Value();
UInt64Value(const UInt64Value& from);
@@ -568,7 +526,7 @@
return *this;
}
inline UInt64Value& operator=(UInt64Value&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -576,12 +534,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -606,7 +558,7 @@
}
inline void Swap(UInt64Value* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -614,7 +566,7 @@
}
void UnsafeArenaSwap(UInt64Value* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -654,13 +606,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -692,7 +637,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -702,10 +646,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT Int32Value :
+class PROTOBUF_EXPORT Int32Value PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int32Value) */ {
public:
- Int32Value();
+ inline Int32Value() : Int32Value(nullptr) {};
virtual ~Int32Value();
Int32Value(const Int32Value& from);
@@ -719,7 +663,7 @@
return *this;
}
inline Int32Value& operator=(Int32Value&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -727,12 +671,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -757,7 +695,7 @@
}
inline void Swap(Int32Value* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -765,7 +703,7 @@
}
void UnsafeArenaSwap(Int32Value* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -805,13 +743,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -843,7 +774,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -853,10 +783,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT UInt32Value :
+class PROTOBUF_EXPORT UInt32Value PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt32Value) */ {
public:
- UInt32Value();
+ inline UInt32Value() : UInt32Value(nullptr) {};
virtual ~UInt32Value();
UInt32Value(const UInt32Value& from);
@@ -870,7 +800,7 @@
return *this;
}
inline UInt32Value& operator=(UInt32Value&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -878,12 +808,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -908,7 +832,7 @@
}
inline void Swap(UInt32Value* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -916,7 +840,7 @@
}
void UnsafeArenaSwap(UInt32Value* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -956,13 +880,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -994,7 +911,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1004,10 +920,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT BoolValue :
+class PROTOBUF_EXPORT BoolValue PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BoolValue) */ {
public:
- BoolValue();
+ inline BoolValue() : BoolValue(nullptr) {};
virtual ~BoolValue();
BoolValue(const BoolValue& from);
@@ -1021,7 +937,7 @@
return *this;
}
inline BoolValue& operator=(BoolValue&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1029,12 +945,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1059,7 +969,7 @@
}
inline void Swap(BoolValue* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1067,7 +977,7 @@
}
void UnsafeArenaSwap(BoolValue* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1107,13 +1017,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1145,7 +1048,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1155,10 +1057,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT StringValue :
+class PROTOBUF_EXPORT StringValue PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.StringValue) */ {
public:
- StringValue();
+ inline StringValue() : StringValue(nullptr) {};
virtual ~StringValue();
StringValue(const StringValue& from);
@@ -1172,7 +1074,7 @@
return *this;
}
inline StringValue& operator=(StringValue&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1180,12 +1082,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1210,7 +1106,7 @@
}
inline void Swap(StringValue* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1218,7 +1114,7 @@
}
void UnsafeArenaSwap(StringValue* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1258,13 +1154,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1312,7 +1201,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1322,10 +1210,10 @@
};
// -------------------------------------------------------------------
-class PROTOBUF_EXPORT BytesValue :
+class PROTOBUF_EXPORT BytesValue PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BytesValue) */ {
public:
- BytesValue();
+ inline BytesValue() : BytesValue(nullptr) {};
virtual ~BytesValue();
BytesValue(const BytesValue& from);
@@ -1339,7 +1227,7 @@
return *this;
}
inline BytesValue& operator=(BytesValue&& from) noexcept {
- if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
+ if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
@@ -1347,12 +1235,6 @@
return *this;
}
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
- return GetArenaNoVirtual();
- }
- inline void* GetMaybeArenaPointer() const final {
- return MaybeArenaPtr();
- }
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
@@ -1377,7 +1259,7 @@
}
inline void Swap(BytesValue* other) {
if (other == this) return;
- if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
@@ -1385,7 +1267,7 @@
}
void UnsafeArenaSwap(BytesValue* other) {
if (other == this) return;
- GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
@@ -1425,13 +1307,6 @@
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
- private:
- inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
- return _internal_metadata_.arena();
- }
- inline void* MaybeArenaPtr() const {
- return _internal_metadata_.raw_arena_ptr();
- }
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
@@ -1479,7 +1354,6 @@
private:
class _Internal;
- ::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
@@ -1668,7 +1542,7 @@
// string value = 1;
inline void StringValue::clear_value() {
- value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& StringValue::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.StringValue.value)
@@ -1687,36 +1561,35 @@
}
inline void StringValue::_internal_set_value(const std::string& value) {
- value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void StringValue::set_value(std::string&& value) {
value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.StringValue.value)
}
inline void StringValue::set_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.StringValue.value)
}
inline void StringValue::set_value(const char* value,
size_t size) {
value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.StringValue.value)
}
inline std::string* StringValue::_internal_mutable_value() {
- return value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* StringValue::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.StringValue.value)
-
- return value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void StringValue::set_allocated_value(std::string* value) {
if (value != nullptr) {
@@ -1725,26 +1598,26 @@
}
value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.StringValue.value)
}
inline std::string* StringValue::unsafe_arena_release_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.StringValue.value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void StringValue::unsafe_arena_set_allocated_value(
std::string* value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (value != nullptr) {
} else {
}
value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- value, GetArenaNoVirtual());
+ value, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.StringValue.value)
}
@@ -1754,7 +1627,7 @@
// bytes value = 1;
inline void BytesValue::clear_value() {
- value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ value_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline const std::string& BytesValue::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.BytesValue.value)
@@ -1773,36 +1646,35 @@
}
inline void BytesValue::_internal_set_value(const std::string& value) {
- value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
+ value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
}
inline void BytesValue::set_value(std::string&& value) {
value_.Set(
- &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.BytesValue.value)
}
inline void BytesValue::set_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_char:google.protobuf.BytesValue.value)
}
inline void BytesValue::set_value(const void* value,
size_t size) {
value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
+ reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.BytesValue.value)
}
inline std::string* BytesValue::_internal_mutable_value() {
- return value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return value_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline std::string* BytesValue::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.BytesValue.value)
-
- return value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ return value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void BytesValue::set_allocated_value(std::string* value) {
if (value != nullptr) {
@@ -1811,26 +1683,26 @@
}
value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value,
- GetArenaNoVirtual());
+ GetArena());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.BytesValue.value)
}
inline std::string* BytesValue::unsafe_arena_release_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.BytesValue.value)
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
return value_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- GetArenaNoVirtual());
+ GetArena());
}
inline void BytesValue::unsafe_arena_set_allocated_value(
std::string* value) {
- GOOGLE_DCHECK(GetArenaNoVirtual() != nullptr);
+ GOOGLE_DCHECK(GetArena() != nullptr);
if (value != nullptr) {
} else {
}
value_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
- value, GetArenaNoVirtual());
+ value, GetArena());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.BytesValue.value)
}
diff --git a/tests.sh b/tests.sh
index abe184b..0f8e10c 100755
--- a/tests.sh
+++ b/tests.sh
@@ -63,7 +63,8 @@
# List all files that should be included in the distribution package.
git ls-files | grep "^\(java\|python\|objectivec\|csharp\|js\|ruby\|php\|cmake\|examples\|src/google/protobuf/.*\.proto\)" |\
grep -v ".gitignore" | grep -v "java/compatibility_tests" | grep -v "java/lite/proguard.pgcfg" |\
- grep -v "python/compatibility_tests" | grep -v "csharp/compatibility_tests" > dist.lst
+ grep -v "python/compatibility_tests" | grep -v "python/docs" | grep -v "python/.repo-metadata.json" |\
+ grep -v "csharp/compatibility_tests" > dist.lst
# Unzip the dist tar file.
DIST=`ls *.tar.gz`
tar -xf $DIST
@@ -162,10 +163,13 @@
export GOPATH="$HOME/gocode"
mkdir -p "$GOPATH/src/github.com/protocolbuffers"
+ mkdir -p "$GOPATH/src/github.com/golang"
rm -f "$GOPATH/src/github.com/protocolbuffers/protobuf"
+ rm -f "$GOPATH/src/github.com/golang/protobuf"
ln -s "`pwd`" "$GOPATH/src/github.com/protocolbuffers/protobuf"
export PATH="$GOPATH/bin:$PATH"
- go get github.com/golang/protobuf/protoc-gen-go
+ (cd $GOPATH/src/github.com/golang && git clone https://github.com/golang/protobuf.git && cd protobuf && git checkout v1.3.5)
+ go install github.com/golang/protobuf/protoc-gen-go
cd examples && PROTO_PATH="-I../src -I." make gotest && cd ..
}
@@ -195,7 +199,7 @@
$MVN -version
}
-# --batch-mode supresses download progress output that spams the logs.
+# --batch-mode suppresses download progress output that spams the logs.
MVN="mvn --batch-mode"
build_java() {
@@ -233,7 +237,7 @@
build_java_compatibility() {
use_java jdk7
internal_build_cpp
- # Use the unit-tests extraced from 2.5.0 to test the compatibilty between
+ # Use the unit-tests extracted from 2.5.0 to test the compatibility between
# 3.0.0-beta-4 and the current version.
cd java/compatibility_tests/v2.5.0
./test.sh 3.0.0-beta-4
@@ -251,16 +255,6 @@
# Linkage Monitor uses $HOME/.m2 local repository
MVN="mvn -e -B -Dhttps.protocols=TLSv1.2"
cd java
- # Sets java artifact version with SNAPSHOT, as Linkage Monitor looks for SNAPSHOT versions.
- # Example: "3.9.0" (without 'rc')
- VERSION=`grep '<version>' pom.xml |head -1 |perl -nle 'print $1 if m/<version>(\d+\.\d+.\d+)/'`
- cd bom
- # This local installation avoids the problem caused by a new version not yet in Maven Central
- # https://github.com/protocolbuffers/protobuf/issues/6627
- $MVN install
- $MVN versions:set -DnewVersion=${VERSION}-SNAPSHOT
- cd ..
- $MVN versions:set -DnewVersion=${VERSION}-SNAPSHOT
# Installs the snapshot version locally
$MVN install -Dmaven.test.skip=true
@@ -360,6 +354,10 @@
build_python_version py37-python
}
+build_python38() {
+ build_python_version py38-python
+}
+
build_python_cpp() {
internal_build_cpp
export LD_LIBRARY_PATH=../src/.libs # for Linux
@@ -408,9 +406,13 @@
build_python_cpp_version py37-cpp
}
+build_python38_cpp() {
+ build_python_cpp_version py38-cpp
+}
+
build_python_compatibility() {
internal_build_cpp
- # Use the unit-tests extraced from 2.5.0 to test the compatibilty.
+ # Use the unit-tests extracted from 2.5.0 to test the compatibility.
cd python/compatibility_tests/v2.5.0
# Test between 2.5.0 and the current version.
./test.sh 2.5.0
@@ -437,6 +439,10 @@
internal_build_cpp # For conformance tests.
cd ruby && bash travis-test.sh ruby-2.6.0 && cd ..
}
+build_ruby27() {
+ internal_build_cpp # For conformance tests.
+ cd ruby && bash travis-test.sh ruby-2.7.0 && cd ..
+}
build_javascript() {
internal_build_cpp
@@ -514,14 +520,19 @@
}
build_php5.5_c() {
+ IS_64BIT=$1
use_php 5.5
pushd php/tests
/bin/bash ./test.sh 5.5
popd
- # TODO(teboring): Add it back
- # pushd conformance
- # make test_php_c
- # popd
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
}
build_php5.5_mixed() {
@@ -529,18 +540,25 @@
pushd php
rm -rf vendor
composer update
- /bin/bash ./tests/compile_extension.sh ./ext/google/protobuf
+ pushd tests
+ /bin/bash ./compile_extension.sh 5.5
+ popd
php -dextension=./ext/google/protobuf/modules/protobuf.so ./vendor/bin/phpunit
popd
}
build_php5.5_zts_c() {
+ IS_64BIT=$1
use_php_zts 5.5
cd php/tests && /bin/bash ./test.sh 5.5-zts && cd ../..
- # TODO(teboring): Add it back
- # pushd conformance
- # make test_php_zts_c
- # popd
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
}
build_php5.6() {
@@ -556,12 +574,17 @@
}
build_php5.6_c() {
+ IS_64BIT=$1
use_php 5.6
cd php/tests && /bin/bash ./test.sh 5.6 && cd ../..
- # TODO(teboring): Add it back
- # pushd conformance
- # make test_php_c
- # popd
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
}
build_php5.6_mixed() {
@@ -569,18 +592,25 @@
pushd php
rm -rf vendor
composer update
- /bin/bash ./tests/compile_extension.sh ./ext/google/protobuf
+ pushd tests
+ /bin/bash ./compile_extension.sh 5.6
+ popd
php -dextension=./ext/google/protobuf/modules/protobuf.so ./vendor/bin/phpunit
popd
}
build_php5.6_zts_c() {
+ IS_64BIT=$1
use_php_zts 5.6
cd php/tests && /bin/bash ./test.sh 5.6-zts && cd ../..
- # TODO(teboring): Add it back
- # pushd conformance
- # make test_php_zts_c
- # popd
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
}
build_php5.6_mac() {
@@ -602,10 +632,9 @@
# Test
cd php/tests && /bin/bash ./test.sh && cd ../..
- # TODO(teboring): Add it back
- # pushd conformance
- # make test_php_c
- # popd
+ pushd conformance
+ make test_php_c
+ popd
}
build_php7.0() {
@@ -621,12 +650,17 @@
}
build_php7.0_c() {
+ IS_64BIT=$1
use_php 7.0
cd php/tests && /bin/bash ./test.sh 7.0 && cd ../..
- # TODO(teboring): Add it back
- # pushd conformance
- # make test_php_c
- # popd
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
}
build_php7.0_mixed() {
@@ -634,18 +668,25 @@
pushd php
rm -rf vendor
composer update
- /bin/bash ./tests/compile_extension.sh ./ext/google/protobuf
+ pushd tests
+ /bin/bash ./compile_extension.sh 7.0
+ popd
php -dextension=./ext/google/protobuf/modules/protobuf.so ./vendor/bin/phpunit
popd
}
build_php7.0_zts_c() {
+ IS_64BIT=$1
use_php_zts 7.0
cd php/tests && /bin/bash ./test.sh 7.0-zts && cd ../..
- # TODO(teboring): Add it back.
- # pushd conformance
- # make test_php_zts_c
- # popd
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
}
build_php7.0_mac() {
@@ -667,10 +708,33 @@
# Test
cd php/tests && /bin/bash ./test.sh && cd ../..
- # TODO(teboring): Add it back
- # pushd conformance
- # make test_php_c
- # popd
+ pushd conformance
+ make test_php_c
+ popd
+}
+
+build_php7.4_mac() {
+ generate_php_test_proto
+ # Install PHP
+ curl -s https://php-osx.liip.ch/install.sh | bash -s 7.4
+ PHP_FOLDER=`find /usr/local -type d -name "php7-7.4*"` # The folder name may change upon time
+ export PATH="$PHP_FOLDER/bin:$PATH"
+
+ # Install phpunit
+ curl https://phar.phpunit.de/phpunit-8.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 ../..
+ pushd conformance
+ make test_php_c
+ popd
}
build_php_compatibility() {
@@ -678,6 +742,13 @@
php/tests/compatibility_test.sh $LAST_RELEASED
}
+build_php_multirequest() {
+ use_php 7.4
+ pushd php/tests
+ ./multirequest.sh
+ popd
+}
+
build_php7.1() {
use_php 7.1
pushd php
@@ -691,15 +762,17 @@
}
build_php7.1_c() {
- ENABLE_CONFORMANCE_TEST=$1
+ IS_64BIT=$1
use_php 7.1
cd php/tests && /bin/bash ./test.sh 7.1 && cd ../..
- if [ "$ENABLE_CONFORMANCE_TEST" = "true" ]
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
then
- pushd conformance
make test_php_c
- popd
+ else
+ make test_php_c_32
fi
+ popd
}
build_php7.1_mixed() {
@@ -707,16 +780,85 @@
pushd php
rm -rf vendor
composer update
- /bin/bash ./tests/compile_extension.sh ./ext/google/protobuf
+ pushd tests
+ /bin/bash ./compile_extension.sh 7.1
+ popd
php -dextension=./ext/google/protobuf/modules/protobuf.so ./vendor/bin/phpunit
popd
}
build_php7.1_zts_c() {
+ IS_64BIT=$1
use_php_zts 7.1
cd php/tests && /bin/bash ./test.sh 7.1-zts && cd ../..
pushd conformance
- # make test_php_c
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
+}
+
+build_php7.4() {
+ use_php 7.4
+ pushd php
+ rm -rf vendor
+ composer update
+ ./vendor/bin/phpunit
+ popd
+ pushd conformance
+ make test_php
+ popd
+}
+
+build_php7.4_c() {
+ IS_64BIT=$1
+ use_php 7.4
+ cd php/tests && /bin/bash ./test.sh 7.4 && cd ../..
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
+ pushd php/ext/google/protobuf
+ phpize --clean
+ popd
+}
+
+build_php7.4_mixed() {
+ use_php 7.4
+ pushd php
+ rm -rf vendor
+ composer update
+ pushd tests
+ /bin/bash ./compile_extension.sh 7.4
+ popd
+ php -dextension=./ext/google/protobuf/modules/protobuf.so ./vendor/bin/phpunit
+ popd
+ pushd php/ext/google/protobuf
+ phpize --clean
+ popd
+}
+
+build_php7.4_zts_c() {
+ IS_64BIT=$1
+ use_php_zts 7.4
+ cd php/tests && /bin/bash ./test.sh 7.4-zts && cd ../..
+ pushd conformance
+ if [ "$IS_64BIT" = "true" ]
+ then
+ make test_php_c
+ else
+ make test_php_c_32
+ fi
+ popd
+ pushd php/ext/google/protobuf
+ phpize --clean
popd
}
@@ -725,22 +867,27 @@
build_php5.6
build_php7.0
build_php7.1
- build_php5.5_c
- build_php5.6_c
- build_php7.0_c
+ build_php7.4
+ build_php5.5_c $1
+ build_php5.6_c $1
+ build_php7.0_c $1
build_php7.1_c $1
+ build_php7.4_c $1
build_php5.5_mixed
build_php5.6_mixed
build_php7.0_mixed
build_php7.1_mixed
- build_php5.5_zts_c
- build_php5.6_zts_c
- build_php7.0_zts_c
- build_php7.1_zts_c
+ build_php7.4_mixed
+ build_php5.5_zts_c $1
+ build_php5.6_zts_c $1
+ build_php7.0_zts_c $1
+ build_php7.1_zts_c $1
+ build_php7.4_zts_c $1
}
build_php_all() {
build_php_all_32 true
+ build_php_multirequest
build_php_compatibility
}
@@ -775,6 +922,7 @@
ruby24 |
ruby25 |
ruby26 |
+ ruby27 |
jruby |
ruby_all |
php5.5 |
diff --git a/update_compatibility_version.py b/update_compatibility_version.py
old mode 100644
new mode 100755